blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
6ffba84aafcdb3a4491c8268cba8ea1e2adfdf1e
|
JapoDeveloper/think-python
|
/exercises/chapter6/exercise_6_2.py
| 951 | 4.3125 | 4 |
"""
Think Python, 2nd Edition
Chapter 6
Exercise 6.2
Description:
The Ackermann function, A(m,n), is defined:
n + 1 if m = 0
A(m,n) = A(m-1, 1) if m > 0 and n = 0
A(m-1, A(m,n-1)) if m > 0 and n > 0
See http://en.wikipedia.org/wiki/Ackermann_function.
Write a function named ack that evaluates the Ackermann function.
Use your function to evaluate ack(3, 4), which should be 125.
What happens for larger values of m and n?
"""
def ack(m, n):
if m < 0 or n < 0:
print('ack function called with invalid input, only positive integers are valid')
return
elif m == 0:
return n + 1
elif n == 0:
return ack(m-1, 1)
else:
return ack(m-1, ack(m, n-1))
print(ack(3, 4)) # 125
print(ack(1, 2)) # 4
print(ack(4, 3)) # RecursionError
# For larger values of m and n python can proceed the operation because
# the number of allow recursion call is exceeded
|
508a885f71292a801877616a7e8132902d1af6c5
|
JapoDeveloper/think-python
|
/exercises/chapter6/exercise_6_4.py
| 643 | 4.3125 | 4 |
"""
Think Python, 2nd Edition
Chapter 6
Exercise 6.4
Description:
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b and returns True
if a is a power of b. Note: you will have to think about the base case.
"""
def is_power(a, b):
"""Check if a integer 'a' is a power of a integer 'b'"""
if a == 1 or a == b: # base case
return True
elif a % b != 0:
return False
else:
return is_power(a / b, b)
print(is_power(2,2)) # True
print(is_power(1,2)) # True
print(is_power(8,2)) # True
print(is_power(9,2)) # False
|
125124731c5b0b32448eb2ffd2a144ec826cecdb
|
DDDlyk/learningpython
|
/01_Python基础/07_买苹果增强.py
| 249 | 3.96875 | 4 |
# 1. 输入苹果单价
price_str = input("苹果的单价:")
# 2. 输入苹果重量
weight_str = input("苹果的重量:")
# 3. 计算支付的总金额
price = float(price_str)
weight = float(weight_str)
money = price * weight
print(money)
|
1f6ff08de38c7d153a37dc5a821d91613150a6f5
|
DDDlyk/learningpython
|
/02_分支/01_判断年龄.py
| 290 | 3.984375 | 4 |
# 1. 定义一个整数变量记录年龄
age = 23
# 2. 判断是否满了18岁
if age >= 18:
# 3. 如果满了18岁,可以进网吧嗨皮
print("你已经成年,欢迎进网吧嗨皮")
else:
print("未满18岁,请回吧,施主")
print("看看什么时候会执行")
|
643e110affedc0b55ab47ef462c743ec2e8cea50
|
DDDlyk/learningpython
|
/network/15_循环为多个客户端服务并且多次服务一个客户端.py
| 1,774 | 3.75 | 4 |
import socket
def main():
# 1.买个手机(创建套接字)
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2.插入手机卡(绑定本地信息)
tcp_server_socket.bind(("", 7788))
# 3.将手机设置为正常的响铃模式(让默认的套接字由主动变为被动 listen)
tcp_server_socket.listen(128)
# 这个while true循环为多个客户端服务
while True:
print("等待一个新的客户端的到来:")
# 4.等待别人的电话到来(等待客户端的连接 accept)
new_client_socket, client_addr = tcp_server_socket.accept()
# print("-----2-----")
print("一个新的客户端已经到来%s" % str(client_addr))
# 这个while true循环多次为一个客户端多次服务
while True:
# 接收客户端发送过来的请求
recv_data = new_client_socket.recv(1024)
print("客户端发送过来的请求是:%s " % recv_data.decode("gbk"))
# 如果receive解堵塞,那么有两种方式:
# 1.客户端发送过来数据
# 2.客户端调用close导致了这里recv解堵塞
if recv_data:
# 回送一部分数据给客户端
new_client_socket.send("嘻嘻嘻".encode("gbk"))
else:
break
# 关闭套接字
# 关闭accept返回的套接字,意味着不会再为这个客户端服务
new_client_socket.close()
print("已经服务器完毕。。。")
# 如果将监听套接字关闭了,那么会导致不能再次等待新客户端的到来,及xxx.accept会失败
tcp_server_socket.close()
if __name__ == '__main__':
main()
|
9d89589c9137605389db181b0414240dc963f4c2
|
DDDlyk/learningpython
|
/08_面向对象/ddd_16_士兵突击_03_士兵开火.py
| 1,212 | 3.703125 | 4 |
class Gun:
def __init__(self, model):
# 1.抢的型号
self.model = model
# 2.子弹的数量
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
# 1.判断子弹数量
if self.bullet_count <= 0:
print ("[%s]没有子弹了..." % self.model)
return
# 2.发射子弹,-1
self.bullet_count -= 1
# 3.提示发射信息
print ("[%s] 突突突... [%d]" % (self.model, self.bullet_count))
class Soldiers:
def __init__(self, name):
# 1.新兵的姓名
self.name = name
# 2.枪
self.gun = None
def fire(self):
# 1.判断士兵是否有枪
if self.gun is None:
print ("[%s] 还没有枪" % self.name)
return
# 2.高喊口号
print ("冲啊...[%s]" % self.name)
# 3.让枪装填子弹
self.gun.add_bullet(50)
# 4.让枪发射子弹
self.gun.shoot()
# 1.创建抢对象
ak47 = Gun("ak47")
# 2.创建许三多
xusanduo = Soldiers("许三多")
# xusanduo.gun = ak47
xusanduo.fire()
print (xusanduo.gun)
|
8568a51f56ca37c1d25411e07c8047bd5f345268
|
DDDlyk/learningpython
|
/07_语法进阶/ddd_20_递归求和.py
| 270 | 3.75 | 4 |
def sum_numbers(num):
# 1.出口
if num == 1:
return 1
# 2. 数字的累加 num +(1....num - 1)
# 假设 sum_numbers能够正确处理1....num-1
temp = sum_numbers(num-1)
return num + temp
result = sum_numbers(100)
print(result)
|
8c5faf13fe2952f33dd45000bf56e87bd1a0747e
|
Shubham1304/Semester6
|
/ClassPython/4.py
| 711 | 4.21875 | 4 |
#31st January class
#string operations
s='hello'
print (s.index('o')) #exception if not found
#s.find('a') return -1 if not found
#------------------check valid name-------------------------------------------------------------------------------------
s=''
s=input("Enter the string")
if(s.isalpha()):
print ("Valid name")
else :
print ("Not a valid name")
#--------------------check a palindrome----------------------------------------------------------------------------------
s=input ("Enter a number")
r=s[::-1]
if r==s:
print ("It is a palindrome")
else:
print("It is not a palindrome")
s='abba'
print (s.index('a'))
s = input ("Enter the string")
while i<len(s):
if (s.isdigit()):
if(
|
f6623a49a565eb677d0e43fff9e717d081d6b0a4
|
saahil1292/fsdse-python-assignment-7
|
/prime_numbers.py
| 280 | 3.625 | 4 |
def get_prime_numbers(n):
prime_numbers = []
for num1 in range(2,n+1):
for num2 in range(2, num1):
if (num1 % num2 == 0):
break;
else:
prime_numbers.append(num1)
return prime_numbers
n = 20
get_prime_numbers(n)
|
4dac98267bf7d419c085190c2540c32ef54ea430
|
anivanchen/stuycs-classlist
|
/getClass.py
| 976 | 3.53125 | 4 |
import requests
from bs4 import BeautifulSoup
print("Enter your teacher's name in the format firstInitialLastName. Example: dholmes")
teacherName = str(input('Teacher Name (ex. dholmes): '))
print("Enter your term name in the format [fall/spring]year. Example: fall2021")
term = str(input("Enter the term (fall2021): "))
url = 'http://bert.stuy.edu/{}/{}/pages.py?page=submit_homework'.format(teacherName, term)
page = requests.get(url)
substring = ''
soup = BeautifulSoup(page.content, 'html.parser')
script = soup.find('script').string.split(' ++i)', 1)[0].split(';')
for line in script:
if 'students[' in line:
start = line.find('"') + len('"')
end = line.find('|')
period = line[start:end]
start = line.replace('|', '', 1).find('|') + len('|')
end = line.replace('"', '', 1).find('"')
name = line[start+1:end+1]
substring = substring + period + ' | ' + name + '\n'
file = open('ClassList.txt', 'w')
file.write(substring)
file.close()
|
b896f3577f80daaf46e56a70b046aecacf2288cb
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/17.py
| 718 | 4.375 | 4 |
'''
Write a version of a palindrome recognizer that also accepts phrase palindromes such as
"Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis",
"Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori",
"Rise to vote sir", or the exclamation "Dammit, I'm mad!".
Note that punctuation, capitalization, and spacing are usually ignored.
'''
def palindrome(x):
l=[]
for i in x:
if i.isalpha():
l.append(i.lower())
print ''.join(l)
if l==l[::-1]:
print 'palindrome'
else:
print 'Not a palindrome'
palindrome("Go hang a salami I'm a lasagna hog.")
|
9b2ff0337869bc9125c8134ca93e43b33262488b
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/42.py
| 2,350 | 3.921875 | 4 |
'''
A sentence splitter is a program capable of splitting a text into sentences.
The standard set of heuristics for sentence splitting includes (but isn't limited to) the following rules:
Sentence boundaries occur at one of "." (periods), "?" or "!", except that
1. Periods followed by whitespace followed by a lower case letter are not sentence boundaries.
2. Periods followed by a digit with no intervening whitespace are not sentence boundaries.
3. Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries.
Sample titles include Mr., Mrs., Dr., and so on.
4 Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries
(for example, www.aptex.com, or e.g).
5. Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries.
Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line.
Test your program with the following short text:
Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind?
Adam Jones Jr. thinks he didn't. In any case, this isn't true... Well, with a probability of .9 it isn't.
The result should be:
Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it.
Did he mind?
Adam Jones Jr. thinks he didn't.
In any case, this isn't true...
Well, with a probability of .9 it isn't.
'''
import re
text = "Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. \
Did he mind? Adam Jones Jr. thinks he didn't. In any case, \
this isn't true... Well, with a probability of .9 it isn't."
# Method 1
for i in re.findall(r'[A-Z][a-z]+\.?.*?[.?!](?= [A-Z]|$)', text):
print i
print '*'*80
#Method 2 - using verbose mode.
for i in re.findall(r'''
[A-Z][a-z]+\.? # Starts with Capital includes (Mr., Mrs.)
.*? # followed by anything
[.?!] # ends with a (.)(?)(!)
(?=\s[A-Z]|$) # is followed by whitespace and a capital letter
''', text, re.X):
print i
print '*'*80
#Method 3
for i in re.split(r'(?<=[^Mr|Mrs|Dr][.?!])\s(?=[A-Z])', text):
print i
|
e7cba5438a771a16987ca6f1bf55a7f8bd0e160d
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/45.py
| 4,064 | 3.578125 | 4 |
'''
A certain childrens game involves starting with a word in a particular category. Each participant in
turn says a word, but that word must begin with the final letter of the previous word.
Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category,
they fall out of the game. For example, with "animals" as the category,
Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
Your task in this exercise is as follows: Take the following selection of 70 English Pokemon names
(extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible
number of Pokemon names where the subsequent name starts with the final letter of the preceding name.
No Pokemon name is to be repeated.
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
'''
from collections import defaultdict
import time
pokemon = '''audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask'''.split()
# Method 1
def find(chain):
last_character = chain[-1][-1]
options = d[last_character] - set(chain)
if not options:
return chain
else:
return max( (find(chain+[i]) for i in options), key=len)
start = time.clock()
d = defaultdict(set)
for word in pokemon:
d[word[0]].add(word)
print max( (find([word]) for word in pokemon), key=len)
end = time.clock()
print end - start
# Method 2 try bottom down approach
def find2(chain):
first_character = chain[0][0]
options = d[first_character] -set(chain)
if not options:
return chain
else:
return max( (find2([i]+ chain) for i in options), key=len)
start = time.clock()
d = defaultdict(set)
for word in pokemon:
d[word[-1]].add(word)
print max( (find2([word]) for word in pokemon), key=len)
end = time.clock()
print end - start
# Method 3 - Using loop instead of generator expression
def find(chain):
l=[]
last_character = chain[-1][-1]
options = d[last_character] - set(chain)
if not options:
return chain
else:
for i in options:
l.append(find(chain+[i]))
return max(l, key=len)
#return [ find(chain+[i]) f=or i in options]
pokemon = set(pokemon)
d = defaultdict(set)
for word in pokemon:
d[word[0]].add(word)
print max( [find([word]) for word in pokemon], key=len)
# Just try it out to have a better understanding how return plays an important role in recursion
def find(chain):
last_character = chain[-1][-1]
options = d[last_character] - set(chain)
if not options:
return chain
else:
for i in options:
find(chain+[i])
#to understand importance of return, here once we are in else block nothing is returned
pokemon = set(pokemon)
d = defaultdict(set)
for word in pokemon:
d[word[0]].add(word)
print [find([word]) for word in pokemon]
|
52419c3a1ddf2587d2d6d771351be6d380a78650
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/06.py
| 430 | 3.9375 | 4 |
'''
Define a function sum() and a function multiply() that sums and multiplies
(respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4])
should return 10, and multiply([1, 2, 3, 4]) should return 24.
'''
def sum1(x):
c=0
for i in x:
c += i
return c
print sum1([1, 2, 3, 4])
def multiply(x):
c=1
for i in x:
c *= i
return c
print multiply([1, 2, 3, 4])
|
f18204d3dab48280b29808613a3e039eab72ec4b
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/22.py
| 2,488 | 4.125 | 4 |
'''
In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a
letter some fixed number of positions down the alphabet. For example,
with a shift of 3, A would be replaced by D, B would become E, and so on.
The method is named after Julius Caesar, who used it to communicate with his generals.
ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13.
In Python, the key for ROT-13 may be represented by means of the following dictionary:
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
Your task in this exercise is to implement an encoder/decoder of ROT-13.
Once you're done, you will be able to read the following secret message:
Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English.
'''
def rot_decoder(x):
new =[]
d = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
for i in x:
new.append(d.get(i,i))
print ''.join(new)
rot_decoder('Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!')
# Our decoder function can also encode the message since we have 26 characters. But in case if isn't you can use below strategy.
def rot_encoder(x):
key_inverse = { v:k for k,v in d.items()}
for i in x:
new.append(d.get(i,i))
print ''.join(new)
rot_decoder('Caesar cipher? I much prefer Caesar salad!')
|
40589034a276810b9b22c31ca519399df66bd712
|
sukirt01/Python-for-Beginners-Solve-50-Exercises-Live
|
/02.py
| 277 | 4.125 | 4 |
'''
Define a function max_of_three() that takes three numbers as
arguments and returns the largest of them.
'''
def max_of_three(a,b,c):
if a>b and a>c:
print a
elif b>c and b>a:
print b
else:
print c
print max_of_three(0,15,2)
|
2c90729cf624a34ca2c7a6a4f1afe63fe4bba7a7
|
Isonzo/100-day-python-challenge
|
/Day 1/day 1.4 exercise.py
| 249 | 3.90625 | 4 |
#Don't change code below!
a = input("a: ")
b = input("b: ")
#Don't change code above!
#Switch a and b variables
c = a
a = b
b = c
#Don't change code below!
print("a = " + a)
print("b = " + b)
#Don't change code above!
|
728b7a20adbaf507242e6a090a0d19a403c01fda
|
Isonzo/100-day-python-challenge
|
/Day 9/silent_auction.py
| 918 | 3.59375 | 4 |
import os
from silent_auction_art import logo
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
auction_record = {}
def check_highest_bidder(auction_record):
highest_bid = 0
for bidder in auction_record:
bid_amount = auction_record[bidder]
if bid_amount > highest_bid:
highest_bid = bid_amount
winner = bidder
print(f"Highest bidder was {winner} at ${highest_bid}.")
end_of_auction = False
print(logo)
print("Welcome to the secret auction!")
while not end_of_auction:
name = input("\nInput your name: ")
bid = int(input("\nInput your bid: $"))
auction_record[name] = bid
decision = input("\nAre there more bidders? (type yes or no)\n").lower()
if decision == "no":
end_of_auction = True
clear()
check_highest_bidder(auction_record)
clear()
|
5de58b512ac999c7df3c3f76ab1aaa7289ed1ef5
|
Isonzo/100-day-python-challenge
|
/Day 32/main.py
| 1,243 | 3.65625 | 4 |
import pandas as pd
import datetime as dt
import random
import smtplib
my_email = "isonzo@gmail.com"
password = "not_going_to_put_my_password"
# Extra Hard Starting Project ######################
# 1. Update the birthdays.csv
data = pd.read_csv("birthdays.csv")
birthdays = data.to_dict(orient="records")
now = dt.datetime.now()
# 2. Check if today matches a birthday in the birthdays.csv
for birthday in birthdays:
if now.month == birthday["month"] and now.day == birthday["day"]:
num = random.randint(1, 3)
directory = f"letter_templates/letter_{num}.txt"
with open(directory) as f:
pre_letter = f.read()
letter = pre_letter.replace("[NAME]", birthday["name"])
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(
from_addr=my_email,
to_addrs=birthday["email"],
msg=f"Subject:Happy Birthday!\n\n{letter}"
)
# 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's actual name from birthdays.csv
# 4. Send the letter generated in step 3 to that person's email address.
|
252960bd12d66af9c6f9e2edbf1b423a726f894c
|
Isonzo/100-day-python-challenge
|
/Day 14/higher_lower.py
| 2,158 | 3.828125 | 4 |
import random
from art import logo, vs
from game_data import data
import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def higher_lower():
score = 0
game_not_lost = True
def pick_celebrity():
"""Picks a random celebrity from data"""
return random.choice(data)
def extract_data(x_data):
"""Returns name, follower, description, and country. To be paired with pick_celebrity()"""
name = x_data["name"]
follower = x_data["follower_count"]
description = x_data["description"]
country = x_data["country"]
return name, follower, description, country
def compare(choice, a_is_bigger):
if choice == "a" and a_is_bigger:
return True
elif choice == "b" and not a_is_bigger:
return True
else:
return False
while game_not_lost:
print (logo)
if score != 0:
print(f"Your current score is {score}")
#Assign A and B
a_data = pick_celebrity()
b_data = pick_celebrity()
while a_data == b_data:
a_data = pick_celebrity()
b_data = pick_celebrity()
a_name, a_follower, a_description, a_country = extract_data(a_data)
b_name, b_follower, b_description, b_country = extract_data(b_data)
print(f"Compare A: {a_name}, a {a_description}, from {a_country}")
print(vs)
print(f"Against B: {b_name}, a {b_description}, from {b_country} ")
choice = input("Which one has more followers? 'A' or 'B'? ").lower()
a_is_bigger = a_follower > b_follower
if compare(choice, a_is_bigger):
score += 1
clear()
else:
game_not_lost = False
break
clear()
print (logo)
print(f"You were wrong. You've lost.Your final score was {score}")
play_again = input("Press 'y' to start again or 'n' to quit.").lower()
if play_again == "y":
clear()
higher_lower()
higher_lower()
|
fc24e9ff6df3c2d766e719892fae9426e33f81f6
|
Isonzo/100-day-python-challenge
|
/Day 8/prime_number_checker.py
| 460 | 4.15625 | 4 |
def prime_checker(number):
if number == 0 or number == 1:
print("This number is neither prime nor composite")
return
prime = True
for integer in range(2, number):
if number % integer == 0:
prime = False
break
if prime:
print("It's a prime number")
else:
print("It's not a prime number")
n = int(input("Check this number: "))
prime_checker(number=n)
|
2b7449866da41f54572d858520c2acf0b5404f92
|
shash222/Project_Euler_Python
|
/03LargestPrimeFactor.py
| 253 | 3.6875 | 4 |
def isPrime(i):
for j in range(2,i):
if (i%j==0):
return False
return True
num=600851475143
largest=0;
for i in range(int("%.0f" % num**(1/2))):
if(num%i==0):
if(isPrime(i)):
largest=i
print(largest)
|
8377f2cd5a0dbb6be074c203a80fb55d71a5d98c
|
alexcomu/python-examples
|
/properties_classmethods.py
| 674 | 3.765625 | 4 |
class Address(object):
_cap = []
def __init__(self):
self._cap = []
def append_cap(self, value):
self._cap.append(value)
# append to global, all classes
def append_global_cap(self, value):
self.__class__._cap.append(value)
# property definition
@property
def cap(self):
return self._cap + self.__class__._cap
# class method example
@classmethod
def address_with_cap_100(self):
a = Address()
a.append_cap(100)
return a
a = Address()
a.append_global_cap(5)
a.append_cap(1)
b = Address()
b.append_cap(3)
print a.cap, b.cap
c = Address.address_with_cap_100()
print c.cap
|
b3f1c9211b20e36ce97ea3d73ec5eb2b58b59676
|
jwilliams8899/CS_1301
|
/HW05.py
| 8,150 | 4.40625 | 4 |
#!/usr/bin/env python3
"""
Georgia Institute of Technology - CS1301
HW05 - Tuples & Modules
"""
__author__ = " Jared Williams "
__collaboration__ = """ I worked on this homework assignment alone, using only this semester's resources. """
"""
Function name: cubeVolume
Parameters: tuple
Returns: tuple
Description: Write a function that accepts a tuple of dimensions (length,
width, and height) for an object and returns a tuple with the volume and shape
of the object. Assume that the tuple will always contain three values (each of
which can be integers or floats). Given that the three values in the tuple each
represent the width, length, and height of a rectangular prism or cube, make a
new tuple that contains the volume. The volume should ALWAYS be a float (round
the volume to two decimal places if needed). If the object is a cube (the
width, length, and height are all equal), then add the word "Cube" to the end
of the tuple. Otherwise, add the word "Rectangular Prism" to the end of the
tuple. Zero will never be given as a value in the tuple. Return the tuple that
you have created.
"""
##############################
def cubeVolume(tuple1):
volume = 1
for dimension in tuple1:
volume *= dimension
copy_tuple = tuple1[:]
volume = float(round(volume,2))
if all(index == tuple1[0] for index in tuple1): # also could have done: if len(set(tuple1))==1
return (volume, 'Cube')
else:
return (volume, 'Rectangular Prism')
##############################
"""
Function name: beMyValentine
Parameters: list of tuples of booleans
Returns: tuple of booleans
Description: It's almost Valentine's day (even though it's over now) and
someone is looking for a date! Each tuple in the list passed in represents
someone who might potentially be free to go out on Valentine's day. Each tuple
contains Boolean values and if a tuple has two or more True values, then the
person represented by that tuple will be your valentine!
Return a tuple of Booleans that corresponds to whether or not each person
represented in the list will be your valentine.
"""
##############################
def beMyValentine(list1):
true_count = 0
dates = []
for tuples in list1:
for bools in tuples:
if bools == True:
true_count += 1
if true_count == 2:
dates.append(True)
else:
dates.append(False)
true_count = 0
return tuple(dates)
##############################
"""
Function name: passingMembers
Parameters: aList (list of lists of a tuple and a teamScore(int)), testScore
(int)
Returns: list of tuples of strings
Description: It's an Olympic year and in order to celebrate, Georgia Tech is
holding a competition to find who the best test takers at the university are.
The list passed in is a nested list. Each nested list represents a team. Each
nested list contains a tuple that holds the names of the competitors on the
team as strings and the team's overall score (as an int). The first name in the
tuple is the team captain. The testScore (int) passed in represents the minimum
passing grade for the test.
Return a list of tuples that hold the name of the team captain and all of the
passing members on the team.
Members are only considered to be passing if their team's score is greater than
or equal to the minimum passing grade and the first letter of their name is the
same as the first letter of the ir team captain's name. Always include the team
captain's name if the team score is above the threshold. If a team doesn't meet
the requirements to pass, don't include any of the members of the team.
"""
##############################
def passingMembers(aList,testScore):
passed_list = []
passed_tuple = []
final_list = []
for lists in aList:
#for tuples in range(len(lists[0])):
if lists[1] >= testScore:
passed_list.append(lists[0][0])
for tuples in range(1,len(lists[0])):
if (lists[0][tuples][0]) == (lists[0][0][0]): # if age matches
passed_list.append(lists[0][tuples])
passed_tuple = tuple(passed_list)
final_list.append(passed_tuple)
passed_list = []
for tups in final_list:
if len(tups) == 0:
final_list.remove(tups)
return final_list
##############################
"""
Function name: removeVeggies
Parameters: recipeList (list of tuples of strings), veggieList (list of strings)
Returns: list of tuples of strings
Description: You're hired to create a menu for a birthday party, but at the
last minute you realize that it's for a 5-year-old baby who hates vegetables.
You are given recipeList which is a list of tuples. Each tuple represents a
dish and contains strings representing the ingredients of the dish. The second
parameter, veggieList, is a list of vegetables that the baby does not like. For
this function, go through the ingredients for each dish (tuple) and remove the
vegetables. Return a new list of tuples representing the modified dishes
without vegetables.
"""
##############################
def removeVeggies(recipeList, veggieList):
new_recipe = []
new_recipeList = []
for tuples in recipeList:
for tuple_index in range(len(tuples)):
if tuples[tuple_index] not in veggieList:
new_recipe.append(tuples[tuple_index])
new_recipe_tups = tuple(new_recipe)
new_recipeList.append(new_recipe_tups)
new_recipe = []
return new_recipeList
##############################
"""
Function name: hireTAs
Parameters: listOfTAs (list of tuples), newTAList(list of tuples)
Returns: listOfTAs (modified)
Description: We are hiring new TAs and we want to keep track of all TAs by
their age. The first parameter, listOfTAs, represents all the existing TAs and
is a list of tuples. The tuples are in the format of age (as an integer)
followed by the TAs that are that age (as strings). The second parameter,
newTAList, is of all the newly hired TAs, but the format is different. It is a
list of tuples, but each tuple contains only the age and the name of one TA
that is that age. There can be multiple tuples in this list that have the same
age. In this function, go through the list of newly hired TAs and add the names
to the end of the tuples in listOfTAs that have the same age. Do not make and
return a new list. Modify and return the existing listOfTAs.
Note: There will not be an age in newTAList that is not in listOfTAs so you do
not have to worry about that edge case.
"""
##############################
def hireTAs(listTAs,newTAs):
add_list = []
new_tup = ()
for tuples in range(len(listTAs)):
for tups in newTAs:
if listTAs[tuples][0] == tups[0]:
add_list.append(tups[1])
listTAs[tuples] += tuple(add_list)
add_list = []
return listTAs
##############################
"""
Function name: simpleCalculator
Parameters: a (int), b (int), operation (string)
Returns: int
Description: Provided is a Python file (calculator.py) containing functions for
simple calculations. This function will take in an operation (as a string) that
will either be '+', '-', '*', or '/'. Depnding on the operation that is passed
in, call the appropriate function from the provided Python file and pass in the
a and b arguments as parameters to the function. Return the result of your
calculation. If you do not use the functions in calculator.py to solve this
function then you will not recieve credit for this function.
"""
##############################
import calculator
def simpleCalculator(a,b,op): # op = operation
if op == '+':
result = calculator.add(a,b)
elif op == '-':
result = calculator.subtract(a,b)
elif op == '*':
result = calculator.multiply(a,b)
elif op == '/':
result = calculator.divide(a,b)
result = int(result)
return result
##############################
|
14601b1d69c3fe8845df4f75715eb6e2bc07a34c
|
oversj96/NumericalMethodsHW
|
/Homework 3/Newton Method.py
| 232 | 3.875 | 4 |
# Author: Justin Overstreet
# Purpose: Test Newton-Raphson Method for finding zeros.
def f(x):
return x - ((x ** 2 - 2 * x - 1) / (2 * x - 2))
list = [2.5]
i = 0
while (len(list) < 4):
list.append(f(list[i]))
i += 1
print(list)
|
c97e005896dcb2c66f218583a8d75179e1962d8b
|
Matzikratzi/AoC2020
|
/12/12.py
| 1,403 | 4.0625 | 4 |
#!/usr/bin/python3
def Movement(pos, direction, instruction):
action = instruction[0]
value = int(instruction[1:])
newPos = pos.copy()
newDirection = direction
if action == 'N':
newPos[1] += value
elif action == 'S':
newPos[1] -= value
elif action == 'E':
newPos[0] += value
elif action == 'W':
newPos[0] -= value
elif action == 'F':
if direction == 90: # N
newPos[1] += value
elif direction == 270: # S
newPos[1] -= value
elif direction == 0: # E
newPos[0] += value
else: # W
newPos[0] -= value
else: # Change of direction
if action == 'R':
# clockwise change
newDirection -= value
newDirection += 360
newDirection %= 360
else:
# anti clockwise
newDirection += value
newDirection %= 360
return newPos, newDirection
with open('input') as f:
#with open('input-small') as f:
data = [line.rstrip() for line in f]
direction = 0 # E=0, N=90, W=180, S=270
position = [0,0]
for row in data:
print(position)
print(direction)
print(row)
position, direction = Movement(position, direction, row)
print('Position:', position)
print('Manhattan distance:', abs(position[0])+abs(position[1]))
|
30acdc43cd634f05c95d71165925d67dcbfaeefe
|
biewdev/unicid-python-exercises
|
/lista-1/acertos.py
| 376 | 3.796875 | 4 |
points = 0
answer_one = input("Resposta da primeira questão: ")
if answer_one.lower() == "B".lower():
points += 1
answer_two = input("Resposta da segunda questão: ")
if answer_two.lower() == "A".lower():
points += 1
answer_three = input("Resposta da terceira questão: ")
if answer_three.lower() == "D".lower():
points += 1
print("Total de pontos:", points)
|
a579085f352f2b9c4d1c5c0b85d1cc99fde7ee9f
|
paveltsytovich/telegram-course
|
/Code/Module 3/Exercies/transfer.py
| 153 | 3.828125 | 4 |
x = input("введите строку >")
d = int(x)
y = input("введите другую строку >")
print(float(y))
print(bin(d))
print(hex(d))
|
962b23479b12f885243add0f6ced0b8e7c6dae0e
|
paveltsytovich/telegram-course
|
/Code/Module 3/Exercies/string.py
| 309 | 3.859375 | 4 |
x = input("введите строку >")
y = input("введите вторую строку >")
print(x*5)
print(x+y)
print(len(x)+len(y))
if y in x:
print("Вторая строка является подстрокой первой")
else:
print("строки являютеся разными")
|
a914a0732f5c79630dab6419a9ba5094e888c6a2
|
paveltsytovich/telegram-course
|
/Code/Module 3/Live/list.py
| 179 | 3.59375 | 4 |
x = [1,2,3,4]
x.append(5)
print(x)
y = [6,7,8,9]
print(x + y)
x.extend(y)
print(x)
x.insert(2,99)
print(x)
print(x.pop())
print(x.count(2))
x.reverse()
print(x)
x.clear()
print(x)
|
1b14889db04fed658d481fd563213b7c9ef3e4d8
|
lucasrumney94/Python
|
/Python/Catching the Cold or-the-Flu/1/StringBuilder.py
| 988 | 3.546875 | 4 |
import time
iterations = 100
word_list = ["Hello ", "there! ", "How ", "are ", "you ", " doing", " today?"]
with open('freebsddictionary.txt', 'r') as file_object:
for line in file_object:
word_list.append(file_object.readline())
# additive string concatenation
def join_words(words):
sentence = ''
for word in words:
sentence = sentence + word
return sentence
start_time = time.time()
for i in range(0, iterations):
join_words(word_list)
end_time = time.time()
print ('Normal Concatenation Time ' + str(end_time-start_time))
##########################
# String builder function
def join_words_using_string_builder_idea(words):
sentence = []
for word in words:
sentence.append(word)
return ''.join(sentence)
start_time = time.time()
for i in range(0, iterations):
join_words_using_string_builder_idea(word_list)
end_time = time.time()
print ('String Builder Time ' + str(end_time-start_time))
##########################
|
3c14a40a15d5205d30f126cde1378373a4d82a76
|
CKalinowski/KalinowskiChloeTP03
|
/main.py
| 3,079 | 4.3125 | 4 |
print ('1. Listes')
print ('1.1 Modifier une liste')
annee = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre',10,11,12]
print('1.1.1 Supprimez les trois derniers éléments un par un, dans un premier temps')
print (annee)
del(annee[-1])
print (annee)
del(annee[-1])
print (annee)
del(annee[-1])
print (annee)
print("1.1.2 Puis rajoutez les mois 'Octobre', 'Novembre', 'Décembre' à la fin")
moisManquant = ['Octobre', 'Novembre', 'Decembre']
annee = annee + moisManquant
print (annee)
print('1.1.3 Supprimez les trois derniers éléments un par un, dans un premier temps')
annee = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre',10,11,12]
annee[9] = 'Octobre'
annee[10] = 'Novembre'
annee[11] = 'Decembre'
print(annee)
print('1.1.4 Pour aller plus loin : la liste ‘en compréhension’')
x = [1, 2, 3, 4, 3, 5, 3, 1, 3, 2]
resultat = [y+1 for y in x]
print(resultat)
print('2. Tuples')
moisDeLannee = ('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre')
print('2.1 Accès aux éléments d’un tuple')
print(moisDeLannee[3])
print('2.2 Vérifier la présence d’un élément dans un tuple')
print('mars' in moisDeLannee)
print('Mars' in moisDeLannee)
print('3. Dictionnaires')
age = {"pierre" : 35 , "paul" : 32 , "Jacques" : 27 , "andre" : 23}
print('3.1 Ajoutez des éléments au dictionnaire')
age['david'] = 35
age['veronique'] = 21
age['sylvie'] = 30
age['damien'] = 37
print(age)
print('3.2 Accéder à une valeur à partir d’une clé')
print(age['sylvie'])
print('3.3 Accéder à une valeur à partir d’une clé')
print('jean' in age)
print('3.4 Gérer des valeurs multiples')
#pierre durand, 1986, 1.72, 70 soit [‘pierre durand’]=(1986,1.72,70)
#victor dupont, 1987, 1.89, 57
#paul dupuis, 1989, 1.60, 92
#jean rieux, 1985, 1.88, 77
club ={}
club['pierre durand']=(1986,1.72,70)
club['victor dupont']=(1987,1.89,57)
club['paul dupuis']=(1989, 1.60, 92)
club['jean rieux']=(1985, 1.88, 77)
print(club)
print('3.5 Afficher les données d’un sportif')
#Accédez aux données de ‘paul dupuis’ et initialisez les variables dateNaissSportif, poidsSportif et tailleSportif avec les valeurs du tuple correspondant.
print(club['paul dupuis'])
dateNaissSportif = club['paul dupuis'][0]
tailleSportif = club['paul dupuis'][1]
poidsSportif = club['paul dupuis'][2]
#Créez ensuite une chaine de formatage formatDonnees qui permettra d’utiliser les variables pour afficher la chaine suivante avec un print()
phrase = 'Le sportif nommé Paul Dupuis est né en {}, sa taille est de {} m et son poids est de {} Kg'
print(phrase.format(dateNaissSportif, tailleSportif,poidsSportif))
print('4. Entrées utilisateur')
print('4.1 Club sportif : variante')
nomSportif = input('Entrez le nom du sportif : ')
dateNaissSportif = club[nomSportif][0]
tailleSportif = club[nomSportif][1]
poidsSportif = club[nomSportif][2]
phrase = 'Le sportif nommé {} est né en {}, sa taille est de {} m et son poids est de {} Kg'
print(phrase.format(nomSportif, dateNaissSportif, tailleSportif,poidsSportif))
|
d228d4888770b45dfc5b444f547024ff3830815f
|
hobbz216/Number-Guessing-Game
|
/number_guess.py
| 3,118 | 3.9375 | 4 |
#Number guessing game
import random
from replit import clear
import art
def answer():
answer = random.choice(range(1, 101))
return answer
print(answer)
def difficulty(choice):
if choose == 'easy':
return easy_guess
else:
return hard_guess
player_guess = 0
game_answer = 0
game_over = False
while not game_over:
play_game = input("Type 'y' to play a game or 'n' to exit: ")
clear()
easy_guess = 9
hard_guess = 4
if play_game == 'n':
game_over = True
elif play_game == 'y':
print(art.logo)
choose = input("Choose 'easy' for 10 attempts or 'hard' for 5 attempts: ")
game_answer = answer()
difficulty(choose)
choice = True
while choice:
if choose == 'easy':
guess = input("Guess a number between 1 and 100: ")
player_guess = int(guess)
if player_guess == game_answer:
print("Correct, player wins.")
choice = False
elif player_guess > game_answer and easy_guess > 1:
print(f"Too high, guess again. # left to guess: {easy_guess}")
easy_guess -= 1
elif player_guess < game_answer and easy_guess > 1:
print(f"Too low, guess again. # left to guess: {easy_guess}")
easy_guess -= 1
elif player_guess > game_answer and easy_guess == 1:
print("Too high. Last guess.")
easy_guess -= 1
elif player_guess < game_answer and easy_guess == 1:
print("Too low. Last guess.")
easy_guess -= 1
elif easy_guess == 0:
print(f"You're out of guesses. The answer was {game_answer}. You lose.")
choice = False
elif choose == 'hard':
guess = input("Guess a number between 1 and 100: ")
player_guess = int(guess)
if player_guess == game_answer:
print("Correct, player wins.")
choice = False
elif player_guess > game_answer and hard_guess > 1:
print(f"Too high, guess again. # left to guess: {hard_guess}")
hard_guess -= 1
elif player_guess < game_answer and hard_guess > 1:
print(f"Too low, guess again. # left to guess: {hard_guess}")
hard_guess -= 1
elif player_guess > game_answer and hard_guess == 1:
print("Too high. Last guess.")
hard_guess -= 1
elif player_guess < game_answer and hard_guess == 1:
print("Too low. Last guess.")
hard_guess -= 1
elif hard_guess == 0:
print(f"You're out of guesses. The answer was {game_answer}. You lose.")
choice = False
|
a4a77a7a6d168d1ba0c1778a6170915cb51b38a6
|
esvrindha/python-programming
|
/largest.py
| 211 | 4 | 4 |
dig1=int(raw_input(""))
dig2=int(raw_input(""))
dig3=int(raw_input(""))
if (dig1>dig2)and(dig1>dig3):
largest = dig1
elif (dig2>dig1)and(dig2>dig3):
largest = dig2
else:
largest= dig3
print(largest)
|
b8815b4957ae8ca3e96f6b5e6926657828d7f87c
|
esvrindha/python-programming
|
/97.py
| 90 | 3.578125 | 4 |
vrin=int(raw_input(""))
e=0
while (vrin!=0):
r=vrin%10;
e=e*10+r
vrin/=10;
print(e)
|
99139c2ecf70d3985d8eef46bf11350d6a4a9843
|
esvrindha/python-programming
|
/eveninrange.py
| 98 | 3.53125 | 4 |
moni=int(input(""))
vamp=int(input(""))
for i in range(moni+1,vamp):
if(i%2 == 0):
print(i)
|
6b85d1e3ad83c50cbfdc9b2117de0faf0b8c9b52
|
esvrindha/python-programming
|
/powof2.py
| 95 | 3.78125 | 4 |
i=int(raw_input(""))
if (i%2)==0:
print("yes")
if (i==1):
print("yes")
else:
print("no")
|
52a268329f255d74fa721ae8d175e9024e39377e
|
kashenfelter/IXL-Learning-Coding-Challenge
|
/reduced_fraction_sums.py
| 1,209 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 01:37:03 2018
@author: raleigh-littles
"""
import fractions, unittest
def reducedFractionSums(expressions):
"""
Fairly self-explanatory, just use the built-in fractions package to perform
the fraction addition -- they'll be automatically reduced in the end.
"""
sum_array = []
for expr in expressions:
first_frac_string, second_frac_string = expr.split('+')
first_frac = fractions.Fraction(first_frac_string)
second_frac = fractions.Fraction(second_frac_string)
sum_frac = first_frac + second_frac
sum_array.append(str(sum_frac.numerator) + '/' + str(sum_frac.denominator))
return sum_array
fraction_expressions = ['722/148+360/176',
'978/1212+183/183',
'358/472+301/417',
'780/309+684/988',
'258/840+854/686']
class TestReducedFractionSums(unittest.TestCase):
def test(self):
self.assertEqual( reducedFractionSums(fraction_expressions), ['2818/407', '365/202', '145679/98412', '4307/1339', '1521/980'])
if __name__ == '__main__':
unittest.main()
|
14e6ae9bb95689aa234afe00ec5a6396cc41dd8b
|
M0673N/Programming-Fundamentals-with-Python
|
/05_lists_advanced/lab/04_palindrome_strings.py
| 210 | 3.78125 | 4 |
data = input().split()
search = input()
counter = 0
data2 = [palindrome for palindrome in data if palindrome == "".join(reversed(palindrome))]
print(data2)
print(f"Found palindrome {data.count(search)} times")
|
d5c0a82cafd613bc94898650c051945e195d85b0
|
M0673N/Programming-Fundamentals-with-Python
|
/04_functions/exercise/10_list_manipulator.py
| 3,395 | 3.71875 | 4 |
from sys import maxsize
def exchange(index):
array = data[index + 1:] + data[:index + 1]
return array
def max_even():
max_num = -maxsize
max_num_index = -1
for index in range(len(data)):
if data[index] >= max_num and data[index] % 2 == 0:
max_num = data[index]
max_num_index = index
return max_num_index
def max_odd():
max_num = -maxsize
max_num_index = -1
for index in range(len(data)):
if data[index] >= max_num and data[index] % 2 == 1:
max_num = data[index]
max_num_index = index
return max_num_index
def min_even():
min_num = maxsize
min_num_index = -1
for index in range(len(data)):
if data[index] <= min_num and data[index] % 2 == 0:
min_num = data[index]
min_num_index = index
return min_num_index
def min_odd():
min_num = maxsize
min_num_index = -1
for index in range(len(data)):
if data[index] <= min_num and data[index] % 2 == 1:
min_num = data[index]
min_num_index = index
return min_num_index
def first(count, kind):
temp_list = []
counter = 0
if kind == "even":
for num in data:
if count == counter:
break
if num % 2 == 0:
temp_list.append(num)
counter += 1
else:
for num in data:
if count == counter:
break
if num % 2 == 1:
temp_list.append(num)
counter += 1
return temp_list
def last(count, kind):
temp_list = []
counter = 0
if kind == "even":
for num in reversed(data):
if count == counter:
break
if num % 2 == 0:
temp_list.append(num)
counter += 1
else:
for num in reversed(data):
if count == counter:
break
if num % 2 == 1:
temp_list.append(num)
counter += 1
temp_list.reverse()
return temp_list
data = list(map(int, input().split()))
command = input()
while not command == "end":
command_as_list = command.split()
if command_as_list[0] == "exchange":
if 0 <= int(command_as_list[1]) < len(data):
data = exchange(int(command_as_list[1]))
else:
print("Invalid index")
elif command_as_list[0] == "max":
if command_as_list[1] == "even" and max_even() != -1:
print(max_even())
elif command_as_list[1] == "odd" and max_odd() != -1:
print(max_odd())
else:
print("No matches")
elif command_as_list[0] == "min":
if command_as_list[1] == "even" and min_even() != -1:
print(min_even())
elif command_as_list[1] == "odd" and min_odd() != -1:
print(min_odd())
else:
print("No matches")
elif command_as_list[0] == "first":
if int(command_as_list[1]) > len(data):
print("Invalid count")
else:
print(first(int(command_as_list[1]), command_as_list[2]))
elif command_as_list[0] == "last":
if int(command_as_list[1]) > len(data):
print("Invalid count")
else:
print(last(int(command_as_list[1]), command_as_list[2]))
command = input()
print(data)
|
133c061729e061076793a84878ad0cb4347fc016
|
M0673N/Programming-Fundamentals-with-Python
|
/exam_preparation/final_exam/05_mock_exam/03_problem_solution.py
| 1,713 | 4.15625 | 4 |
command = input()
map_of_the_seas = {}
while not command == "Sail":
city, population, gold = command.split("||")
if city not in map_of_the_seas:
map_of_the_seas[city] = [int(population), int(gold)]
else:
map_of_the_seas[city][0] += int(population)
map_of_the_seas[city][1] += int(gold)
command = input()
command_2 = input()
while not command_2 == "End":
command_2 = command_2.split("=>")
if command_2[0] == "Plunder":
city = command_2[1]
people = int(command_2[2])
gold = int(command_2[3])
map_of_the_seas[city][0] -= people
map_of_the_seas[city][1] -= gold
print(f"{city} plundered! {gold} gold stolen, {people} citizens killed.")
if map_of_the_seas[city][0] <= 0 or map_of_the_seas[city][1] <= 0:
print(f"{city} has been wiped off the map!")
map_of_the_seas.pop(city)
elif command_2[0] == "Prosper":
city = command_2[1]
gold = int(command_2[2])
if gold < 0:
print("Gold added cannot be a negative number!")
else:
map_of_the_seas[city][1] += gold
print(f"{gold} gold added to the city treasury. {city} now has {map_of_the_seas[city][1]} gold.")
command_2 = input()
if len(map_of_the_seas) == 0:
print("Ahoy, Captain! All targets have been plundered and destroyed!")
else:
map_of_the_seas = dict(sorted(map_of_the_seas.items(), key=lambda x: (-x[1][1], x[0])))
print(f"Ahoy, Captain! There are {len(map_of_the_seas)} wealthy settlements to go to:")
for city in map_of_the_seas:
print(f"{city} -> Population: {map_of_the_seas[city][0]} citizens, Gold: {map_of_the_seas[city][1]} kg")
|
743ddca34beba4ccbe754971a751106cb2e7b1f5
|
M0673N/Programming-Fundamentals-with-Python
|
/03_lists_basics/more exercises/04_car_race.py
| 592 | 3.703125 | 4 |
data = [int(i) for i in input().split()]
route_1 = data[:len(data) // 2]
route_2 = data[len(data) // 2 + 1:]
route_2.reverse()
total_time_route_1 = 0
total_time_route_2 = 0
for i in route_1:
if i == 0:
total_time_route_1 *= 0.8
else:
total_time_route_1 += i
for i in route_2:
if i == 0:
total_time_route_2 *= 0.8
else:
total_time_route_2 += i
if total_time_route_1 < total_time_route_2:
print(f"The winner is left with total time: {total_time_route_1:.1f}")
else:
print(f"The winner is right with total time: {total_time_route_2:.1f}")
|
9b7d84c119d2cffe523113566fd286682c4ee0cb
|
M0673N/Programming-Fundamentals-with-Python
|
/05_lists_advanced/exercise/05_office_chairs.py
| 397 | 3.609375 | 4 |
rooms = int(input())
free_chairs = 0
flag = False
for room in range(1, rooms + 1):
command = input().split()
if len(command[0]) < int(command[1]):
print(f"{int(command[1]) - len(command[0])} more chairs needed in room {room}")
flag = True
else:
free_chairs += len(command[0]) - int(command[1])
if not flag:
print(f"Game On, {free_chairs} free chairs left")
|
955aa650829c230ad2bec9d3ae3674a1fc108889
|
M0673N/Programming-Fundamentals-with-Python
|
/07_dictionaries/exercise/05_softuni_parking.py
| 708 | 3.828125 | 4 |
n = int(input())
data = {}
for i in range(n):
command = input().split()
if command[0] == "register":
username = command[1]
plate = command[2]
if username not in data:
data[username] = plate
print(f"{username} registered {plate} successfully")
else:
print(f"ERROR: already registered with plate number {plate}")
elif command[0] == "unregister":
username = command[1]
if username in data:
print(f"{username} unregistered successfully")
data.pop(username)
else:
print(f"ERROR: user {username} not found")
for user, plate in data.items():
print(f"{user} => {plate}")
|
fceea066bb99f0f3e16b0668c1f19a79896b376d
|
M0673N/Programming-Fundamentals-with-Python
|
/03_lists_basics/more exercises/01_zeros_to_back.py
| 231 | 3.578125 | 4 |
string = [int(i) for i in input().split(", ")]
counter = 0
for i in range(len(string)):
if string[i] == 0:
counter += 1
result = [i for i in string if i != 0]
for i in range(counter):
result.append(0)
print(result)
|
be9abb9d6b95ef9b00fee1f9865791b9b0d099b9
|
M0673N/Programming-Fundamentals-with-Python
|
/02_data_types_and_variables/exercise/07_water_overflow.py
| 200 | 3.828125 | 4 |
n = int(input())
capacity = 0
for i in range(n):
litres = int(input())
if capacity + litres > 255:
print("Insufficient capacity!")
else:
capacity += litres
print(capacity)
|
38a12439edb079a049bbe6b82ca1c7ae7691f7dc
|
M0673N/Programming-Fundamentals-with-Python
|
/02_data_types_and_variables/exercise/05_print_part_of_the_ASCII_table.py
| 125 | 3.90625 | 4 |
start_char = int(input())
end_char = int(input())
for char in range(start_char, end_char + 1):
print(chr(char), end=" ")
|
90887abf69343cca14a0732c30a7ad54233ec9de
|
M0673N/Programming-Fundamentals-with-Python
|
/03_lists_basics/exercise/10_bread_factory.py
| 1,189 | 3.59375 | 4 |
data = input().split("|")
energy = 100
coins = 100
for i in range(len(data)):
data[i] = data[i].split("-")
for i in range(len(data)):
if data[i][0] == "rest":
if energy + float(data[i][1]) <= 100:
energy += float(data[i][1])
print(f"You gained {float(data[i][1]):.0f} energy.")
print(f"Current energy: {energy:.0f}.")
else:
energy += float(data[i][1]) - 100
jump = energy
energy = 100
print(f"You gained {float(data[i][1]) - jump:.0f} energy.")
print(f"Current energy: {energy:.0f}.")
elif data[i][0] == "order":
if energy >= 30:
coins += float(data[i][1])
energy -= 30
print(f"You earned {data[i][1]} coins.")
else:
energy += 50
print(f"You had to rest!")
else:
if coins > float(data[i][1]):
coins -= float(data[i][1])
print(f"You bought {data[i][0]}.")
else:
print(f"Closed! Cannot afford {data[i][0]}.")
break
else:
print(f"Day completed!")
print(f"Coins: {coins:.0f}")
print(f"Energy: {energy:.0f}")
|
f3e71dd7e6bcd7f159f12408140b4d7bb6d481f3
|
M0673N/Programming-Fundamentals-with-Python
|
/02_data_types_and_variables/exercise/01_integer_operations.py
| 127 | 3.75 | 4 |
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
print(int((int((num1 + num2) / num3)) * num4))
|
44bc85447139252b30c7c9b2ea4ef689ecea196b
|
M0673N/Programming-Fundamentals-with-Python
|
/02_data_types_and_variables/exercise/09_snowballs.py
| 347 | 3.5625 | 4 |
n = int(input())
best = 0
for i in range(n):
snow = int(input())
time = int(input())
quality = int(input())
value = (snow / time) ** quality
if value > best:
best_snow = snow
best_time = time
best_quality = quality
best = value
print(f"{best_snow} : {best_time} = {int(best)} ({best_quality})")
|
83c8656882b2d869dc2bdc6ea0e397b449e27e33
|
M0673N/Programming-Fundamentals-with-Python
|
/05_lists_advanced/exercise/06_electron_distribution.py
| 282 | 3.78125 | 4 |
electrons = int(input())
counter = 1
result = []
while electrons > 0:
if electrons - 2 * counter ** 2 >= 0:
result.append(2 * counter ** 2)
electrons -= 2 * counter ** 2
counter += 1
else:
result.append(electrons)
break
print(result)
|
ba8907050af53baa67dcbbaba314ab151ea20d41
|
M0673N/Programming-Fundamentals-with-Python
|
/04_functions/exercise/04_odd_and_even_sum.py
| 261 | 4.28125 | 4 |
def odd_even_sum(num):
odd = 0
even = 0
for digit in num:
if int(digit) % 2 == 0:
even += int(digit)
else:
odd += int(digit)
print(f"Odd sum = {odd}, Even sum = {even}")
num = input()
odd_even_sum(num)
|
5df9b99440b11611715bcd857315518e77020cdc
|
M0673N/Programming-Fundamentals-with-Python
|
/09_regular_expressions/exercise/02_find_variable_names_in_sentences.py
| 122 | 3.734375 | 4 |
import re
data = input()
pattern = r"\b[_]([A-Za-z0-9]+\b)"
result = re.findall(pattern, data)
print(",".join(result))
|
050bbbd9b7c21004b600b9bd5215623ce38c7736
|
shaybrynes/MatrixPy
|
/MatrixPy/print_matrix.py
| 387 | 3.890625 | 4 |
__author__ = "Shay Brynes"
__license__ = "Apache License 2.0"
def print_matrix(matrix):
for n in range(0, len(matrix)):
for m in range(0, len(matrix[n])):
if m == 0:
print("(", end="")
print(matrix[n][m], end="")
if m == len(matrix[n])-1:
print(")")
else:
print(", ", end="")
|
e4a3e396396c895e4b2cb900e184cff9d7a3fdd3
|
ojaisnielsen/project-euler
|
/ProjectEuler/Problem14.py
| 279 | 3.671875 | 4 |
def collatz(n):
yield n
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
yield n
max = 0
arg_max = 0
for a in range(1, 1000000):
l = sum(1 for x in collatz(a))
if a % 10000 == 0:
print a, max
if l > max:
max = l
arg_max = a
print arg_max, max
|
69c56a925315c330cccca84de2d760871b970f9f
|
AdityaDolas/CJPJHCVN
|
/python/CFLOW008.py
| 149 | 3.9375 | 4 |
z=int(input())
while(z>0):
a=int(input())
if(a<10):
print("What an obedient servant you are!")
else:
print("-1")
z-=1
|
e6127b87f2f91c10538c5d5c97d5108866c13c2d
|
camilleemig/CSE231
|
/Project11/proj11-app.py
| 2,897 | 3.71875 | 4 |
###########################################################
# Computer Project #11
#
# Imports classes
# Trys to open two files
# Reads assignment weights from file
# Reads assignment names from file
# Reads student grades and ids from file
# Seperates student grades and ids
# Associates student grades as Grade objects to student ids
# Makes a list of student objects
# Prints the student objects
# Calculates average and prints average
#
###########################################################
import classes
try:
#Trys to open files, stops program if error occurs
grades = open('grades.txt','r')
students = open('students.txt','r')
#Gets weights from the first line, converts to floats
weights = grades.readline().split()
weights = weights[1:]
for i,weight in enumerate(weights):
weights[i] = float(weight)
#Gets project names from the next line, gets rid of id column header
project_names = grades.readline().split()
project_names = project_names[1:]
#Loops through remaining lines, appending a list of a student's grades
#to a list of all of the student's grades
students_grades = []
for line in grades:
students_grades.append(line.split())
#Seperates student ids from the student's grades, maintaining order
student_ids = []
for student in students_grades:
student_ids.append(int(student.pop(0)))
#Makes a dictionary relating the student ids and the list of Grade objects
grades_dictionary = {}
for i in range(len(students_grades)):
for j in range(len(students_grades[i])):
students_grades[i][j] = classes.Grade(project_names[j],\
float(students_grades[i][j]),weights[j])
grades_dictionary[int(student_ids[i])] = students_grades[i]
students_list = []
for line in students:
#Gets student information from students file
information = line.split()
stu_id = information[0]
stu_first = information[1]
stu_last = information[2]
#makes a student object from information in the students file and
#appends it to a list
students_list.append(classes.Student(int(stu_id), stu_first, stu_last,\
grades_dictionary[int(stu_id)]))
#Sets variables for class average
number_of_students = 0
class_average = 0
#Prints data for each student and adds each final grade to the class average
for student in students_list:
print(student)
class_average += student.calculate_grade()
number_of_students += 1
#Computes and prints class average
class_average = class_average/number_of_students
print("{}{:.2f}%".format("The class average is: ", class_average))
except FileNotFoundError:
print("Could not successfully open file")
|
53c0dcf5bea7d37c051f30ac88194424a2ea63c3
|
camilleemig/CSE231
|
/Project2/control_example.py
| 708 | 3.96875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 8 10:25:11 2016
@author: Camille
"""
points_str = input("Enter the lead in points: ")
points_ahead_int = int(points_str)
lead_calculation_float = float(points_ahead_int - 3)
has_ball_str = input("Does the lead team have the ball (Yes or No)? ")
if has_ball_str == "Yes":
lead_calculation_float += .5
else:
lead_calculation_float -=.5
if lead_calculation_float < 0:
lead_calculation_float = 0
lead_calculation_float = lead_calculation_float**2
seconds_remaining_int = int(input("Enter the number of seconds remaining: "))
if lead_calculation_float > seconds_remaining_int:
print("Lead is safe.")
else:
print("Lead is not safe.")
|
536e2492179562082c1e94c7828f4d965e6dda0e
|
Alejandro-Larumbe/appAcademy-backend-frontend-project-skeleton
|
/week17-Python/monday-basics/sets.py
| 494 | 3.625 | 4 |
# SETS
# a = set('banana')
# b = set('scarab')
# print(a, b)
# print(a | b)
# print(a.union(b))
# print(a & b)
# print(a.intersection(b))
# print(a ^ b)
# print(a.symmetric_difference(b))
# print(a - b)
# print(a.difference(b))
# error
# print(a + b) unsupported operand
# purchasingEmails = ('bob@gmail.com', 'sam@yahoo.com', 'riley@rileymail.org')
# helpEmails = ('jo@josbilling.com', 'bob@gmail.com', 'sam@yahoo.com')
# print('Users making a purchase and also calling help desk')
# print(set(purchasingEmails) & set(helpEmails))
|
1c6fbf0268874aed0a8a4b89efb3c8c538199e3a
|
Alejandro-Larumbe/appAcademy-backend-frontend-project-skeleton
|
/week17-Python/monday-basics/pythonBasics.py
| 2,753 | 4.0625 | 4 |
# print('Hello world')
# Arithmetic
# ~~~~~~~~~~~~~~~~~~
# x = 25 # integer
# y = 5 # float
# print(x, y) # 25 5
# print(x + y) # 30
# print(x - y) # 20
# print(x * y) # 125
# print(x / y) # 5
# print(x // y) # 5
# print(x % y) # 0
# print(x ** 2)
# print(y ** 2)
# Input / Output
# ~~~~~~~~~~~~~~~~~~
# name = input('What is your name?: ') # or input('blabla\') <- line break
# print(name)
# print('Hi,' + name + '.')
# print('Hi, %s, %s' % (name, name)) # s is for string
# print('Hi, {0}, {1}.'.format(name, name))
# print(f'Hi, {name}.')
# Duck typing
# ~~~~~~~~~~~~~~~~~~
# a = False
# a = None
# a = 5
# a = 'Box'
# try:
# print(len(a))
# except:
# print(f'{a} has no length')
# Arithmetic with Strings
# ~~~~~~~~~~~~~~~~~~
# a = 'a'
# b = 'b'
# an = 'an'
# print(b + an)
# print(b + a*7)
# print(b + an*2 + a)
# print('$1' + ',000'*3)
# Assignment operators
# ~~~~~~~~~~~~~~~~~~
# i = 1
# i = i + 1
# i **= 2
# i //= 10
# i += 3
# i *= 10**20
# i **= 10*20
# print(i)
# print(float(i))
# Equality
# ~~~~~~~~~~~~~~~~~~
# a = 1
# b = 1.0
# c = '1'
# print(a == b)
# print(a == c)
# print(b == c)
# if(a == c):
# print('match')
# elif (a == b):
# print(f'{a} matches {b}')
# else:
# print('not a match')
# Meaning of truth
# ~~~~~~~~~~~~~~~~~~
# def test(value):
# if (value):
# print(f'{value} is true')
# else:
# print(f'{value} is false')
# # Truthy
# a = 1
# b = 1.0
# c = '1'
# d = [a, b, c]
# e = {'hi': 'hello'}
# f = test
# # Falsey
# g = ''
# h = 0
# i = None
# j = []
# k = {}
# test(f)
# Identity vs. Equality
# ~~~~~~~~~~~~~~~~~~
# a = 1
# b = 1.0
# c = '1'
# # True
# print(a == b)
# print(a == 1 and isinstance(a, int))
# print([[], 2, 3] is [[], 2, 3])
# # false
# print(a is b) # compares reference/identity in memory
# print(a is c)
# print(b is c)
# print([] is [])
# print(b == 1 and isinstance(b, int))
# Functions
# ~~~~~~~~~~~~~~~~~~
# def xor(left, right):
# return left != right
# def xor(left, right): return left != right
# def print_power_of(base, exp=1):
# i = 1
# while i <= exp:
# print(base**i)
# i += 1
# def greetingMaker(salutation):
# def greeting(name):
# return f'{salutation} {name}'
# return greeting
# print(xor(True, True))
# print(xor(True, False))
# print(xor(False, True))
# print(xor(False, False))
# print(print_power_of(2, 5))
# print_power_of(2, 5)
# print_power_of(exp=5, base=2)
# print(print_power_of(2, exp=5, base=2)) # Error because you have more arguments than parameters.
# print(print_power_of(2)) # Error because you have less arguments than parameters.
# hello = greetingMaker('Hello')
# hiya = greetingMaker('Hiya')
# print(hello('Monika'))
# print(hiya('Raja'))
|
e32a9549aedd90cd0c5995dae17827c9a5c004cc
|
WillyRenzo/Introduction-to-Python
|
/Minicurso2209/ex10.py
| 479 | 3.90625 | 4 |
lista = ['Willy', 1000, 5.00, 'Sei la', 70.2]
print("Lista: \n")
print lista
print lista[0]
print lista[1:3]
print lista[2:]
print("\nTupla:\n")
tupla = ('Willy', 1000, 5.00, 'Sei la', 70.2)
tinytuple = (123, 'pedro')
print tupla
print tupla[0]
print tupla[1:3]
print tupla[2:]
print tinytuple * 2
print tupla + tinytuple
print("\nDicionario:\n")
tinydict = {'nome': 'willy', 'codigo':6734, 'departamento': 'TI'}
print tinydict
print tinydict.keys()
print tinydict.values()
|
6e8ac25e465a4c45f63af8334094049c0b660c4b
|
IrisCSX/LeetCode-algorithm
|
/476. Number Complement.py
| 1,309 | 4.125 | 4 |
"""
Promblem:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Note:
任何二进制数和1111按位异都是该数字的互补数字
比如
(101)表示5
(111)
(010)得到5的互补数字是3
算法:
1.得到与n的位数相同的1111
2.与1111取异
"""
def numComplement(n):
# 1.得到与n的二进制位数相同的111
lenth = len(bin(n))-2
compareN = 2 ** lenth -1
# 2.让111与数字n取异
complementN = compareN ^ n
return complementN
def numComplement2(num):
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num
def test():
n = 8
m = numComplement2(n)
print(bin(n),"的互补的二进制数是:",bin(m))
if __name__ == '__main__':
test()
|
a9a18bd52d6f79f9c013e43929633445d513f2a8
|
samsonosiomwan/printer-model
|
/printer/printing_machine.py
| 1,501 | 3.75 | 4 |
from data.data import *
class Printer:
"""this class holds template for format and resources attrbute, estimated resources(calculates resources to be used) and report"""
color,greyscale = FORMAT['coloured']['materials']['ink'],FORMAT['greyscale']['materials']['ink']
colored_price,greyscale_price = FORMAT['coloured']['price'], FORMAT['greyscale']['price']
def __init__(self,no_of_pages = None, coloured = color, greyscale = greyscale, ink_resources = resources['ink'], paper_resources = resources['paper']):
self.no_of_pages = no_of_pages
self.ink_resources= ink_resources
self.paper_resources = paper_resources
self.coloured = coloured
self.greyscale = greyscale
def estimated_resources(self,resources):
"""method serves as template to calculate resources used for ink, it pass resources type as argument"""
total_materials = self.no_of_pages * resources
return total_materials
def price_transaction(self,price_per_page):
"""method to calucate cost or print, multipies no of pages by the price per page"""
printing_cost = self.no_of_pages * price_per_page
return printing_cost
def report(self):
"""method returns the report of after printing is completed"""
ink = resources['ink']
paper = resources['paper']
profit = resources['profit']
resource = f'Ink Level: {ink}ml\nPaper Level:{paper}pc\nProfit:₦{profit}'
return resource
|
90f00c6b29d23379ceff38454d9300a58eb8ff67
|
litrin/MonkeyTyping
|
/monkey_typing.py
| 614 | 3.609375 | 4 |
import random
import time
CHARS = "abcdefjhijklmnopqrstuvwxyz"
GOAL = 'match'
def typing():
charaters_count = len(CHARS)
count = 0
while True:
count += 1
i = 0
word = ''
while i < len(GOAL):
i += 1
charater_number = random.randint(1, charaters_count) - 1
word += CHARS[charater_number]
if word == GOAL:
break
print "GOT MATCHED! When %s words generated." % count
def timer(func):
start_time = time.time()
func()
print time.time() - start_time
if __name__ == '__main__':
timer(typing)
|
d3ff0dbbec0de62b85ed373e71029904c89f7482
|
shivang-123/pro-coder
|
/player_set1_ques3.py
| 110 | 3.53125 | 4 |
import re
pat = r'\d+'
n = input()
if bool(re.match(pat, n)):
print(n[::-1])
else:
print("Invalid")
|
81928885e8373265f26459dbb7c5eaac1d887792
|
KozielPiotr/Character-creator-for-Dungeons-and-Dragons
|
/game/mechanics/throws/dice_throw.py
| 407 | 4.0625 | 4 |
"""Throws n-number of n-sided dices"""
from random import randint
def throw_dices(dices, sides):
"""
Throw given number of seleted-sided dices
:param dices: number of dices
:param sides: number of sides of dices
:return: list of every dice result
"""
throw = []
dice = 1
while dice <= dices:
throw.append(randint(1, sides))
dice += 1
return throw
|
560ecc2f6cf8c42714c36e0743b40d525fcfb0b6
|
JAnto2017/pythonVarios
|
/pythonRPi/bucleWhile.py
| 197 | 3.609375 | 4 |
#uso de bucle while
from time import sleep
temp = 10
while temp < 15:
temp+=1
print("La temp está "+str(temp)+" grados")
print("aumento en 1ºC")
sleep(1)
print("Temp >= 15ºC")
|
726bb728209b9d3723953b3744ea5ab0c647fc2e
|
aanikooyan/CSULB-CECS-229
|
/Linear Algebra and Python (2).py
| 13,439 | 4.375 | 4 |
#!/usr/bin/env python
# coding: utf-8
# # VECTOR AND MATRICES IN PYTHON NUMPY LIBRARY
# IMPORTING THE NUMPY LIBRARY
# In[ ]:
import numpy as np
# CREATING VECTOR AND MATRIX USING Numpy array
# In[ ]:
A = np.array([[1,2,3], [4,5,6], [7,8,9]]) # matrix
# In[ ]:
print(A)
print(type(A)) # type of object
print(A.size) # overal size (total number of elements)
print(A.shape) # number rows vs columns
print(A.ndim) # number of dimensions: 1 for vectors, 2 for matrices
# In[ ]:
B = np.array([1,2,3,4]) #Vector
# In[ ]:
print(A)
B
# In[ ]:
B.size
# In[ ]:
B.shape
# In[ ]:
type(B)
# CREATING MATRIX USING mat or matrix
# In[ ]:
N = np.matrix([[1,2,3], [4,5,6], [7,8,9]])
print(N)
print(type(N))
print(N.size)
print(N.shape)
# In[ ]:
M = np.mat([[1,2,3], [4,5,6], [7,8,9]])
print(M)
print(type(M))
print(M.size)
print(M.shape)
# Advantage of using mat function over array for matrix
# In[ ]:
# this is not the correct way to create a 3 by 2 matrix using np.array
M = np.array('1,2;3,4;5,6')
print(M)
print(type(M))
print(M.size)
print(M.shape)
# In[ ]:
M = np.mat('1,2;3,4;5,6')
print(M)
print(type(M))
print(M.size)
print(M.shape)
# CREATING VECTOR AND MATRIX USING random function
# In[ ]:
V = np.random.randn(3)
print(V)
print(type(V))
print(V.size)
print(V.shape)
# In[ ]:
M = np.random.randn(2,4)
print(M)
print(type(M))
print(M.size)
print(M.shape)
# CREATING VECTOR AND MATRIX USING arange
# In[ ]:
V = np.arange(8)
print(V)
print(type(V))
print(V.size)
print(V.shape)
# In[ ]:
M = np.arange(8).reshape(2,4)
print(M)
print(type(M))
print(M.size)
print(M.shape)
**************************************************
ASSIGNMENT:
Create a numerical 4 by 5 matrix using two mehtods:
1 - using random function
2 - using arange function
**************************************************
# In[ ]:
# ACCESS TO THE ELEMENTS OF THE ARRAY
Access to specific elements/rows/columns:
# In[ ]:
print('V = ', V)
print('M = ', M)
# In[ ]:
print(V[1])
print(M[1,2])
# In[ ]:
print(V[:1])
print(V[:2])
# In[ ]:
M = np.random.randn(4,3)
# In[ ]:
print(np.round(M,2))
# In[ ]:
print(np.round(M[:1,:],2))
# In[ ]:
print(np.round(M[:1,:],2))
# In[ ]:
print(np.round(M[:-2,:],2))
Show the array by rows:
# In[ ]:
M
# In[ ]:
i = 0
for rows in M:
i+=1
print('row'+str(i), rows)
**************************************************
ASSIGNMENT:
- Create a numerical 4 by 3 matrix using arange function, and call it M
- Print the followings
- all elements in the first row of M
- all element in the second column of M
- the element in the second row and third column
**************************************************
# In[ ]:
# SPECIAL MATRICES
empty(shape[, dtype, order]): Return a new array of given shape and type, without initializing entries.
empty_like(prototype[, dtype, order, subok]): Return a new array with the same shape and type as a given array.
eye(N[, M, k, dtype, order]): Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity(n[, dtype]): Return the identity array.
ones(shape[, dtype, order]): Return a new array of given shape and type, filled with ones.
ones_like(a[, dtype, order, subok]): Return an array of ones with the same shape and type as a given array.
zeros(shape[, dtype, order]): Return a new array of given shape and type, filled with zeros.
zeros_like(a[, dtype, order, subok]): Return an array of zeros with the same shape and type as a given array.Some examples:
# In[ ]:
np.eye(4)
# In[ ]:
np.identity(3)
# In[ ]:
np.ones(5)
# In[ ]:
np.ones((3,2))
# In[ ]:
np.zeros(5)
# In[ ]:
np.zeros((3,2))
**************************************************
ASSIGNMENT:
Create and print numerical matrices as follows:
- I4 (a 4 by 4 identity matrix)
- a 4 by 5 matrix composed of all 1 as its elements
- a 7 by 8 matrix composed of al1 0 as its elements
**************************************************
# RESHAPING MATRICES: reshape
# In[ ]:
print(M)
print(M.shape)
# In[ ]:
M2 = np.reshape(M, (3,4))
print(M2)
print(M2.shape)
# In[ ]:
V = np.array([0,1,3,6])
print(V)
print(V.shape)
print(V.ndim)
# In[ ]:
W = np.reshape(V,(4,1))
print(W)
print(W.shape)
print(W.ndim)
**************************************************
ASSIGNMENT:
- Create and print a 6 by 4 numerical matrix (using any method you like)
- Reshape and save it as a new 12 by 2 matrix
- Print the new matrix
**************************************************
# FLATTENING A MATRIX
# In[ ]:
A = np.random.randn(2,4)
B = A.flatten()
print('A = ', np.round(A,2))
print('Flatten of A = ', np.round(B,2))
# ADDING/SUBTRACTING/MULTIPLYING SCALAR TO MATRIX
# In[ ]:
A = np.random.randn(4,4)
n = 10
B = A + n
print('A = ', np.round(A,2))
print('A + ',n,' = ', np.round(B,2))
# In[ ]:
C = A - n
print('A = ', np.round(A,2))
print('A - ',n,' = ', np.round(C,2))
# In[ ]:
D = A * n
print('A = ', np.round(A,2))
print('A * ',n,' = ', np.round(D,1))
# In[ ]:
# ADDING A SCALAR TO SPECIFIC ROW/COLUMN
A[1,:] = A[1,:] + 3 # add to the second row only
print('A = ', np.round(A,2))
A[:,1] = A[:,1] + 3 # add to the second column only
print('A = ', np.round(A,2))
# ADD/SUBTRACT MATRICES
# In[ ]:
A = np.random.randn(3,4)
B = np.random.randn(3,4)
C = A + B
D = A - B
E = B - A
print('A = ', np.round(A,2))
print('B = ', np.round(B,2))
print('A + B = ', np.round(C,2))
print('A - B = ', np.round(D,2))
print('B - A = ', np.round(E,2))
**************************************************
ASSIGNMENT:
create two matrices A and B (shape and method on your choice)
calculate the sum and the difference between two matrices and save them as new matrices and print them
**************************************************
# MULTIPLYING VECTORS
INNER PRODUCT OF TWO VECTORS: inner & dot
# In[ ]:
a = np.arange(4)
b = np.arange(4)+3
c = np.inner(a,b)
d = np.dot(a,b)
f = np.sum(a * b)
print('a = ', a)
print('b = ', b)
print('a.b = ', c)
print('a.b = ', d)
print('a.b = ', f)
OUTER PRODUCT OF TWO VECTORS: Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product is:
[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
[ ... .
[aM*b0 aM*bN ]]
# In[ ]:
np.outer(a,b)
**************************************************
ASSIGNMENT:
- create two vectors A and B (shape and method on your choice)
calculate the inner and outer product of the two vectors and save them as new vectors/matrices and print them
**************************************************
# MULTIPLYING A MATRIX BY A SCALAR
# In[ ]:
A = np.random.randn(3,3)
n = 10
B = A*n
print('A = ', np.round(A,2))
print('B = ', np.round(B,1))
# MULTIPLYING TWO MATRICES
element-wise multiplication
# In[ ]:
A = np.random.randn(5,3)
B = np.random.randn(5,3)
C = A * B
print('A = ', np.round(A,2))
print('B = ', np.round(B,2))
print('A * B = ', np.round(C,2))
print('dimension A = ', A.shape)
print('dimension B = ', B.shape)
print('dimension A * B = ', C.shape)
**************************************************
ASSIGNMENT:
- create two matrices A and B (shape and method on your choice)
calculate the element-wise product of the two matrices and save them as new matrix and print them
**************************************************dot product
# In[ ]:
A = np.random.randn(3,2)
B = np.random.randn(2,4)
# 3 METHODS:
# METHOD 1:
C = A.dot(B)
# METHOD 2:
D = np.dot(A,B)
# METHOD 3:
E = A @ B
print('A = ', np.round(A,2))
print('B = ', np.round(B,2))
print('Method 1: A . B = ', np.round(C,2))
print('Method 2: A . B = ', np.round(D,2))
print('Method 3: A . B = ', np.round(E,2))
print('dimension A = ', A.shape)
print('dimension B = ', B.shape)
print('dimension A . B = ', C.shape)
**************************************************
ASSIGNMENT:
- create two matrices A and B (shape and method on your choice)
calculate the dot product of the two matrices using three methods and save them as new matrices and print them
**************************************************
# DIAGONAL OF A MATRIX: diagonal
# In[ ]:
A_diag = A.diagonal()
print('A = ', A)
print('diagonal of A is:', A_diag)
# TRACE OF A MATRIX: trace
# In[ ]:
A_trace = A.trace()
print('A = ', A)
print('Trace of A is:', A_trace)
# TRANSPOSING A MATRIX
# In[ ]:
A = np.random.randn(3,4)
A_tran = A.T
print('A = ', np.round(A,2))
print('Transpose of A = ', np.round(A_tran,2))
print('dimension A = ', A.shape)
print('dimension Transpose(A) = ', A_tran.shape)
**************************************************
ASSIGNMENT:
- create matrix A (diagonal shape but method on your choice)
calculate the digonal, trace, and Trnspose of the matrix and print them
**************************************************
# # np.linalg
ADDITIONAL OPERATIONS INCLUDING:
- INVERTING
- DETERMINANT
- RANK
- EIGENVALUES AND EIGENVECTORS
- NORM
- SOLVING SYSTEM OF EQUATIONS
# In[ ]:
import numpy as np
from numpy import linalg as LA
# INVERTING A MATRIX
# In[ ]:
A = np.random.randn(4,4)
A = np.round(A,2)
print(A)
# In[ ]:
# A_inv = np.linalg.inv(A)
A_inv = LA.inv(A)
A_inv = np.round(A_inv, 2)
print('A = ', A)
print('Inverse of A = ', A_inv)
print('dimension A = ', A.shape)
print('dimension Inverse(A) = ', A_inv.shape)
**************************************************
ASSIGNMENT:
-Create a matrix (method on your choice)
- Calculate the inverse of the matrix and save it into a new matrix and print them
**************************************************
# DETERMINANT OF MATRIX: det
# In[ ]:
print('A = ', A)
print('Shape of Matrix A is:', A.shape)
print('Determinant of Matrix A is:', LA.det(A))
**************************************************
ASSIGNMENT:
- Calculate the determinant of the matrix you created and print them
**************************************************
# RANK OF A MATRIX: matrix_rank
# In[ ]:
print('A = ', A)
print('Shape of Matrix A is:', A.shape)
print('Rank of Matrix A is:', LA.matrix_rank(A))
# EIGEN VALUES AND EIGEN VECTORS OF A MATRIX: eig
# In[ ]:
eigenvalues, eigenvectors = LA.eig(A)
print('A = ', A)
print('Eigen values of A:', eigenvalues)
print('Number of the Eigenvalues',eigenvalues.size)
print('Eigen vctors of A:', eigenvectors)
print('Shape of the Eigenvectors',eigenvectors.shape)
**************************************************
ASSIGNMENT:
- Calculate the Eigenvalues and Eigenvectors of the matrix you created and print them
**************************************************
# NORM OF A VECTOR/MATRIX: norm
# In[ ]:
# Vector
a = np.arange(6)
n = LA.norm(a)
print('a = ', a)
print('norm(a) = ', n)
Use of norm to calculate the distance between two points
# In[ ]:
a = np.array([0,0])
b = np.array([2,1])
d = LA.norm(a-b)
print('Euclidian Distance between a and b =', d)
# In[ ]:
# Matrix
A = np.arange(4).reshape(2,2)
N = LA.norm(A)
print('A = ', A)
print('norm(A) = ', N)
**************************************************
ASSIGNMENT:
- create two vectors. calculate their norms and also the norm of their difference, and print them
- create a matrix and calculate its norm, and print them
**************************************************
# SOLVING LINEAR MATRIX EQUATION OR SYSTEM OF SCALAR EQUATIONS
# Exact solution: solve
If the general form of the system of equations is as :
A.x = b
Given matrix A and vector b, the goal is to computes the exact solution xExample:
4x1 + 2x2 = 8
-3x1 + 5x2 = 11
# In[ ]:
A = np.array([[4,-3],[2,5]])
b = np.array([8,11])
x = LA.solve(A, b)
for i in range(len(x)):
print('x'+str(i+1)+' = ',x[i])
To check that the solution is correct: True for correct, False for incorrect
# In[ ]:
if np.allclose(np.dot(A,x),b):
print('The solution is correct!')
else:
print('The solution is NOT correct!')
print(np.allclose(np.dot(A,x),b))
# The Least Square solution: lstsq
If the general form of the system of equations is as :
A.x = b
Solves the equation by computing a vector x that minimizes the L2-norm
# In[ ]:
A = np.array([[4,-3],[2,5]])
b = np.array([8,11])
x, res, rnk, s = LA.lstsq(A, b)
print(x)
# In[ ]:
if np.allclose(np.dot(A,x),b):
print('The solution is correct!')
else:
print('The solution is NOT correct!')
**************************************************
ASSIGNMENT:
Define a system of three equations
solve it using two methods:
- exact soltuion
- least square (L2-norm)
**************************************************
# SINGULAR VALUE DECOMPOSITION: svd
Singular Value Decomposition (SVD) can be thought of as an extension of the eigenvalue problem to matrices that are not square. Returns:
u :
Unitary array(s). The first a.ndim - 2 dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices.
s :
Vector(s) with the singular values, within each vector sorted in descending order. The first a.ndim - 2 dimensions have the same size as those of the input a.
vh :
Unitary array(s). The first a.ndim - 2 dimensions have the same size as those of the input a. The size of the last two dimensions depends on the value of full_matrices. Only returned when compute_uv is True.
# In[ ]:
A = np.array([[1,2,3],[4,5,6]])
u,s,Vh = LA.svd(A)
# In[ ]:
print(u)
# In[ ]:
print(s)
# In[ ]:
|
4c6311954387c2f68fc7d19b87ffe7996070b37c
|
YosefatJQ/Python-Course-TC1014
|
/wsq10.py
| 554 | 3.765625 | 4 |
def total(l):
x=0
sum = 0
while(x<10):
sum = sum + l[x]
x=x+1
return sum
def promedio(t):
promedio = t/10
return promedio
def standarddeviation(l, p):
x=0
sum = 0
while(x<10):
s = (l[x]-p)**(2.0)
sum = sum+s
x=x+1
s = (sum/9)**(.5)
return s
x=0
l=[]
print("This is a list of 10 numbers.")
while (x<10):
num = int(input("Give me the a number: "))
l.append(num)
x=x+1
t=total(l)
p=promedio(t)
print("\nList: ",l)
print("\nTotal: ",total(l))
print("\nPromedio: ",promedio(t))
print("\nStandard Deviation: ",standarddeviation(l, p))
|
0922e3067fb1b997dfde1a6ca9dc80580c62db09
|
Yustyn/mebli_db
|
/test.py
| 1,506 | 3.796875 | 4 |
import unittest
from methods import Admin, SuperAdmin
class SuperAdminTests(unittest.TestCase):
# valid data
VALID_EMAIL = 'Correct@email.com'
VALID_PASSWORD = 'AQwe12!_'
# invalid data
# INVALID_INIT = ('Incorrect@email.com', 12345678,)
INVALID_EMAIL = 'Incorrect@@email..com'
INVALID_PASSWORD = 12345678
def setUp(self):
# # create SuperAdmin
# self.admin = SuperAdmin(self.VALID_EMAIL, self.VALID_PASSWORD)
pass
def test_create_SuperAdmin(self):
# Test valid data
super_admin_valid = SuperAdmin(self.VALID_EMAIL, self.VALID_PASSWORD)
self.assertIsInstance(super_admin_valid, SuperAdmin)
print('Test 1.1: passed')
def test_create_invalid_email_SuperAdmin(self):
# Test invalid data
super_admin_invalid = SuperAdmin(
self.INVALID_EMAIL, self.INVALID_PASSWORD)
self.assertIsInstance(self.INVALID_EMAIL, str)
print('Test 1.2: passed')
def test_create_invalid_password_SuperAdmin(self):
super_admin_invalid = SuperAdmin(
self.INVALID_EMAIL, self.INVALID_PASSWORD)
self.assertIsInstance(self.INVALID_PASSWORD, str)
print('Test 1.3: passed')
def test_create_invalid_SuperAdmin(self):
super_admin_invalid = SuperAdmin(
self.INVALID_EMAIL, self.INVALID_PASSWORD)
self.assertIsInstance(super_admin_invalid, SuperAdmin,)
print('Test 1.4: passed')
if __name__ == '__main__':
unittest.main()
|
33603407b4541e901aade723adba8726ee8a5635
|
AKZMH/Python_Algos
|
/Урок 1. Практическое задание/task_4.py
| 1,954 | 3.71875 | 4 |
"""
Задание 4. Написать программу, которая генерирует в указанных пользователем границах:
случайное целое число;
случайное вещественное число;
случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы.
Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно.
Подсказка:
Нужно обойтись без ф-ций randint() и uniform()
Использование этих ф-ций = задание не засчитывается
Функцию random() использовать можно
Опирайтесь на пример к уроку
"""
from random import random
left_int = int(input('введите минимальное целое число: '))
right_int = int(input('введите максимальное целое число'))
if left_int != right_int:
rand_int = int(random() * (right_int - left_int + 1)) + left_int
print(f'случайное целое число в заданном диапазоне {rand_int}')
else:
print('Вы ввели одинаковые числа!')
left = float(input('введите минимальное вещественное число: '))
right = float(input('введите максимальное вещественное число: '))
if left != right:
rand = random() * (right - left) + left
print(f'случайное вещественное число в заданном диапазоне {rand}')
else:
print('Вы ввели одинаковые числа!')
|
c688cd33c59845b2dba167bcef914616a18dd473
|
1Mike1/Functional-programming-in-Python
|
/Functional Programming_In_Python.py
| 4,148 | 3.796875 | 4 |
'''
Lets Understaned Higher Order Function (HOF)
HOF if Function which will accept argument as function
and return function as well.
NOTE : Use Debugger to Understand the flow of code.
'''
''' Example '''
# 1
print('\nHigher Order Function\n')
def Login(func,username,password):
isValid = func(username, password)
if isValid:
return f'Welcome {username}'
else:
return 'Invalid username or password... ?'
def validate_user_data(temp_uname, temp_pass):
if temp_uname.strip()=='Mike' and temp_pass.strip()=='mikeee128':
return True
def get_user_details():
uname = str(input('Enter your username:'))
passwrd = str(input('Enter your password:'))
return uname,passwrd
if __name__=='__main__':
usrname, paswd = get_user_details()
print(f'1.{Login(validate_user_data, usrname, paswd)}')
'''
In above example i have created 3 function but if you Notice
In "Login" Function i have passed the "validate_user_data" as
an arrgument and used that function future in my code.
'''
print('#'*58)
####################################################################################################################################################################################################################################################################################################################
''' Currying '''
'''
We can use higher-order functions to convert a function that takes
multiple arguments into a chain of functions that each take a single
argument. More specifically, given a function f(x, y), we can define
a function g such that g(x)(y) is equivalent to f(x, y). Here, g is a
higher-order function that takes in a single argument x and returns
another function that takes in a single argument y. This transformation
is called currying.
'''
''' Example '''
print('\n\nCurrying\n')
# 1.
def get_1st_number(num_1):
def get_2nd_number(num_2):
return num_1+num_2
return get_2nd_number
if __name__=='__main__':
print(f'1. Addition of two Number: {get_1st_number(10)(20)}')
''' The above function is pure function because is completely depend on input.'''
# 2.
def pas_function(user_func):
def get_x(x):
def get_y(y):
return user_func(x,y)
return get_y
return get_x
def mul_function(a,b):
return a+b
pas_func = pas_function(mul_function)
print(f'2. Currying With user define or pre define function:{pas_func(2)(4)}\n')
'''
In above example you can apply any function which applicable for two arrguments such as "max","min", "pow". etc.
You can also passs user define function ..in our case i have passed "mul_function", you guys can yours
Function but make sure that function will work on 2 prameter.
'''
print('#'*58)
####################################################################################################################################################################################################################################################################################################################
''' Higher Order Function With Currying '''
print('\nHigher order fucntion with Currying\n')
#1.
def Login(func,welcom_func):
def get_username(uname):
def get_password(pas):
isValid = func(get_user_details,uname,pas)
if isValid:
return welcom_func(uname)
else:
return Invalid_user()
return get_password
return get_username
def check_valid_User(func_user_input,usernm,userpas):
tempUname,tempPass = func_user_input()
return ((tempUname.strip()==usernm) and (tempPass.strip()==userpas.strip()))
def welcome_user(uname):
return f'Welcome {uname}'
def Invalid_user():
return 'invalid username or password'
def get_user_details():
tempName = str(input('Username:'))
tempPass = str(input('Password:'))
return str(tempName).strip(), str(tempPass).strip()
login = Login(check_valid_User,welcome_user)
print(login('Mike')('Mikeee'))
print('#'*58)
|
72961f6c43c619457c2c704a7dd2eed520403943
|
JhonnelN/examen_isep
|
/drops.py
| 470 | 3.953125 | 4 |
def drops(numero):
# variable de tipo string vacia para poder anidar los resultados
resultado = ""
if numero % 3 == 0:
resultado += "Plic"
if numero % 5 == 0:
resultado += "Plac"
if numero % 7 == 0:
resultado += "Ploc"
return resultado or numero # Shortcircuit
# Se convierte el input en un caracter de tipo entero para la validacion en
# los condicionales
print(drops(int(input("Introduce numero: "))))
|
124f02540d0b7712a73b5d2e2e03868ac809b791
|
anikaator/CodingPractice
|
/Datastructures/HashMap/Basic/Python/main.py
| 687 | 4.15625 | 4 |
def main():
# Use of dict
contacts = {}
contacts['abc'] = 81
contacts['pqr'] = 21
contacts['xyz'] = 99
def print_dict():
for k,v in contacts.items():
print 'dict[', k, '] = ', v
print("Length of dict is %s" % len(contacts))
print("Dict contains:")
print_dict()
print("Deleting dict[key]:")
del(contacts['abc'])
print_dict()
print("Checking if pqr key is present %r :" % ('pqr' in contacts))
print("Deleting non existant key \'lmn\'")
try:
del(contacts['lmn'])
except KeyError:
print("Caught error : KeyError:item does not exist")
if __name__ == "__main__":
main()
|
5f542a3e4e1d4d187757e4133471ec488f8c007c
|
MaratAG/Netology_Python_T9
|
/Netology_Task_9.py
| 2,849 | 3.578125 | 4 |
"""Программа расчета необходимых для готовки блюд ингридиентов."""
def return_shop_list(cook_book, dishes, person_count):
"""Расчет необходимых для покупки ингридиентов."""
shop_list = {}
for dish in dishes:
for ingridient in cook_book[dish]:
new_shop_list_item = dict(ingridient)
new_shop_list_item['quantity'] *= person_count
if new_shop_list_item['ingridient_name'] not in shop_list:
shop_list[new_shop_list_item['ingridient_name']] \
= new_shop_list_item
else:
shop_list[new_shop_list_item['ingridient_name']]['quantity'] \
+= new_shop_list_item['quantity']
return shop_list
def return_cook_book():
"""Процедура подготовки книги рецептов."""
cook_book = {}
with open('cook_book.txt', encoding='utf8') as our_file:
finish_reciept = True
for line in our_file:
line = line.strip().lower()
if finish_reciept:
dish = line
dish_reciept = []
finish_reciept = False
# Строка с количеством ингридиентов
# не требуется, поэтому ее пропускаем.
our_file.readline()
else:
if not line:
cook_book[dish] = dish_reciept
finish_reciept = True
else:
our_ingridient = line.split('|')
dish_ingridients = {}
dish_ingridients['ingridient_name'] = \
our_ingridient[0].strip()
dish_ingridients['quantity'] = float(our_ingridient[1])
dish_ingridients['measure'] = our_ingridient[2].strip()
dish_reciept.append(dish_ingridients)
cook_book[dish] = dish_reciept
return cook_book
def return_dishes():
"""Запрашиваем наименование блюд."""
return input(
'Введите блюда в расчете на одного человека через запятую: ').\
lower().split(', ')
def print_shop_list(p_list):
"""Выводим содержимое листа покупок."""
for p_list_item in p_list.values():
print('{ingridient_name} {quantity} {measure}'.format(**p_list_item))
def main():
"""Основная процедура."""
person_count = int(input('Введите количество человек: '))
dishes = return_dishes()
cook_book = return_cook_book()
print_shop_list(return_shop_list(cook_book, dishes, person_count))
main()
|
9ce433080385f3fc6ac6f9e1460a57d84b8e0273
|
rlyyah/erp_for_bill_gates
|
/inventory/inventory.py
| 10,809 | 3.5 | 4 |
""" Inventory module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* name (string): Name of item
* manufacturer (string)
* purchase_year (number): Year of purchase
* durability (number): Years it can be used
"""
# everything you'll need is imported:
# User interface module
import ui
# data manager module
import data_manager
# common module
import common
def handle_menu_inventory_module():
options = ["Show table",
"Add item to table",
"Remove item from the table",
"Update item in table",
"Available items",
'Show average durability by manufacturers']
menu_title = "Inventory module menu"
menu_title = ui.return_headline_for_menu_title_(menu_title)
exit_message = "Back to main menu"
ui.print_menu(menu_title, options, exit_message)
def choose_inventory_module():
FILE_PATH = 'inventory/inventory.csv'
TITLE_LIST = ['id', 'name', 'manufacturer', 'purchase_year', 'durability']
table = data_manager.get_table_from_file(FILE_PATH)
inputs = ui.get_inputs(["Please enter a number: "], "")
INDEX_OF_FIRST_ELEMENT_OF_INPUTS_LIST = 0
option = inputs[INDEX_OF_FIRST_ELEMENT_OF_INPUTS_LIST]
if option == "1":
common.clear_terminal()
ui.blank_line()
ui.headline('---- TABLE WITH INVENTORY ----')
ui.blank_line()
show_table(data_manager.get_table_from_file(FILE_PATH)) # ONLY THIS NEEDEd TO PRINT TABLE RIGHT NOW
elif option == "2":
# list_from_file = data_manager.get_table_from_file(FILE_PATH)
# data_manager.write_table_to_file(FILE_PATH, add(list_from_file))
common.clear_terminal()
ui.blank_line()
data_manager.write_table_to_file(FILE_PATH, add(data_manager.get_table_from_file(FILE_PATH))) # same as above but in one line
elif option == "3":
common.clear_terminal()
ui.headline('---- TABLE WITH INVENTORY ----')
table = data_manager.get_table_from_file(FILE_PATH)
ui.blank_line()
show_table(data_manager.get_table_from_file(FILE_PATH)) # ONLY THIS NEEDEd TO PRINT TABLE RIGHT NOW
ui.blank_line()
ui.blank_line()
ui.headline('Removing item from inventory')
# header = ui.headline('Removing item from inventory')
data_manager.write_table_to_file(FILE_PATH, remove(table, find_id(table, ui.get_inputs(['Insert index of file to remove'], "REMOVE"))))
# data_manager.write_table_to_file(FILE_PATH, remove(table, find_id(table, ui.get_inputs(['Insert index of file to remove'], header))))
elif option == "4":
common.clear_terminal()
ui.blank_line()
ui.blank_line()
ui.headline('---- EDITING EXISTING RECORD ----')
table = data_manager.get_table_from_file(FILE_PATH)
ui.blank_line()
show_table(data_manager.get_table_from_file(FILE_PATH)) # ONLY THIS NEEDEd TO PRINT TABLE RIGHT NOW
data_manager.write_table_to_file(FILE_PATH, update(table, find_id(table, ui.get_inputs(['Insert index of file to update'], "UPDATING"))))
elif option == "5":
common.clear_terminal()
ui.headline('---- GETTING AVAILABLE ITEMS ---- ')
TITLE_LIST = ['']
year = ui.get_inputs(TITLE_LIST, "Please enter information about year")
INDEX_OF_FIRST_ELEMENT_OF_YEAR_LIST = 0
year = int(year[INDEX_OF_FIRST_ELEMENT_OF_YEAR_LIST])
ui.blank_line()
ui.headline('ITEMS THAT MEETS YOUR CONDITIONS')
ui.blank_line()
show_table(get_available_items(table, year))
elif option == "6":
common.clear_terminal()
ui.blank_line()
ui.blank_line()
ui.headline('---- GETTING AVERAGE DURABILITY BY MANUFRACTURERS ---- ')
table = data_manager.get_table_from_file(FILE_PATH)
ui.blank_line()
ui.print_dictionary(get_average_durability_by_manufacturers(table))
elif option == "0":
common.clear_terminal()
return False
else:
common.clear_terminal()
print('Please enter number of one of the options')
# raise KeyError("There is no such option.")
return True
def find_id(table, index):
INDEX_POSITION = 0
INDEX_OF_FIRST_ELEMENT_OF_INDEX_LIST = 0
NUMBER_TO_DISTRACT_BECAUES_INDEXING_IS_FROM_ZER0 = 1
number_of_id = table[int(index[INDEX_OF_FIRST_ELEMENT_OF_INDEX_LIST]) - NUMBER_TO_DISTRACT_BECAUES_INDEXING_IS_FROM_ZER0][INDEX_POSITION]
# number_of_id = number_of_id - 1
return number_of_id
def start_module():
"""
Starts this module and displays its menu.
* User can access default special features from here.
* User can go back to main menu from here.
Returns:
None
"""
is_running = True
while is_running:
handle_menu_inventory_module()
try:
is_running = choose_inventory_module()
except KeyError as err:
ui.print_error_message(str(err), 'There is no such option')
def showing_table(table, FILE_PATH): # TODO
common.clear_terminal()
ui.blank_line()
ui.headline('---- TABLE WITH INVENTORY ----')
ui.blank_line()
show_table(data_manager.get_table_from_file(FILE_PATH)) # ONLY THIS NEEDEd TO PRINT TABLE RIGHT NOW
def show_table(table):
"""
Display a table
Args:
table (list): list of lists to be displayed.
Returns:
None
"""
TITLE_LIST = ['id', 'name', 'manufacturer', 'purchase_year', 'durability']
ui.print_table(table, TITLE_LIST)
def add(table):
"""
Asks user for input and adds it into the table.
Args:
table (list): table to add new record to
Returns:
list: Table with a new record
"""
ui.headline('Adding item to inventory')
id = common.generate_random(table)
# without id!!!!! :
# TITLE_LIST = ['id: ', 'What is the item? ', 'Who manufactured the item? ', 'What is the purchase year? [year]', 'What is the durability? [year] ']
TITLE_LIST = ['What is the item? ', 'Who manufactured the item? ', 'What is the purchase year? [year]', 'What is the durability? [year] ']
ask_input = ui.get_inputs(TITLE_LIST, 'Please enter information about an item')
INDEX_OF_ID_TO_ADD_TO_ASK_INPUT = 0
ask_input.insert(INDEX_OF_ID_TO_ADD_TO_ASK_INPUT, id)
table.append(ask_input)
return table
def remove(table, id_):
"""
Remove a record with a given id from the table.
Args:
table (list): table to remove a record from
id_ (str): id of a record to be removed
Returns:
list: Table without specified record.
"""
ID_POSITION = 0
for index, record in enumerate(table):
if record[ID_POSITION] == id_:
table.pop(index)
return table
def update(table, id_):
"""
Updates specified record in the table. Ask users for new data.
Args:
table (list): list in which record should be updated
id_ (str): id of a record to update
Returns:
list: table with updated record
"""
TITLE_LIST = ['What is the item? ', 'Who manufactured the item? ', 'What is the purchase year? [year]', 'What is the durability? [year] ']
ask_input = ui.get_inputs(TITLE_LIST, 'Please enter information about an item')
# print('ask input: ', ask_input)
# print('ask input 0:', ask_input[0])
ID_POSITION = 0
INDEX_OF_SECOND_ELEMENT_OF_RECORD = 1
INDEX_OF_THIRD_ELEMENT_OF_RECORD = 2
INDEX_OF_FOURTH_ELEMENT_OF_RECORD = 3
INDEX_OF_FIVE_ELEMENT_OF_RECORD = 4
INDEX_OF_FIRST_ELEMENT_OF_ASK_INPUT = 0
INDEX_OF_SECOND_ELEMENT_OF_ASK_INPUT = 1
INDEX_OF_THIRD_ELEMENT_OF_ASK_INPUT = 2
INDEX_OF_FOURTH_ELEMENT_OF_ASK_INPUT = 3
for record in table:
if record[ID_POSITION] == id_:
# print(record[ID_POSITION])
# print(record)
record[INDEX_OF_SECOND_ELEMENT_OF_RECORD] = ask_input[INDEX_OF_FIRST_ELEMENT_OF_ASK_INPUT]
record[INDEX_OF_THIRD_ELEMENT_OF_RECORD] = ask_input[INDEX_OF_SECOND_ELEMENT_OF_ASK_INPUT]
record[INDEX_OF_FOURTH_ELEMENT_OF_RECORD] = ask_input[INDEX_OF_THIRD_ELEMENT_OF_ASK_INPUT]
record[INDEX_OF_FIVE_ELEMENT_OF_RECORD] = ask_input[INDEX_OF_FOURTH_ELEMENT_OF_ASK_INPUT]
return table
# special functions:
# ------------------
def get_available_items(table, year):
"""
Question: Which items have not exceeded their durability yet (in a given year)?
Args:
table (list): data table to work on
year (number)
Returns:
list: list of lists (the inner list contains the whole row with their actual data types)
"""
# ACTUAL_YEAR = 2019
# TITLE_LIST = ['What is the year you want to know the items will be still available? ']
# year = ui.get_inputs(TITLE_LIST, "Please enter information about year")
PURCHASE_YEAR_INDEX = 3
DURABILITY_INDEX = 4
list_of_available_items = []
for elem in range(len(table)):
# print(table[elem])
# print(table[elem][PURCHASE_YEAR_INDEX])
table[elem][PURCHASE_YEAR_INDEX] = int(table[elem][PURCHASE_YEAR_INDEX])
# print(table[elem][PURCHASE_YEAR_INDEX])
table[elem][DURABILITY_INDEX] = int(table[elem][DURABILITY_INDEX])
# print(table[elem][DURABILITY_INDEX])
expiration_difference = table[elem][PURCHASE_YEAR_INDEX] + table[elem][DURABILITY_INDEX]
# print('expi diff: ', expiration_difference)
if expiration_difference >= year:
list_of_available_items.append(table[elem])
# print(list_of_available_items)
return list_of_available_items
def get_average_durability_by_manufacturers(table):
"""
Question: What are the average durability times for each manufacturer?
Args:
table (list): data table to work on
Returns:
dict: a dictionary with this structure: { [manufacturer] : [avg] }
"""
list_of_manufacturers = []
manufacturer_index = 2
# print(table)
for elem in table:
# print(elem)
list_of_manufacturers.append(elem[manufacturer_index])
# print()
# print(list_of_manufacturers)
adding_one_to_count_of_each_manufacturers = 1
dictionary_of_manufacturers = {}
for elem in list_of_manufacturers:
if elem in dictionary_of_manufacturers:
dictionary_of_manufacturers[elem] += adding_one_to_count_of_each_manufacturers
else:
dictionary_of_manufacturers[elem] = adding_one_to_count_of_each_manufacturers
# print(dictionary_of_manufacturers)
return dictionary_of_manufacturers
|
8e9a3b4479db346d089f9926031dcc1a021b3fb8
|
tuouo/smallTools
|
/files/findFileByName.py
| 2,820 | 3.765625 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
'''
Only under os.path.abspath('.'), a file can be distinguish as file.
'''
def selectCondition(fileName, toFind, opt, path = '.'):
flag = False
if opt == 'name':
if toFind == fileName.split('.')[0]:
flag = True
elif toFind == fileName:
flag = True
elif opt == 'pattern':
flag = True if toFind in fileName else False
elif opt == 'suffix':
flag = True if toFind == fileName.split('.')[-1] else False
elif opt == 'size':
flag = True if toFind == os.path.getsize(path) else False
return flag
def findFileFirst(toFind, root = '.', opt = 'name'):
dirlist = os.listdir(root)
for x in dirlist:
path = os.path.join(root, x)
if os.path.isfile(path) and selectCondition(x, toFind, opt, path):
print(path)
for x in dirlist:
path = os.path.join(root, x)
if os.path.isdir(path):
findFileFirst(toFind, path, opt)
def findFileOrder(toFind = 'txt', root = '.', opt = 'name'):
dirs = []
for x in os.listdir(root):
path = os.path.join(root, x)
if os.path.isfile(path) and selectCondition(x, toFind, opt, path):
print(path)
elif os.path.isdir(path):
dirs.append(path)
for dir in dirs:
findFileOrder(toFind, dir, opt)
def findFileFirstByPattern(pattern = 'txt', root = '.'):
findFileFirst(pattern, root, 'pattern')
def findFileFirstByName(name = '', root = '.'):
findFileFirst(name, root, 'name')
def findFileFirstBySuffix(suffix = 'txt', root = '.'):
findFileFirst(suffix, root, 'suffix')
def findFileOrderByPattern(pattern = 'txt', root = '.'):
findFileOrder(pattern, root, 'pattern')
def findFileOrderByName(name = '', root = '.'):
findFileOrder(name, root, 'name')
def findFileOrderBySuffix(suffix = 'txt', root = '.'):
findFileOrder(suffix, root, 'suffix')
def test_find(func):
func('.md')
print("End of one findding.")
func('md')
print("End of one findding.")
func('otf', r'C:\soft')
print("End of one findding.")
func('.gitconfig', r'C:')
print("End of one findding.")
func('pdf', 'C:\\Users\\tuouo_000\\Documents\\其它')
print()
#test_find(findFileFirstByPattern)
#test_find(findFileFirstByName)
#test_find(findFileFirstBySuffix)
#test_find(findFileOrderByPattern)
#test_find(findFileOrderByName)
#test_find(findFileOrderBySuffix)
def findFileFirstBySuffix(size = '58464', root = '.'):
findFileFirst(size, root, 'size')
def findFileOrderByPattern(size = '58464', root = '.'):
findFileOrder(size, root, 'size')
def test_find_size(func):
func(58464, r'C:\soft') #\Inconsolata
#test_find_size(findFileFirstBySuffix)
#test_find_size(findFileOrderByPattern)
|
d5dfbda5011eac36fe7d54e581e5b28d52d11c17
|
lambdaydoty/programming-bitcoin
|
/ecc.py
| 5,703 | 3.640625 | 4 |
from random import randint
class FieldElement:
def __init__(self, num, prime):
if num >= prime or num < 0:
error = 'Num {} not in field range 0 to {}'.format(num, prime - 1)
raise ValueError(error)
self.num = num
self.prime = prime
def __repr__(self):
return 'F({})'.format(self.num)
# return 'F_{}( {} )'.format(self.prime, self.num)
def __eq__(self, other):
if other is None:
return False
elif other == 0:
return self.num == 0
else:
return self.num == other.num and self.prime == other.prime
def __ne__(self, other):
return not self == other
def __add__(self, other):
return self.arithmetic(other, lambda x, y: x + y)
def __sub__(self, other):
return self.arithmetic(other, lambda x, y: x - y)
def __mul__(self, other):
return self.arithmetic(other, lambda x, y: x * y)
def __rmul__(self, m):
p = self.prime
n = self.num
return self.__class__((n * m) % p, p)
def __pow__(self, exponent):
p = self.prime
n = self.num
return self.__class__(pow(n, exponent, p), p)
def __truediv__(self, other):
return self * (other ** -1)
def arithmetic(self, other, op):
self.assertSamePrime(other)
p = self.prime
n = op(self.num, other.num) % p
return self.__class__(n, p)
def assertSamePrime(self, other):
if other is None:
raise ValueError('...')
if self.prime != other.prime:
raise TypeError('...')
return
#
P = 2**256 - 2**32 - 977
#
class S256Field(FieldElement):
def __init__(self, num, prime=None):
super().__init__(num, P)
def __repr__(self):
return '{:x}'.format(self.num).zfill(64)
#
class Point:
# y^2 = x^3 + ax + b
def __init__(self, x, y, a, b):
self.x = x
self.y = y
self.a = a
self.b = b
if x is None and y is None:
return
elif y**2 == x**3 + a*x + b:
return
error = 'Not a valid Point: (x,y,a,b)=({},{},{},{})'.format(x, y, a, b)
raise ValueError(error)
def __eq__(self, other):
return self.x == other.x and \
self.y == other.y and \
self.a == other.a and \
self.b == other.b
def __ne__(self, other):
return not self == other
def __repr__(self):
x = self.x
y = self.y
a = self.a
b = self.b
return 'Point({},{})'.format(x, y)
# return 'Point_{{{}x+{}}}( {}, {} )'.format(a, b, x, y)
def assertSameCurve(self, other):
if other is None:
raise ValueError('...')
if self.a != other.a or self.b != other.b:
raise TypeError('...')
return
def __add__(self, other):
self.assertSameCurve(other)
a = self.a
b = self.b
infinity = self.__class__(None, None, a, b)
if self.x is None:
return other
elif other.x is None:
return self
elif self == other and self.y != 0:
x1 = self.x
y1 = self.y
s = (3 * (x1**2) + a) / (2*y1)
x = s**2 - x1 - x1
y = s * (x1 - x) - y1
return self.__class__(x, y, a, b)
elif self == other and 2*self.y == 0:
return infinity
elif self.x == other.x and self.y != other.y:
return infinity
else:
x1 = self.x
y1 = self.y
x2 = other.x
y2 = other.y
s = (y2 - y1) / (x2 - x1)
x = s**2 - x1 - x2
y = s * (x1 - x) - y1
return self.__class__(x, y, a, b)
def __rmul__(self, n):
a = self.a
b = self.b
curr = self
acc = self.__class__(None, None, a, b)
while n > 0:
if n & 1:
acc = acc + curr
curr = curr + curr
n >>= 1
return acc
#
Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
#
class S256Point(Point):
def __init__(self, x, y, a=None, b=None):
a = S256Field(0)
b = S256Field(7)
if type(x) == int and type(y) == int:
super().__init__(S256Field(x), S256Field(y), a, b)
else:
super().__init__(x, y, a, b) # for Inf Point
def __rmul__(self, n):
if self.x.num == Gx and self.y.num == Gy:
return super().__rmul__(n % N)
else:
return super().__rmul__(n)
def verify(self, z, sig):
s_inv = pow(sig.s, N-2, N)
u = (z * s_inv) % N
v = (sig.r * s_inv) % N
comb = u * G + v * self
return comb.x.num == sig.r
#
G = S256Point(Gx, Gy)
Z = S256Point(None, None)
#
class Signature:
def __init__(self, r, s):
self.r = r
self.s = s
def __repr__(self):
return 'Signature({:x},{:x})'.format(self.r, self.s)
#
class PrivateKey:
def __init__(self, e):
self.e = e
self.point = e * G
def hex(self):
return '{:x}'.format(self.e).zfill(64)
def sign(self, z):
k = randint(0, N) # !!
r = (k*G).x.num
k_inv = pow(k, N-2, N)
s = ((z + r * self.e) * k_inv) % N
# https://bitcoin.stackexchange.com/questions/85946/low-s-value-in-bitcoin-signature
if s > N/2:
s = N - s
return Signature(r, s)
|
67ab4071647ea24bc2965f2226c90da56a89506b
|
umanelluri/test2
|
/sring+fun.py
| 197 | 3.765625 | 4 |
a="hello world!123"
def let_dig(a):
l=d=0
for i in range(len(a)):
if a[i].isalpha():
l=l+1
elif a[i].isdigit():
d=d+1
print('letters are',l,'\n','digits are',d)
let_dig(a)
|
e0338b9f8e57f5d54473d12ddd203f2bb216611e
|
BladeSides/Mathics
|
/Pytha.py
| 1,382 | 3.9375 | 4 |
print("PYTHAGOREAN TRIPLETS: \n")
def run():
ar = []
y = 1
x = input("\nEnter the termination value or range of values (initial and final value)\n>>> ")
for k in range (len(x)):
if x[k] != ',':
ar.append(x[k])
x = "".join(ar)
l = x.split(" ")
if(l.count("")>0):
l.remove("")
if(not l[0].isdigit() and (l[0] != "inrange" or l[0] != "range")):
print("Please enter a valid range (initial value must be smaller than final value)")
return
elif(not l[0].isdigit() and len(l)<2):
print("Please enter a valid range (initial value must be smaller than final value)")
return
if((l[0] == "inrange" or l[0] == "range")):
x=l[2]
y=l[1]
elif(len(l)>1):
x=l[1]
y=l[0]
if(int(x) < int(y)):
print("Please enter a valid range (initial value must be smaller than final value)")
if(not x.isdigit()):
print("Please enter a valid integer")
return
print()
x=int(x)
if int(y)>0:
y=int(y)
else:
y=1
s=0
for i in range(y, x+1):
for j in range(1, i+1):
if(int(((i**2 + j**2)**(1/2)))==((i**2 + j**2)**(1/2))):
print(i, "\u00b2 + ", j, "\u00b2", " = ", int((i**2 + j**2)**(1/2)), "\u00b2", sep='')
while(1):
run()
|
d765ef2276fd0aacd41d2d935929c593fc582173
|
nspavlo/AlgorithmsPython
|
/Algorithms/Goodrich/BinarySearch.py
| 757 | 3.90625 | 4 |
import unittest
# The binary search algorithm runs in O(logn) time for a sorted
# sequence with n elements.
def binary_search(data, target, low, high) -> int:
if low > high:
return None
else:
mid = (low + high) // 2
if target == data[mid]:
return mid
elif target < data[mid]:
return binary_search(data, target, low, mid - 1)
else:
return binary_search(data, target, mid + 1, high)
class TestBinarySearch(unittest.TestCase):
def test_one_item(self):
sut = binary_search([0], 0, 0, 1)
self.assertEqual(sut, 0)
def test_large_list(self):
sut = binary_search([1, 2, 3, 4, 5, 6, 7, 18, 19, 100], 18, 0, 9)
self.assertEqual(sut, 7)
|
d63c0d793b68e140e7381c19e59a5abe78fc0cec
|
pavanrao/python-projects
|
/wordplay/palindrome.py
| 640 | 3.8125 | 4 |
from pathlib import Path
from pprint import pprint
WORDS_FILE = '/usr/share/dict/words'
def get_words(file_name=WORDS_FILE):
try:
text = Path(WORDS_FILE).read_text()
except FileNotFoundError:
print(f'File {file_name} not found.')
return None
words = text.strip().split('\n')
words = [word.lower() for word in words]
return words
def find_palindrome(words):
palindrome = [
word for word in words if word == word[::-1] and len(word) > 1
]
return palindrome
if __name__ == "__main__":
words = get_words()
palindrome = find_palindrome(words)
pprint(palindrome)
|
744decff8f8848d3129e373dea40ec4a8a79ce6a
|
xennygrimmato/Data-Structures-and-Algorithms
|
/Longest Increasing Subsequence/lis.py
| 347 | 3.5 | 4 |
from bisect import bisect_left
def lis(A, return_only_length=False):
B = []
for a in A:
i = bisect_left(B, a)
if i == len(B):
B.append(a)
else:
B[i] = a
if return_only_length:
return len(B)
return B
# Usage
print(lis([3, 1, 5, 2, 4, 3]))
print(lis([1]))
print(lis([2, 1]))
|
47e7c0230ca5611fabc28160162cfb9de5f2d2d1
|
dperezc21/ejercicios
|
/ejercicio/conteo_palidromas.py
| 538 | 3.640625 | 4 |
palabra = "holacomo"
lista = []
cont = 0
def palindroma(string):
lista = list(string)
l = []
for i in lista:
l.insert(0,i)
cadena = ''.join(l)
if cadena == string:
return True
else:
return False
for i in range(len(palabra)+1):
for j in range(len(palabra)+1):
if palabra[i:j] != "":
if palindroma( palabra[i:j]):
cont +=1
lista.append(palabra[i:j])
|
e2350657520b17cc90a0fb9406a4cc6f99cee53a
|
CookieComputing/MusicMaze
|
/MusicMaze/model/data_structures/Queue.py
| 1,532 | 4.21875 | 4 |
from model.data_structures.Deque import Deque
class Queue:
"""This class represents a queue data structure, reinvented out of the
wheel purely for the sake of novelty."""
def __init__(self):
"""Constructs an empty queue."""
self._deque = Deque()
def peek(self):
"""Peek at the earliest entry in the queue without removing it.
Returns:
Any: the data of the front-most entry in the queue
Raises:
IndexError: If no data is in the queue."""
if not self._deque:
raise IndexError("Queue is empty")
return self._deque.peek_head()
def enqueue(self, data):
"""Puts the given data into the queue.
Args:
data(Any): the data to be inserted into the back of the queue"""
self._deque.push_tail(data)
def dequeue(self):
"""Removes the earliest entry from the queue and returns it.
Returns:
Any: the data of the earliest entry in the queue
Raises:
IndexError: If the queue is empty"""
if not self._deque:
raise IndexError("Queue is empty")
return self._deque.pop_head()
def __len__(self):
"""Returns the size of the queue.
Returns:
int: the size of the queue"""
return len(self._deque)
def __bool__(self):
"""Returns true if the queue has an entry
Returns:
bool: True if len(queue) > 0, false otherwise"""
return len(self) > 0
|
a1ae7f685f24b3d4ee366da29f46dd9894a82d8f
|
CookieComputing/MusicMaze
|
/tests/unit/model/graph/test_kruskal.py
| 7,128 | 3.625 | 4 |
from unittest import TestCase
from model.graph.Graph import Graph
from model.graph.kruskal import kruskal
class TestKruskal(TestCase):
"""Tests to see that kruskal will return the set of edges corresponding
to the minimum spanning tree from various graphs"""
@staticmethod
def contains_edge(v1, v2, edges):
for edge in edges:
if (v1 == edge.from_vertice().name()
and v2 == edge.to_vertice().name()) \
or (v2 == edge.from_vertice().name()
and v1 == edge.to_vertice().name()):
return True
return False
def test_three_by_three_graph(self):
g = Graph()
# The graph looks like this:
# o - o - o
# |
# o - o - o
# |
# o - o - o
node_00 = "(0, 0)"
node_01 = "(0, 1)"
node_02 = "(0, 2)"
node_10 = "(1, 0)"
node_11 = "(1, 1)"
node_12 = "(1, 2)"
node_20 = "(2, 0)"
node_21 = "(2, 1)"
node_22 = "(2, 2)"
g.add_vertice(node_00)
g.add_vertice(node_01)
g.add_vertice(node_02)
g.add_vertice(node_10)
g.add_vertice(node_11)
g.add_vertice(node_12)
g.add_vertice(node_20)
g.add_vertice(node_21)
g.add_vertice(node_22)
g.add_edge(node_00, node_01, 0)
g.add_edge(node_01, node_02, 1)
g.add_edge(node_00, node_10, 10)
g.add_edge(node_01, node_11, 2)
g.add_edge(node_02, node_12, 11)
g.add_edge(node_10, node_11, 3)
g.add_edge(node_11, node_12, 4)
g.add_edge(node_10, node_20, 5)
g.add_edge(node_11, node_21, 12)
g.add_edge(node_12, node_22, 13)
g.add_edge(node_20, node_21, 6)
g.add_edge(node_21, node_22, 7)
kruskal_edges = kruskal(g)
self.assertEqual(8, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_01, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_02, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_11, kruskal_edges))
self.assertTrue(self.contains_edge(node_10, node_11, kruskal_edges))
self.assertTrue(self.contains_edge(node_11, node_12, kruskal_edges))
self.assertTrue(self.contains_edge(node_10, node_20, kruskal_edges))
self.assertTrue(self.contains_edge(node_20, node_21, kruskal_edges))
self.assertTrue(self.contains_edge(node_21, node_22, kruskal_edges))
def test_two_by_three_graph(self):
g = Graph()
# The graph should look like this:
# o - o - o
# | |
# o - o o
node_00 = "(0, 0)"
node_01 = "(0, 1)"
node_02 = "(0, 2)"
node_10 = "(1, 0)"
node_11 = "(1, 1)"
node_12 = "(1, 2)"
g.add_vertice(node_00)
g.add_vertice(node_01)
g.add_vertice(node_02)
g.add_vertice(node_10)
g.add_vertice(node_11)
g.add_vertice(node_12)
g.add_edge(node_00, node_01, 0)
g.add_edge(node_01, node_02, 1)
g.add_edge(node_10, node_11, 2)
g.add_edge(node_11, node_12, 9)
g.add_edge(node_00, node_10, 3)
g.add_edge(node_01, node_11, 10)
g.add_edge(node_02, node_12, 4)
kruskal_edges = kruskal(g)
self.assertEqual(5, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_01, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_02, kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_10, kruskal_edges))
self.assertTrue(self.contains_edge(node_02, node_12, kruskal_edges))
self.assertTrue(self.contains_edge(node_10, node_11, kruskal_edges))
def test_three_by_two_graph(self):
g = Graph()
# The graph should look like this:
# o - o
# |
# o o
# | |
# o - o
node_00 = "(0, 0)"
node_01 = "(0, 1)"
node_10 = "(1, 0)"
node_11 = "(1, 1)"
node_20 = "(2, 0)"
node_21 = "(2, 1)"
g.add_vertice(node_00)
g.add_vertice(node_01)
g.add_vertice(node_10)
g.add_vertice(node_11)
g.add_vertice(node_20)
g.add_vertice(node_21)
g.add_edge(node_00, node_01, 0)
g.add_edge(node_00, node_10, 10)
g.add_edge(node_01, node_11, 1)
g.add_edge(node_10, node_11, 11)
g.add_edge(node_10, node_20, 2)
g.add_edge(node_11, node_21, 3)
g.add_edge(node_20, node_21, 4)
kruskal_edges = kruskal(g)
self.assertEqual(5, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_01, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_11, kruskal_edges))
self.assertTrue(self.contains_edge(node_11, node_21, kruskal_edges))
self.assertTrue(self.contains_edge(node_21, node_20, kruskal_edges))
self.assertTrue(self.contains_edge(node_20, node_10, kruskal_edges))
def test_two_by_two_graph(self):
g = Graph()
# The graph looks like this:
# o - o
# |
# o - o
node_00 = "(0, 0)"
node_01 = "(0, 1)"
node_10 = "(1, 0)"
node_11 = "(1, 1)"
g.add_vertice(node_00)
g.add_vertice(node_01)
g.add_vertice(node_10)
g.add_vertice(node_11)
g.add_edge(node_00, node_01, 1)
g.add_edge(node_10, node_11, 2)
g.add_edge(node_01, node_11, 3)
g.add_edge(node_00, node_11, 4)
kruskal_edges = kruskal(g)
self.assertEqual(3, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_01, kruskal_edges))
self.assertTrue(self.contains_edge(node_10, node_11, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_11, kruskal_edges))
def test_one_direction_horizontal_connection(self):
g = Graph()
# The graph looks like this:
# o - o - o
node_00 = "(0, 0)"
node_01 = "(0, 1)"
node_02 = "(0, 2)"
g.add_vertice(node_00)
g.add_vertice(node_01)
g.add_vertice(node_02)
g.add_edge(node_00, node_01, 1)
g.add_edge(node_01, node_02, 2)
kruskal_edges = kruskal(g)
self.assertEqual(2, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_01, kruskal_edges))
self.assertTrue(self.contains_edge(node_01, node_02, kruskal_edges))
def test_one_direction_vertical_connection(self):
g = Graph()
node_00 = "(0, 0)"
node_10 = "(1, 0)"
node_20 = "(2, 0)"
g.add_vertice(node_00)
g.add_vertice(node_10)
g.add_vertice(node_20)
g.add_edge(node_00, node_10, 1)
g.add_edge(node_10, node_20, 2)
kruskal_edges = kruskal(g)
self.assertEqual(2, len(kruskal_edges))
self.assertTrue(self.contains_edge(node_00, node_10, kruskal_edges))
self.assertTrue(self.contains_edge(node_10, node_20, kruskal_edges))
|
ee1afcafa7267dbe5629f8c5edc5ce99d7431966
|
KseniiaP-20/Python_Study
|
/task7_edit.py
| 1,224 | 4.03125 | 4 |
# Самостоятельное задание
# Дана строка из двух слов. Поменяйте слова местами.
string = 'test new'
test_list = string.split( )
string_new = str(test_list[1] + ' ' + test_list[0])
print(string_new +'\n')
# Домашнее задание
import calendar
# С помощью модуля calendar узнайте, является ли 2030 год високосным
leap = calendar.isleap(2030)
if leap == 'True':
print('2030 год будет викосным')
else:
print('2030 год НЕ будет викосным\n')
# С помощью модуля calendar узнайте, каким днем недели
# был день 25 июня 2000 года.
day = calendar.weekday(2000, 6, 25)
if day == 0:
print('Понедельник')
elif day == 1:
print('Вторник')
elif day == 2:
print('Среда')
elif day == 3:
print('Четверг')
elif day == 4:
print('Пятница')
elif day == 5:
print('Суббота')
else:
print('Воскресенье')
# Выведите в консоль календарь на 2023 год
cal = calendar.TextCalendar()
print(cal.formatyear(2023))
|
0d2c3e8c94d0669633ab4e938014fc5018a221d1
|
weekenlee/leetcode-c
|
/leetcodePython/leetcodePython/nqueues.py
| 678 | 3.5625 | 4 |
def solveNQueens(n):
"""
:type n :int
:rtype: List[List[str]]
"""
def isqueens(depth, j):
for i in range(depth):
if board[i] == j or abs(depth - i) == abs(board[i] - j):
return False
return True
def dfs(depth, row):
if depth == n:
ans.append(row)
return
for i in range(n):
if isqueens(depth, i):
board[depth] = i
dfs(depth + 1, row + ['.' * i + 'Q' + '.' * (n - i - 1)])
board = [-1 for i in range(n)]
ans = []
dfs(0, [])
return ans
for i in solveNQueens(8):
for ii in i:
print ii
print ""
|
19ec1a1e76b9ef0cc6ed8340623b52505bf77a77
|
SliverOverlord/HPPython_research
|
/benchmarks/mat_multiplication_benchmark.py
| 5,257 | 3.890625 | 4 |
"""
Author: Heecheon Park
Note: Run python3 100x100_mat_generator.py first before running this program.
Description: Read numbers from 100x100_matrix.txt
Store each line into lists and numpy arrays.
Then, benchmarks matrix multiplication.
For example, list A and list B are 2-dimensional lists and
performs list A * list B.
Likewise, numpy A and numpy B are 2-dimensional numpy arrays and
performs numpy A * numpy B.
I created a matrix multiplication function that takes 2 array-like containers and output array.
The function calculate and append the result to output array.
"""
import numpy as np
import time
import sys
from array import array
#from timeit import timeit
from timeit import Timer
def main():
list_mat = []
list_mat2 = []
np_mat = np.zeros((100,100), dtype=np.int64)
np_mat2 = np.zeros((100,100), dtype=np.int64)
# Initializing 100x100 list_matrix of zeros
list_output = [[0 for col in range(100)] for rows in range(100)]
np_output = np.zeros((100,100), dtype=np.int64)
"""
Tried to implement Python's array module but I cannot find if multidimensional array is possible.
I have only succeeded in making single dimension array with a specific datatype.
"""
#array_mat = array('q', range(100))
#array_mat2 = array('q', range(100))
#array_output = array('q', range(100))
#array_output = array_output.fromlist(array.fromlist(list_output))
#for row in list_output: array_output.append(array.fromlist(row))
#print("array output:", array_output)
with open("100x100_matrix.txt", "r") as f:
for line in f:
# Split each line as a list of string
int_string_list = line.split()
# Convert the string element to int
int_list = [int(i) for i in int_string_list]
# Append the int_list to list_mat and list_mat2
list_mat.append(int_list)
list_mat2.append(int_list)
#array_mat.append(array.fromlist(int_list))
#array_mat2.append(array.fromlist(int_list))
f.close()
# New Discovery!!
# dtype could be "dtype=int". but int is 32-bit based. So if an element gets too large,
# it will become a negative integer.
np_mat = np.loadtxt("100x100_matrix.txt", usecols=range(0, 100), dtype=np.int64)
np_mat2 = np.loadtxt("100x100_matrix.txt", usecols=range(0, 100), dtype=np.int64)
print("list_mat: ", list_mat)
# Print large numpy arrays without truncation.
np.set_printoptions(threshold=sys.maxsize)
print("np_mat: \n", np_mat)
"""
Following print statements display the results of matrix multiplication by list and numpy array.
First and second statements display the results from my custom matrix multiplication function.
Last statements display the result from built-in numpy matrix multiplication function.
Results are quite large. So only use them when you want to compare results.
"""
#print("Custom Mat_Multiplication (list):\n", mat_mult(list_mat, list_mat2, list_output))
#print("Custom Mat_Multiplication (ndarray):\n", mat_mult(np_mat, np_mat2, np_output))
#print("Numpy Built-in Mat_Multiplication (ndarray):\n", np.matmul(np_mat, np_mat2))
"""
Benchmarking using timeit function but the function parameter cannot take arguments
"""
#print("Custom Mat_Mult (list):", timeit("mat_mult(list_mat, list_mat2, list_ouput)", setup="from __main__ import mat_mult"))
#print("Custom Mat_Mult (ndarray):", timeit("mat_mult(np_mat, np_mat2, np_ouput)", setup="from __main__ import mat_mult"))
#print("Numpy Built-in Mat_Mult (ndarray):", timeit("np.matmul(np_mat, np_mat2)", setup="import numpy as np"))
#%timeit mat_mult(list_mat, list_mat2, list_output)
#%timeit mat_mult(np_mat, np_mat2, np_output)
#%timeit np.matmul(np_mat, np_mat2)
"""
Timer function cannot take function parameter with arguments which is uncallable.
However, using lambda can make the function parameter with arguments callable.
"""
list_timer = Timer(lambda: mat_mult(list_mat, list_mat2, list_output))
ndarray_timer = Timer(lambda: mat_mult(np_mat, np_mat2, np_output))
built_in_mult_timer = Timer(lambda: np.matmul(np_mat, np_mat2, np_output))
print("*"*80)
iteration_count = print("How many times would you like to perform the matrix multiplication?")
iteration_count = int(input("I recommend a small number like less than 50: "))
print("*"*80)
print("Custom Mat_Multiplication {} times (list):".format(iteration_count), list_timer.timeit(number=iteration_count))
print("Custom Mat_Multiplication {} times (ndarray):".format(iteration_count), ndarray_timer.timeit(number=iteration_count))
print("Numpy Built-in Mat_Multiplication {} times (array):".format(iteration_count), built_in_mult_timer.timeit(number=iteration_count))
def mat_mult(mat1, mat2, output_mat):
row = len(mat1)
col = len(mat1[0])
for r in range(0, row):
for c in range(0, col):
for r_iter in range(0, row):
output_mat[r][c] += mat1[r][r_iter] * mat2[r_iter][c]
return output_mat
if __name__ == "__main__":
main()
|
6559e13a3d8c617a02dc1ac6862d0961f66eef5e
|
SliverOverlord/HPPython_research
|
/benchmarks/mpi4py_benchmark.py
| 3,640 | 3.796875 | 4 |
#Author: Heecheon Park
#Date: 8/11/2019
"""
#Description: This program benchmarks numpy matrix
multiplication vs standard python on mpi4py
Read numbers from 100x100_matrix.txt
Store each line into lists and numpy arrays.
Then, benchmarks matrix multiplication.
For example, list A and list B are 2-dimensional lists and
performs list A * list B.
Likewise, numpy A and numpy B are 2-dimensional numpy arrays and
performs numpy A * numpy B.
I created a matrix multiplication function that takes 2 array-like containers and output array.
The function calculate and append the result to output array.
Note: Run python3 100x100_mat_generator.py first before running this program.
"""
from mpi4py import MPI
import timeit
import numpy
import sys
from array import array
from timeit import Timer
#set comm,size and rank
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
def main():
if rank == 0:
list_mat = []
list_mat2 = []
np_mat = numpy.zeros((100,100), dtype=numpy.int64)
np_mat2 = numpy.zeros((100,100), dtype=numpy.int64)
# Initializing 100x100 list_matrix of zeros
list_output = [[0 for col in range(100)] for rows in range(100)]
np_output = numpy.zeros((100,100), dtype=numpy.int64)
with open("100x100_matrix.txt", "r") as f:
for line in f:
# Split each line as a list of string
int_string_list = line.split()
# Convert the string element to int
int_list = [int(i) for i in int_string_list]
# Append the int_list to list_mat and list_mat2
list_mat.append(int_list)
list_mat2.append(int_list)
#array_mat.append(array.fromlist(int_list))
#array_mat2.append(array.fromlist(int_list))
f.close()
np_mat = numpy.loadtxt("100x100_matrix.txt", usecols=range(0, 100), dtype=numpy.int64)
np_mat2 = numpy.loadtxt("100x100_matrix.txt", usecols=range(0, 100), dtype=numpy.int64)
#print("list_mat: ", list_mat)
#the above line has been commented out for readability-----------------------
# Print large numpy arrays without truncation.
numpy.set_printoptions(threshold=sys.maxsize)
#print("np_mat: \n", np_mat)
#the above line has been commented out for readability-----------------------
list_timer = Timer(lambda: mat_mult(list_mat, list_mat2, list_output))
ndarray_timer = Timer(lambda: mat_mult(np_mat, np_mat2, np_output))
built_in_mult_timer = Timer(lambda: numpy.matmul(np_mat, np_mat2, np_output))
print("*"*80)
print("How many times would you like to perform the matrix multiplication?")
print("I recommend a small number less than 50: ")
iteration_count = int(input())
print("*"*80)
print('Custom Mat_Multiplication {} times (list):'.format(iteration_count), list_timer.timeit(number=iteration_count))
print('Custom Mat_Multiplication {} times (ndarray):'.format(iteration_count), ndarray_timer.timeit(number=iteration_count))
print('Numpy Built-in Mat_Multiplication {} times (array):'.format(iteration_count), built_in_mult_timer.timeit(number=iteration_count))
def mat_mult(mat1, mat2, output_mat):
row = len(mat1)
col = len(mat1[0])
for r in range(0, row):
for c in range(0, col):
for r_iter in range(0, row):
output_mat[r][c] += mat1[r][r_iter] * mat2[r_iter][c]
return output_mat
if __name__ == "__main__":
main()
|
da468dde42ec8cf37d5a6c500bcd7b844358708e
|
DaDa0013/data_structure_python
|
/My_first_balanced_tree_AVL/Main.py
| 11,636 | 4 | 4 |
class Node:
def __init__(self, key):
self.key = key
self.parent = self.left = self.right = None
self.height = 0 # 높이 정보도 유지함에 유의!!
def __str__(self):
return str(self.key)
class BST:
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def preorder(self, v):
if v:
print(v.key, end=' ')
self.preorder(v.left)
self.preorder(v.right)
def inorder(self, v):
if v:
self.inorder(v.left)
print(v.key, end=" ")
self.inorder(v.right)
def postorder(self, v):
if v:
self.postorder(v.left)
self.postorder(v.right)
print(v.key, end=" ")
def find_loc(self, key):
if self.size == 0:
return None
p = None
v = self.root
while v:
if v.key == key:
return v
else:
if v.key < key:
p = v
v = v.right
else:
p = v
v = v.left
return p
def search(self, key):
p = self.find_loc(key)
if p and p.key == key:
return p
else:
return None
def insert(self, key):
v = Node(key)
if self.size == 0:
self.root = v
else:
p = self.find_loc(key)
if p and p.key != key: # p is parent of v
if p.key < key:
p.right = v
else:
p.left = v
v.parent = p
self.fixHeight(v)
self.size += 1
return v
def fixHeight(self, x): # x의 왼쪽 오른쪽을 비교해 x부터 root 까지 heigth 부여
while x:
if x.left == None and x.right == None: # x의 자식이 없는 경우 ( x는 leaf 노드)
x.height = 0
x = x.parent
elif x.left != None and x.right == None: # x의 왼쪽만 있음
x.height = x.left.height + 1
x = x.parent
elif x.left == None and x.right != None: # x의 오른쪽만 있음
x.height = x.right.height + 1
x = x.parent
elif x.left != None and x.right != None: # 왼 오 다 있을 떄 큰 쪽 따라감
if x.left.height > x.right.height:
x.height = x.left.height + 1
else:
x.height = x.right.height + 1
x = x.parent
return
def deleteByMerging(self, x):
# assume that x is not None
a, b, pt = x.left, x.right, x.parent
m = None
if a == None:
c = b
else: # a != None
c = m = a
# find the largest leaf m in the subtree of a
while m.right:
m = m.right
m.right = b
if b: b.parent = m
if self.root == x: # c becomes a new root
if c: c.parent = None
self.root = c
else: # c becomes a child of pt of x
if pt.left == x:
pt.left = c
else:
pt.right = c
if c: c.parent = pt
self.size -= 1
if m:
self.fixHeight(m)
else:
self.fixHeight(pt)
return
# 노드들의 height 정보 update 필요
def deleteByCopying(self, x):
if x == None:
return None
pt, L, R = x.parent, x.left, x.right
if L: # L이 있음
y = L
while y.right:
y = y.right
x.key = y.key
if y.left:
y.left.parent = y.parent
if y.parent.left is y:
y.parent.left = y.left
else:
y.parent.right = y.left
self.fixHeight(y.parent)
s = y.parent
del y
elif not L and R: # R만 있음
y = R
while y.left:
y = y.left
x.key = y.key
if y.right:
y.right.parent = y.parent
if y.parent.left is y:
y.parent.left = y.right
else:
y.parent.right = y.right
self.fixHeight(y.parent)
s = y.parent
del y
else: # L도 R도 없음
if pt == None: # x가 루트노드인 경우
self.root = None
else:
if pt.left is x:
pt.left = None
else:
pt.right = None
self.fixHeight(pt)
s = x.parent
del x
self.size -= 1
return s
# 노드들의 height 정보 update 필요
def height(self, x): # 노드 x의 height 값을 리턴
if x == None:
return -1
else:
return x.height
def succ(self, x): # key값의 오름차순 순서에서 x.key 값의 다음 노드(successor) 리턴
# x의 successor가 없다면 (즉, x.key가 최대값이면) None 리턴
if x == None:
return None
r = x.right
pt = x.parent
if r:
while r.left:
r = r.left
return r
else:
while pt != None and x == pt.right:
x = pt
pt = pt.parent
return pt
def pred(self, x): # key값의 오름차순 순서에서 x.key 값의 이전 노드(predecssor) 리턴
# x의 predecessor가 없다면 (즉, x.key가 최소값이면) None 리턴
if x == None:
return None
l = x.left
pt = x.parent
if l:
while l.right:
l = l.right
return l
else:
while pt != None and x == pt.left:
x = pt
pt = pt.parent
return pt
def rotateLeft(self, x): # 균형이진탐색트리의 1차시 동영상 시청 필요 (height 정보 수정 필요)
if x == None: return
v = x.right
if v == None: return
b = v.left
v.parent = x.parent
if x.parent:
if x.parent.right == x:
x.parent.right = v
else:
x.parent.left = v
v.left = x
x.parent = v
x.right = b
if b:
b.parent = x
if x == self.root:
self.root = v
self.fixHeight(x)
return v
def rotateRight(self, x): # 균형이진탐색트리의 1차시 동영상 시청 필요 (height 정보 수정 필요)
if x == None: return
v = x.left
if v == None: return
b = v.right
v.parent = x.parent
if x.parent != None:
if x.parent.left == x:
x.parent.left = v
else:
x.parent.right = v
v.right = x
x.parent = v
x.left = b
if b:
b.parent = x
if x == self.root:
self.root = v
self.fixHeight(x)
return v
class AVL(BST):
def __init__(self):
self.root = None
self.size = 0
def BalanceFactor(self, x):
if x.left and x.right: #왼 오 둘 다 있을 때
bal_factor = x.right.height - x.left.height
else:
if x.left: #왼쪽만 있을 때
bal_factor = - (x.left.height + 1)
elif x.right: #오른쪽만 있을 떄
bal_factor = x.right.height + 1
else: #둘 다 없을 때
bal_factor = 0
return bal_factor
def find_fix(self, v): #균형 깨짐 여부 & xyz
while v:
self.BalanceFactor(v)
if abs(self.BalanceFactor(v)) <= 1: # 균형 안꺠짐
v = v.parent
else: #균형 꺠짐
zyx=[]
zyx.append(v) # z 넣기
for i in range(0, 2): # y, x 넣기
if v.left and v.right: #왼쪽 오른쪽 다있음
if v.left.height >= v.right.height: # 왼쪽이 더 깊을거나 같을때
v = v.left
zyx.append(v)
else: #오른쪽이 더 깊을 때
v = v.right
zyx.append(v)
elif v.left and v.right == None: #왼쪽만 있다면
v = v.left
zyx.append(v)
else: #오른쪽만 있으면
v = v.right
zyx.append(v)
return zyx
return "NO"
def rebalance(self, x, y, z):
v = None
if z.left == y:
if y.left == x: #left - left
v = super(AVL, self).rotateRight(z)
else: # left - right
super(AVL, self).rotateLeft(y)
v = super(AVL, self).rotateRight(z)
else:
if y.left == x: #right - left
super(AVL, self).rotateRight(y)
v = super(AVL, self).rotateLeft(z)
else: #right - right
v = super(AVL, self).rotateLeft(z)
return v
def insert(self, key):
v = super(AVL, self).insert(key)
if self.find_fix(v) != "NO": #균형 깨짐
zyx = self.find_fix(v)
self.rebalance(zyx[2], zyx[1], zyx[0])
return v
def delete(self, u): # delete the node u
v = self.deleteByCopying(u) # 또는 self.deleteByMerging을 호출가능하다. 그러나 이 과제에서는 deleteByCopying으로 호출한다
while v:
if self.find_fix(v) != "NO": #균형 깨짐
zyx = self.find_fix(v)
v = self.rebalance(zyx[2], zyx[1], zyx[0])
v = v.parent
return v
T = AVL()
while True:
cmd = input().split()
if cmd[0] == 'insert':
v = T.insert(int(cmd[1]))
print("+ {0} is inserted".format(v.key))
elif cmd[0] == 'delete':
v = T.search(int(cmd[1]))
T.delete(v)
print("- {0} is deleted".format(int(cmd[1])))
elif cmd[0] == 'search':
v = T.search(int(cmd[1]))
if v == None:
print("* {0} is not found!".format(cmd[1]))
else:
print("* {0} is found!".format(cmd[1]))
elif cmd[0] == 'height':
h = T.height(T.search(int(cmd[1])))
if h == -1:
print("= {0} is not found!".format(cmd[1]))
else:
print("= {0} has height of {1}".format(cmd[1], h))
elif cmd[0] == 'succ':
v = T.succ(T.search(int(cmd[1])))
if v == None:
print("> {0} is not found or has no successor".format(cmd[1]))
else:
print("> {0}'s successor is {1}".format(cmd[1], v.key))
elif cmd[0] == 'pred':
v = T.pred(T.search(int(cmd[1])))
if v == None:
print("< {0} is not found or has no predecssor".format(cmd[1]))
else:
print("< {0}'s predecssor is {1}".format(cmd[1], v.key))
elif cmd[0] == 'preorder':
T.preorder(T.root)
print()
elif cmd[0] == 'postorder':
T.postorder(T.root)
print()
elif cmd[0] == 'inorder':
T.inorder(T.root)
print()
elif cmd[0] == 'exit':
break
else:
print("* not allowed command. enter a proper command!")
|
95e8e064dfa86d60977f725f8ec027dce139e0de
|
DaDa0013/data_structure_python
|
/Linked_List_Operation/Main.py
| 4,782 | 3.8125 | 4 |
class Node:
def __init__(self, key=None):
self.key = key
self.next = None
def __str__(self):
return str(self.key)
class SinglyLinkedList:
def __init__(self):
self.head = None
self.size = 0
def __len__(self):
return self.size
def printList(self): # 변경없이 사용할 것!
v = self.head
while(v):
print(v.key, "->", end=" ")
v = v.next
print("None")
def pushFront(self, key):
new_node=Node(key)
if self.head==None:
self.head=new_node
else:
new_node.next=self.head
self.head=new_node
self.size+=1
pass
def pushBack(self, key):
new_node=Node(key)
if self.head==None:
self.head=new_node
else:
tail=self.head
while tail.next!=None:
tail=tail.next
tail.next=new_node
self.size+=1
def popFront(self):
if self.head==None:
return None
else:
pop_node=self.head
pop_data=pop_node.key
self.head=pop_node.next
self.size-=1
del pop_node
return pop_data
# head 노드의 값 리턴. empty list이면 None 리턴
def popBack(self):
if self.size==0:
return None
else:
prev=None
tail=self.head
while tail.next!=None:
prev=tail
tail=tail.next
if prev==None:
self.head=None
else:
prev.next=tail.next
pop_data=tail.key
del tail
self.size-=1
return pop_data
# tail 노드의 값 리턴. empty list이면 None 리턴
def search(self, key):
current=self.head
while current!=None:
if current.key==key:
return current
current=current.next
return None
# key 값을 저장된 노드 리턴. 없으면 None 리턴
def remove(self, x):
current=self.head
prev=None
if x==None:
return False
while current!=None:
if current==x:
break
prev=current
current=current.next
if self.size==1:
self.head=None
elif prev==None:
self.head=current.next
else:
prev.next=current.next
del current
self.size-=1
return True
# 노드 x를 제거한 후 True리턴. 제거 실패면 False 리턴
# x는 key 값이 아니라 노드임에 유의!
def reverse(self,key):
current=self.head
prev=None
while current!=None:# current 찾기
if current.key==key:
break
prev=current
current=current.next
if current==None:
return
Stack=[]
while current!=None:
Stack.append(current)
current=current.next
if prev!=None:
prev.next=Stack[-1]
else:
self.head=Stack[-1]
for i in range(1,len(Stack)):
Stack[-1*i].next=Stack[(-1*i)-1]
Stack[0].next=None
def findMax(self):
if self.size==0:
return None
else:
current=self.head
max_key=current.key
while current.next!=None:
current=current.next
if max_key<current.key:
max_key=current.key
return max_key
# self가 empty이면 None, 아니면 max key 리턴
def deleteMax(self):
if self.size==0:
return None
else:
max_key=self.findMax()
self.remove(self.search(max_key))
return max_key
# self가 empty이면 None, 아니면 max key 지운 후, max key 리턴
def insert(self, k, val):
new_node=Node(val)
if k>self.size:
self.pushBack(val)
else:
prev=None
node=self.head
self.size+=1
for i in range(k):
prev=node
node=node.next
new_node.next=node
prev.next=new_node
def size(self):
return self.size
# 아래 코드는 수정하지 마세요!
L = SinglyLinkedList()
while True:
cmd = input().split()
if cmd[0] == "pushFront":
L.pushFront(int(cmd[1]))
print(int(cmd[1]), "is pushed at front.")
elif cmd[0] == "pushBack":
L.pushBack(int(cmd[1]))
print(int(cmd[1]), "is pushed at back.")
elif cmd[0] == "popFront":
x = L.popFront()
if x == None:
print("List is empty.")
else:
print(x, "is popped from front.")
elif cmd[0] == "popBack":
x = L.popBack()
if x == None:
print("List is empty.")
else:
print(x, "is popped from back.")
elif cmd[0] == "search":
x = L.search(int(cmd[1]))
if x == None:
print(int(cmd[1]), "is not found!")
else:
print(int(cmd[1]), "is found!")
elif cmd[0] == "remove":
x = L.search(int(cmd[1]))
if L.remove(x):
print(x.key, "is removed.")
else:
print("Key is not removed for some reason.")
elif cmd[0] == "reverse":
L.reverse(int(cmd[1]))
elif cmd[0] == "findMax":
m = L.findMax()
if m == None:
print("Empty list!")
else:
print("Max key is", m)
elif cmd[0] == "deleteMax":
m = L.deleteMax()
if m == None:
print("Empty list!")
else:
print("Max key", m, "is deleted.")
elif cmd[0] == "insert":
L.insert(int(cmd[1]), int(cmd[2]))
print(cmd[2], "is inserted at", cmd[1]+"-th position.")
elif cmd[0] == "printList":
L.printList()
elif cmd[0] == "size":
print("list has", len(L), "nodes.")
elif cmd[0] == "exit":
print("DONE!")
break
else:
print("Not allowed operation! Enter a legal one!")
|
ee33c9f41a4d4a0f5a3211720ea315e529898c0f
|
krishnakaspe/bored_and_tried
|
/time_conversion.py
| 457 | 3.6875 | 4 |
def timeConversion(s):
if "AM" in s:
if s.split(':')[0] == '12':
return s.replace('12','00').replace('AM','')
return s.replace('AM','')
else:
hours = s.split(':')[0]
if hours == '12':
return s.replace('PM','')
full_time = str((int(hours) + 12)) + s.replace(str(hours), '',1)
full_time = full_time.replace('PM','')
return full_time
print(timeConversion('12:01:00AM'))
|
cce9f168e66431c2007ba19eebb889f3718c3ddf
|
worker-bee-micah/practice-only
|
/DnD_dice.py
| 894 | 3.546875 | 4 |
#code source Simon Monk 03_02_double_dice
import random
for x in range(1, 2):
die_4 = random.randint(1,4)
die_6 = random.randint(1, 6)
die_8 = random.randint(1,8)
die_10 = random.randint(1,10)
die_12 = random.randint(1,12)
die_20 = random.randint(1,20)
total = die_4 + die_6 + die_8 + die_10 + die_12 + die_20
print("Total=", total)
if total == 6:
print('Lucky Sixes!')
if total == 11:
print('Eleven Thrown!')
if die_12 == die_20:
print('Double Thrown!')
print("D20 =", die_20)
if die_20 == 20:
print('Max D20!!')
print("D12 =", die_12)
if die_12 == 12:
print('Max D12!!')
print("D08 =", die_8)
if die_8 == 8:
print('Max D8!!')
print("D06 =", die_6)
if die_6 == 6:
print('Max D6!!')
print("D04 =", die_4)
if die_4 == 4:
print('Max D4!!')
|
abe30ce13e94e8525cb8800111924ee3177b638c
|
codewithgauri/HacktoberFest
|
/python/Algorithms/Implementation/Utopian Tree.py
| 252 | 3.609375 | 4 |
def utopianTree(n):
k=int(n/2)
m= 1 if n % 2 == 0 else 2
return 2 ** (k + m) - m
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = utopianTree(n)
print(result)
|
9bc3ae714f881fd44890ed63429dc9bc4de89b5c
|
codewithgauri/HacktoberFest
|
/python/Learning Files/10-List Data Type , Indexing ,Slicing,Append-Extend-Insert-Closer look at python data types.py
| 1,129 | 4.28125 | 4 |
l=[10,20,22,30,40,50,55]
# print(type(l))
# 1 Lists are mutable = add update and delete
# 2 Ordered = indexing and slicing
# 3 Hetrogenous
# indexing and slicing:
# print(l[-1])
# print(l[1:3])
#end is not inclusive
# reverse a Lists
# print(l[::-1])
# if you want to iterate over alternate characters
# for value in l[::2]:
# print(value)
# append
# if u want to add single element in a list
# it wont return any thing
#memory location will be the same
# l.append(60)
# print(l)
# extend
# if u want to add multiple elements
# it only take one agrument
# it will iterate over give argument
#l.extend("Python")
# l.extend([500,600,700,800])
# print(l)
# in case of append it will add the whole list as one element
# insert
# Both append and extend will add element at last but if you want to add at particular
# position we use insert method
# l.insert(1,1000)
# print(l)
# l = [ 10,20,30]
# l2=l
# l.append(40)
# print(id(l),id(l2))
# print(l,l2)
# if we modifiy the frist list it will also modifiy the second list
# so we use some time copy
l = [ 10,20,30]
l2=l.copy()
l.append(40)
print(id(l),id(l2))
print(l,l2)
|
06e62fb57a55a421d1a01172ff5bd0bb3ba0e37e
|
codewithgauri/HacktoberFest
|
/python/pdf_scraper.py
| 484 | 3.5 | 4 |
#Downloading pdfs from a url and scraping them into a csv file
#third part libraries needed: tabula-py and requests
#pip install tabula-py
#pip install requests
import requests
import tabula
import os
url= 'url.pdf'
pdf = requests.get(url)
pdf_name = input("Type the name for the pdf file: ")
csv_name = input("Type the name for the csv file: ")
open(pdf_name+'.pdf', 'wb').write(pdf.content)
tabula.convert_into(pdf_name+".pdf",csv_name+".csv",output_format="csv",pages='all')
|
f6588c81322c61935e9df0883ae83af41cee8229
|
codewithgauri/HacktoberFest
|
/python/Learning Files/28-Parsing JSON files using Python.py
| 1,456 | 3.84375 | 4 |
# json objects dict{"key":"value"}
# numbers 10 10.25 int float
# array[10,"string"] list
# tuple
# " " ' ' " " """ """
#Null None
# true True
# false False
# json.load(f) load json data from a file ( or file like structure)
# json.loads(s) loads json data from a string
# json.dump(j,f) write a json object to file (or file like object)
# json.dumps(j) outputs the json object as a string
import json
handle=open("json_input.json","r")
content = handle.read()
# print(content)
# loads function convertes json format file into python datatypes
#handle.close()
#print(handle)
# here content is a string type so we use loads
# we can also use json.load(handle)
d=json.loads(content)
# print(d)
#print(d["database"])
#print(d["database"]["host"])
# d["database"]["host"]="public host"
#print(d)
#print(d['files']['log'])
# d['files']['log']=("/log/app.log","/log/mysql/app.log")
#print(d)
# dumps converts python format to json format
# j=json.dumps(d)
# print(j)
#conversion of a ppython file in to a json file is done by dumps
# handle=open("json_output.json","w")
# handle.write(j)
# handle.close()
# the above will give all in a line with out prettyfy
# j=json.dumps(d,indent=4)
# handle=open("json_output2.json","w")
# handle.write(j)
# handle.close()
# this will the prettyfied versions
# j=json.dumps(d,indent=4,sort_keys=True)
# Sorts the keys in alphabatical order
|
9295676b5187719dd03a96c405f910a3e316a359
|
codewithgauri/HacktoberFest
|
/python/fizzbuzz.py
| 405 | 3.765625 | 4 |
def run_fizzbuzz(ceiling=25):
"""
Prints out a game of fizzbuzz up to the value of `ceiling`.
:param ceiling: maximum value to count up to.
:return: None
"""
for i in range(1, ceiling + 1):
message = ''.join(('fizz' if not i % 3 else '', 'buzz' if not i % 5 else ''))
print(message if message else str(i))
return
if __name__ == '__main__':
run_fizzbuzz()
|
9ac834cdaaac4f7666d02bb6838bb88ac965072a
|
codewithgauri/HacktoberFest
|
/python/countingnames.py
| 340 | 3.703125 | 4 |
z = input()
x = open(z)
lst = list()
count = dict()
for lines in x:
if lines.startswith('From:'):
z= lines.split()
y= z[1]
lst.append(y)
# dict are made only by going through lists, so it is necessary to look through lists using for loop.
for words in lst:
count[words]= count.get(words, 0) +1
print(count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.