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 |
|---|---|---|---|---|---|---|
b250ff1223b67e89d7ec160e270e069441f087b6 | jokerKwu/BOJ_Algorithm | /introduction/BOJ_6376.py | 471 | 3.8125 | 4 | def fact(num):
if num==1or num==0:
return 1
else:
return fact(num-1)*num
print('n e')
print('- -----------')
for i in range(0,3):
res=0
if i==2:
for j in range(0, i + 1):
res += float(1 / fact(j))
print(i,res)
else:
for j in range(0,i+1):
res+=int(1/fact(j))
print(i,res)
for i in range(3,10):
res=0
for j in range(0,i+1):
res+=1/fact(j)
print (i,'%.9f'%res) |
944634470e026720d6b3d237885de4d147008a7d | MiguelChichorro/PythonExercises | /World 3/Dictionary/ex093 - Soccer Player Record.py | 1,387 | 3.625 | 4 | from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
matches = list()
player = dict()
sumtotal = 0
player['name'] = str(input("Enter your name: "))
player['match'] = int(input("How many matches did you play? "))
for c in range(0, player['match']):
n = int(input(f"how many goals did you do in the {c + 1}° match? "))
sumtotal += n
matches.append(n)
print(f"{colors['blue']}Reading data...{colors['clean']}")
sleep(1)
print("=" * 30)
print(f"{colors['yellow']}Hello {player['name']}{colors['clean']}")
print(f"{colors['yellow']}You played {player['match']} {'match' if player['match'] == 1 else 'matches'} in this championship{colors['clean']}")
for c, v in enumerate(matches):
print(f"{colors['yellow']}In the {c + 1}° match you did {v} goals{colors['clean']}")
print(f"{colors['yellow']}You did {sumtotal} {'goal' if sumtotal == 1 else 'goals'} this championship{colors['clean']}")
print("=" * 30)
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
8761536451b37503346a6b2554589cd7a6732e78 | MiguelChichorro/PythonExercises | /World 1/If...Else/ex031 - Cost of the trip.py | 613 | 3.75 | 4 | from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
trip = int(input("Enter your travel distance in km: "))
print("{}Loading...{}".format(colors["green"], colors["clean"]))
sleep(2)
if trip > 200:
price = trip * 0.45
print("{}The travel cost is US${}{}".format(colors["cian"], price, colors["clean"]))
else:
price = trip * 0.50
print("{}The travel cost is US${}{}".format(colors["cian"], price, colors["clean"]))
|
a15ab7b014e73d7280d7cd6089aaba4e07701b3c | MiguelChichorro/PythonExercises | /World 2/If..elif/ex039 - Military Draft.py | 2,318 | 3.984375 | 4 | from datetime import date
from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
gender = int(input("Before continuing the enlistment Enter your gender""\n [ 1 ] Man" "\n [ 2 ] Woman\n: "))
will = 0
if gender == 2:
will = int(input("You aren´t required to do the enlistment,"
"but would you like to do the enlist?""\n [1] Yes""\n [2] No \n: "))
if gender == 1 or will == 1:
name = str(input("Enter your name: "))
day = int(input("Enter the your birth day: "))
month = int(input("Enter the your birth month: "))
year = int(input("Enter the your birth year: "))
birth = date(year, month, day)
today = date.today()
age = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
print("{}reading data...{}".format(colors["green"], colors["clean"]))
sleep(0.5)
if age == 18:
print("{}Hello {}"
"\nYou have {} years old"
"\nYou need to enlist this year{}"
.format(colors["yellow"], name, age, colors["clean"]))
elif age < 18:
y = 18 - age
year = date.today().year + y
print("{}Hello {}"
"\nYou have {} years old"
"\nYou need to enlist in {} {} in {}{}"
.format(colors["green"], name, age, y, "years" if y > 1 else "year", year, colors["clean"]))
else:
y = age - 18
year = date.today().year - y
print("{}Hello {}"
"\nYou have {} years old"
"\nYour enlistment time was {} {} ago in {}{}"
.format(colors["red"], name, age, y, "years" if y > 1 else "year", year, colors["clean"]))
if (today.month == birth.month) and (today.day == birth.day):
print("{}Happy birthday to you!!!{}"
"\n{}Happy birthday to you!!!{}"
"\n{}Happy birthday to you!!!{}"
.format(colors["yellow"], colors["clean"], colors["cian"], colors["clean"], colors["purple"],
colors["clean"]))
elif will == 2:
print("Have a good day")
else:
print("{}Please enter 1 or 2 only{}".format(colors["red"], colors["clean"]))
|
a58d9898f16ffbc80673dad42d9410132d865a47 | MiguelChichorro/PythonExercises | /World 1/First attempts/ex002 - Showing Name.py | 354 | 3.609375 | 4 | colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
name = input('Enter your name: ')
print('{}Nice to meet you, {}{}{}'
.format(colors["blue"], colors["clean"], colors["yellow"], name))
|
6d3436542b700463ab0d7ba5de4c4f21e918ab89 | MiguelChichorro/PythonExercises | /World 3/Dictionary/ex094 - Uniting Dictionary and list.py | 2,799 | 3.640625 | 4 | from time import sleep
from datetime import date
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
people = list()
person = dict()
contperson = sumtotal = contgirl = 0
while True:
person['name'] = str(input("Enter your name: "))
person['gender'] = str(input(f"Enter your gender. \n{colors['blue']}[M]{colors['clean']} or {colors['purple']}[F]{colors['clean']}: ")).strip().upper()[0]
while person['gender'] != "M" and person['gender'] != "F":
person['gender'] = str(input(f"{colors['red']}Enter your gender. \n{colors['blue']}[M]{colors['clean']} or {colors['purple']}[F]{colors['clean']}: ")).strip().upper()[0]
if person['gender'] == "F":
contgirl += 1
day = int(input("Enter the your birth day: "))
month = int(input("Enter the your birth month: "))
year = int(input("Enter the your birth year: "))
birth = date(year, month, day)
today = date.today()
person['age'] = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
sumtotal += person['age']
contperson += 1
people.append(person.copy())
ans = str(input(
f"Do you want do add another person? [{colors['green']}Y{colors['clean']}/{colors['red']}N{colors['clean']}]: ")).strip().upper()[
0]
while ans != "Y" and ans != "N":
ans = str(input(
f"{colors['red']}Please just enter Yes or No {colors['clean']}[{colors['green']}Y{colors['clean']}/{colors['red']}N{colors['clean']}]: ")).strip().upper()[
0]
if ans == "N":
break
print(f"{colors['blue']}Reading data...{colors['clean']}")
sleep(1)
avg = sumtotal/contperson
print("=" * 30)
print(f"{colors['green']}{contperson} {'peoples' if contperson > 1 else 'person'} were registered{colors['clean']}")
print(f"{colors['green']}The average age is {avg:5.2f}{colors['clean']}")
if contgirl > 0:
print(f"The Women registred are", end=" ")
for c in people:
if c['gender'] in "F":
print(f"{c['name']}", end=" ")
print()
else:
print(f"{colors['red']}Any Woman was enter{colors['clean']}")
for c in people:
if c['age'] >= avg:
for k, v in c.items():
print(f'{k} = {v}; ', end=" ")
print()
print("=" * 30)
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
f6ce9c4fe2aede9cf5a2c0aae33d84490ab1a150 | MiguelChichorro/PythonExercises | /World 2/For/ex054 - Majority Group.py | 694 | 3.859375 | 4 | from datetime import date
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
today = date.today().year
old = 0
new = 0
for c in range(1, 8):
major = int(input("Enter seven birthday yeras: "))
age = today - major
if age >= 21:
old += 1
else:
new += 1
print("{}In the ages you enter {} {} minor and {} {} older{}"
.format(colors["purple"],
new, "person is" if new == 1 else "people are",
old, "person is" if old == 1 else "people are",
colors["clean"]))
|
e280976045fd51a9d1f53d85c00efb7708bfcccf | MiguelChichorro/PythonExercises | /World 3/Lists/ex078 - Bigger an Smaller on the list.py | 1,070 | 3.796875 | 4 | from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
values = list()
for c in range(0, 5):
values.append(int(input(f"Enter a number to the position {c}: ")))
print(f"{colors['blue']}Reading data...{colors['clean']}")
sleep(1)
print(f"{colors['green']}The bigger value is {max(values)} and you find him in the positions", end=" ")
for c, v in enumerate(values):
if v == max(values):
print(f"{c}...", end="")
print(f"\n{colors['yellow']}The smaller value is {min(values)} and you find him in the positions", end=" ")
for i, v in enumerate(values):
if v == min(values):
print(f"{i}...", end="")
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
138eb99b9b21888e2d605b2ab7be3b3780a47943 | MiguelChichorro/PythonExercises | /World 1/First attempts/ex003 - Adding Two Numbers.py | 571 | 3.796875 | 4 | colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
n1 = int(input('Enter a number: '))
n2 = int(input('Enter a number: '))
sum = n1 + n2
print('Your first number was {}{}{} '
'\nAnd your second was {}{}{} '
'\nThe sum between them is {}{}{}'
.format(colors["blue"], n1, colors["clean"],
colors["red"], n2, colors["clean"],
colors["green"], sum, colors["clean"]))
|
bdabee3ae2e59c6a9ca0515762c777fecad1ec02 | MiguelChichorro/PythonExercises | /World 3/Lists/ex079 - Unique values on the list.py | 1,045 | 3.546875 | 4 | from time import sleep
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
values = list()
while True:
print("if you want to stop just enter 0")
n = int(input("Enter a number:"))
if n not in values:
values.append(n)
print(f"{colors['green']}Value Added{colors['clean']}")
else:
print(f"{colors['red']}Duplicate value don´t added{colors['clean']}")
if 0 in values:
values.remove(0)
values.sort()
break
print(f"{colors['blue']}Reading data...{colors['clean']}")
sleep(1)
print(f"{colors['yellow']}Your list is {values}{colors['clean']}")
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
0a044022798adb5d9be72d158e492cf64a60acb6 | MiguelChichorro/PythonExercises | /World 3/Tuples/ex072 - Number Out.py | 878 | 3.921875 | 4 | colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
num = ("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty")
ans = 1
while ans == 1:
usunum, cont = -1, 0
while True:
usunum = int(input("Enter a number between 0 and 20: "))
if 0 <= usunum <= 20:
break
print(f"{colors['blue']}You enter the number {num[usunum]}{colors['clean']}")
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
f3322cf13019262a2580f16fe0f9542691539a42 | MiguelChichorro/PythonExercises | /World 3/Tuples/ex076 - Price List with Truple.py | 1,237 | 3.921875 | 4 | colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
ans = 1
while ans == 1:
tuple = ()
ans2 = 1
sum = 0
while ans2 == 1:
produ = str(input("Enter the product name: "))
tuple += produ,
price = int(input("Enter the product price: "))
sum += price
tuple += price,
ans2 = int(input(f"{colors['green']}\nPress [ 1 ] to enter another product or another number to leave: {colors['clean']}"))
print(f"{colors['cian']}={colors['clean']}" * 27)
print(f"{colors['cian']}{'Buy List': ^50}{colors['clean']}")
print(f"{colors['cian']}={colors['clean']}" * 27)
for i in tuple:
if type(i) is str:
print(f'{i:.<32}', end='')
else:
print(f'US$ {i:>5.2f}')
print(f"{colors['cian']}={colors['clean']}" * 27)
print(f"{'Total Price':.<32}", end="")
print(f'US$ {sum:>5.2f}')
ans = int(input(f"{colors['cian']}\nPress [ 1 ] to do again or another number to leave: {colors['clean']}"))
if ans != 1:
print(f"{colors['green']}Have a good day!{colors['clean']}")
|
2071d183d022624a62d55decd5567ece9a3af7c0 | MiguelChichorro/PythonExercises | /World 2/For/ex050 - Even Sum.py | 672 | 3.703125 | 4 | colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
sumc = 0
cont = 0
for c in range(1, 7):
print("{}----- {} Number -----{}".format(colors["cian"], c, colors["clean"]))
sum = int(input("Enter a number: "))
if (sum % 2) == 0:
sumc += sum
cont += 1
print("{}You enter {} even {} {} {}{}"
.format(colors["blue"], cont, "numbers" if cont > 1 else "number",
"and the sum between them is" if cont > 1 else "so don´t have a sum",
sumc, colors["clean"]))
|
e0d7d00c5c7c9c9f18fe6909e3128bed00c8e304 | AkashMondal987/Project100 | /bank.py | 923 | 3.734375 | 4 | class Atm:
def __init__(self,cardNumber,pin):
self.cardNumber = cardNumber
self.pin = pin
def checkBalance(self):
print("Your Balance Is 10,000")
def withdrawl(self,amount):
newAmount = 10000 - amount
print("You Have Withdrawhed: "+str(amount)+" Your Remaining Balance Is: "+str(newAmount))
def main():
cardNumber = input("Enter Your Card Number: ")
pin = input("Enter Your Pin: ")
newUser = Atm(cardNumber,pin)
print("Choose What You Want To Do...")
print("1. Balance 2.Withdraw")
activity = int(input("Enter The Number: "))
if(activity == 1):
newUser.checkBalance()
elif(activity == 2):
amount = int(input("Enter The Amount: "))
newUser.withdrawl(amount)
else:
print("Enter A Valid Number: ")
Atm.main() |
3a615108c97a54cceb7b8187aa0c23d26ef3ff18 | Keonhong/IT_Education_Center | /Jumptopy/Jump_to_python/Chapter6/map2.py | 329 | 3.921875 | 4 | d1 = {1:'one', 2:'two', 3:'three'}
def Add(a):
return a + a
def Mul(a):
return a * a
ret1 = list(map(Add, d1))
print(ret1)
ret2 = list(map(Mul, d1))
print(ret2)
ret1 = list(map(Add, [d1[i]for i in d1]))
print(ret1)
ret2 = list(map(Mul, [d1[i]for i in d1]))
print(ret2)
#문자열끼리 +는 되고, *는 안된다. |
501a3c83cff32f3074b42e1f8096f9cf0ddc1544 | Keonhong/IT_Education_Center | /Jumptopy/Data_science/CSV_test.py | 1,137 | 3.609375 | 4 | import csv
with open('Demographic_Statistics_By_Zip_Code.csv',newline='')as infile:
data = list(csv.reader(infile))
def get_csv_rowInstance(row_name):
row_instance = []
row_index = data[0].index(row_name)
for row in data[1:]:
row_instance.append(int(row[row_index]))
return row_instance
def print_row(row_instance, type = 'int'):
if type == 'int':
for i in row_instance:
print(int(i))
elif type == 'float':
for i in row_instance:
print(float(i))
elif type == 'str':
for i in row_instance:
print(i)
def print_col(col_instance):
for i in col_instance:
print(i, end=' ')
row_instance = input("write title: ")
print_row(row_instance)
# countParticipantsIndex = data[0].index("COUNT PARTICIPANTS")
# print("The index of 'COUNT PARTICIPANTS': "+str(countParticipantsIndex))
# countParticipants = []
# index = 0
# for row in data[1:]:
# countParticipants.append(int(row[countParticipantsIndex]))
# colum = 열(가로) // row = 행(세로)
# get_csv_rowInstance(row_index)
# 입력:row_index
# 출력:row_instance
|
cdaba15e987b834f5d69679ab7fad4a84664fd9b | Keonhong/IT_Education_Center | /Jumptopy/Codding_dojang/namedtuple( ).py | 1,732 | 3.75 | 4 | # collections.nametuple()의 메소드들
# 1) _make(iterable)
import collections
# Person 객체 만들기
Person = collections.namedtuple("Person", 'name age gender')
P1 = Person(name='Jhon', age=28, gender='남')
P2 = Person(name='Sally', age=28, gender='여')
# _make()를 이용하여 새로운 객체 생성
P3 = Person._make(['Peter', 24, '남'])
P4 = Person._make(['Ary', 23, '여'])
for n in [P1, P2, P3, P4]:
print('%s은(는) %d세의 %s성 입니다.' % n)
# 2) _asdict() >>> 기존에 생선된 namedtuple()의 인스턴스(객체)를 OrderedDict로 변환하는 함수
# _asdict()를 이용하여 OrderedDict로 변환
print(P3._asdict())
# 3) _replace(kwargs) >>> 기존에 생성된 nametuple()의 인스턴스의 값을 변경할때 사용
# _replace()를 이용하여 인스턴스 값 변경
P1 = P1._replace(name='Neo')
P2 = P2._replace(age=27)
P3 = P3._replace(age=26)
P4 = P4._replace(name='Ari')
print('-'*20)
for n in [P1, P2, P3, P4]:
print('%s은(는) %d세의 %s성 입니다.' % n)
# 4) _fields >>> 생성된 namedtuple()dml 필드명(field_names)를 tuple()형식으로 return해준다.
# _fields를 이용하여 필드명 출력
print(P1._fields)
# ('name', 'age', 'gender')
# 5) getattr() >>메소드는 아니지만 field_names로 namedtuple() 인스턴스의 값을 추출해준다.
print(getattr(P1,'name'))
print(getattr(P2, 'gender'))
print(getattr(P3, 'age'))
print(getattr(P4, 'age'))
# 6) dictionary에서 namedtuple()로 변환(**dict)
# double-star-operator(**)는 딕셔너리를 namedtuple()로 변환해준다.
dic = {'name': 'Tom', 'age':24, 'gender': '남'}
P3 = Person(**dic)
for n in [P1,P2,P3,P4]:
print('%s은(는) %d세의 %s성 입니다.'% n)
print(n) |
49c5d4341dd270029b3931038c8ffe4b46c8b3ca | dineshd1998/python-assignment | /factorial.py | 135 | 4.25 | 4 | def factorial(a):
if a==1:
return 1
else:
return a*factorial(a-1)
b=factorial(3)
print("Factorial of 3 is",b)
|
c49d3b7a67b467d9b39528c616e0c29391390a06 | BenikaH/NHL_stats | /ReinforcementLearning/blackJack/blackjack_policy_solver.py | 12,050 | 4 | 4 | """ This module implements SIMULATION and SAMPLING methods for solving the optimal policy for playing blackjack.
Simulation: The state-space is sampled by simulating different games situations and accumulating reward
following different strategies (policy)
Sampling: The state-space is sampled randomly in a number of blackjack games
This exercise is part of Sutton and Berto 2003, p.125
"""
from Utils.games.blackjack import *
from random import shuffle, choice
from Utils.programming import ut_ind2sub
class policySolver_blackjack(blackJack):
def __init__(self, gameType='infinite', method='simulation'):
# Initialize the engine
super(policySolver_blackjack, self).__init__(gameType=gameType)
self.method = method
# Initialize the state values
self.agent_states = list( range(12, 22) )
self.dealer_states = list( range(2, 12))
self.nStates = len(self.agent_states)*len(self.dealer_states)
self.state_value = np.random.random([len(self.agent_states), len(self.dealer_states), 2])
# Initialize the action values
self.action_value = np.zeros([len(self.agent_states), len(self.dealer_states), 2, 2])
# Initialize cards pairs
self.cardMat = np.reshape(np.array(range(1, 12)), [11, 1]) + np.array(range(1, 12))
self.cardVec = {2:[2], 3:[3], 4:[4], 5:[5], 6:[6], 7:[7], 8:[8], 9:[9], 10:['jack', 'queen', 'king'], 11:[1]}
self.colors = ['Heart', 'Diamond', 'Club', 'Spade']
def set_policy(self, policy=None):
# Dealer policy: hard-coded - dealer sticks on 17 and higher
self.policy_dealer = np.array([1] * 16 + [0] * 5) > 0 # True means HIT, False means STICK
# Agent policy
if policy is None:
# Initialize a random one
self.policy_agent = np.random.random([len(self.agent_states), len(self.dealer_states), 2]) > .5 # True means HIT, False means STICK
else:
# True means HIT, False means STICK
self.policy_agent = policy
self.nEvaluations = np.zeros([len(self.agent_states), len(self.dealer_states)])
def episode_initialize(self, method='simulation'):
# Select starting state - min nb of updates
if method == 'simulation':
# In case we "simulate" the states, we can chose to sample states for which sampling is lowest
idStart = (np.where(self.nEvaluations==np.min(self.nEvaluations)))
chxSt = choice( list(range(len(idStart[0]))) )
y,x = idStart[0][chxSt], idStart[1][chxSt]
elif method == 'exploringStarts':
y,x = [choice(range(len(self.agent_states))), choice(range(len(self.dealer_states)))]
else:
# In case we "sample" the states, we simply draw them randomly
y,x = choice(range(len(self.agent_states))), choice(range(len(self.dealer_states)))
self.current_state = [y,x]
# Set cards: dealer
dealer = {'hand': [str(choice(self.cardVec[self.dealer_states[x]])) + '_' + choice(self.colors), str(choice(self.cardVec[choice(range(2,12))])) + '_' + choice(self.colors)], 'shown': [True, False], 'plays': [], 'value': 0, 'status': 'On', 'usable': False}
# Set cards: agent
iy, ix = np.where(self.agent_states[y] == self.cardMat)
iy += 1
ix += 1
idUsable = choice( np.where([iy[lp]==11 or ix[lp]==11 for lp in range(len(iy))])[0] )
idUnusable = np.where([iy[lp]!=11 and ix[lp]!=11 for lp in range(len(iy))])[0]
if bool(choice([0,1])) or not len(idUnusable):
# Usable - need an ace
agent = {'hand': [str(min(xlp%11+1, xlp)) + '_' + choice(self.colors) for xlp in [iy[idUsable], ix[idUsable]]], 'shown': [True, True], 'plays': [], 'value': 0, 'status': 'On', 'usable': False}
else: # Unusable ace
idUnusable = choice(idUnusable)
agent = {'hand': [str(min(xlp%11+1, xlp)) + '_' + choice(self.colors) for xlp in [iy[idUnusable], ix[idUnusable]]], 'shown': [True, True], 'plays': [], 'value': 0, 'status': 'On', 'usable': False}
# Init game
self.deck_new(statusOnly=True, printStatus=False, initCards=[agent, dealer])
def episode_run(self, randomInit=True):
# ----------
# play the game
self.turn = 'agent'
curState = self.current_state
reward = 2
state_chain = [curState]
usable_chain = [self.agent['usable']]
action_chain = []
while self.turn == 'agent' and reward == 2:
# --- Pick action according to agent's policy
# Pick agent action at that state according to policy
if randomInit:
action = bool( choice([0,1]) )
randomInit = False
else:
action = self.policy_agent[curState[0], curState[1], int(self.agent['usable'])]
if action:
self.hand_do('hit', statUpd=False)
action_chain.append(1)
if self.agent['value']>0:
# Determine in which state we are now
curState = [self.agent_states.index(self.agent['value']), self.dealer_states.index(self.dealer['value'])]
# Append it to state chain
state_chain.append(curState)
usable_chain.append(self.agent['usable'])
else: # Stick
self.hand_do('stick', statUpd=False)
reward = self.game_status(statusOnly=True, printStatus=False)
action_chain.append(0)
while self.turn == 'dealer' and reward == 2:
# --- Pick action according to dealer's policy
if self.policy_dealer[self.dealer['value'] - 1]: # Hit
self.hand_do('hit', statUpd=False)
else:
self.hand_do('stick', statUpd=False)
reward = self.game_status(statusOnly=True, printStatus=False)
return reward, state_chain, usable_chain, action_chain
def evaluate_policy(self, nIterations=10000):
# Initialize the algorithm
returns = np.random.random([len(self.agent_states), len(self.dealer_states), 2])
visits = np.random.random([len(self.agent_states), len(self.dealer_states), 2])
# Start looping
for ii in range(nIterations):
# --- step1: initialize the episode
self.episode_initialize()
# --- step2: run the episode
reward, state_chain, usable_chain, _ = self.episode_run()
self.nEvaluations[self.current_state] += 1
self.history.append(reward)
# Unfold the reward onto chain
returns_usable = [returns_usable[x] + [reward] if x in state_chain and usable_chain[state_chain.index(x)] else returns_usable[x] for x in range(self.nStates)]
returns_unusable = [returns_unusable[x] + [reward] if x in state_chain and not usable_chain[state_chain.index(x)] else returns_unusable[x] for x in range(self.nStates)]
# Store new state values
self.state_value_usable = [np.mean(x) for x in returns_usable]
self.state_value_unusable = [np.mean(x) for x in returns_unusable]
def solve_policy_MC(self, nIterations=10000):
# Initialize the algorithm
returns = np.zeros(np.shape(self.action_value))
visits = np.ones(np.shape(self.action_value))
# Start looping
for ii in range(nIterations):
if not ii%1000: print('Iteration'+str(ii))
# --- step1: initialize the episode
self.episode_initialize(method='exploringStarts')
# --- step2: run the episode
reward, state_chain, usable_chain, action_chain = self.episode_run(randomInit=True)
#self.game_status(statusOnly=True)
#print(state_chain)
#print(action_chain)
self.nEvaluations[self.current_state] += 1
self.history.append(reward)
# Unfold the reward onto chain
firstVisit = dict((tuple(el),0) for el in state_chain)
for st, ac, us in zip(state_chain, action_chain, usable_chain):
if not firstVisit[tuple(st)]:
returns[st[0], st[1], int(us), ac] += [reward]
visits[st[0], st[1], int(us), ac] += 1
firstVisit[tuple(st)] += 1
# Store new state values
self.action_value = returns / visits
# Set new policy
self.policy_agent = np.argmax( self.action_value, axis=3 )
# ========
# LAUNCHER
# ========
# Instantiate the solver
BJS = policySolver_blackjack(method='sampling', gameType='finite')
# -----POLICY EVALUATION
# Make the agent's policy
#policyAG= np.reshape([x<20 for x in BJS.agent_states], [len(BJS.agent_states),1]) * [x>0 for x in BJS.dealer_states]
#policyAG= np.reshape(policyAG, [1, BJS.nStates])
#BJS.set_policy(policyAG)
# Evaluate that policy
#BJS.evaluate_policy(nIterations=10000)
# -----POLICY ITERATION
# Solve for policy - Monte-Carlo algorithm
BJS.set_policy()
BJS.solve_policy_MC(nIterations=500000)
"""
# ========
# DISPLAY
# ========
import matplotlib.pyplot as plt
from matplotlib import cm
import time
from mpl_toolkits.mplot3d import Axes3D
# --- POLICY ---
fig = plt.figure()
# Axis 1: unusable ace
Z = BJS.policy_agent[:,:,0]
ax1 = fig.add_subplot(121)
surf1 = ax1.imshow( Z )
ax1.set_xlabel("Dealer's states")
ax1.set_ylabel("Agent's states")
ax1.set_title('$\pi_*$: unusable ace')
ax1.set_xticks(list(range(0,len(BJS.dealer_states),2)))
ax1.set_xticklabels([BJS.dealer_states[x] for x in range(0,len(BJS.dealer_states),2)])
ax1.set_yticks(list(range(0,len(BJS.agent_states),2)))
ax1.set_yticklabels([BJS.agent_states[x] for x in range(0,len(BJS.agent_states),2)])
ax1.invert_yaxis()
# Axis 2: usable ace
Z = BJS.policy_agent[:,:,1]
ax2 = fig.add_subplot(122)
surf2 = ax2.imshow(Z)
ax2.set_xlabel("Dealer's states")
ax2.set_ylabel("Agent's states")
ax2.set_title('$\pi_*$: usable ace')
ax2.set_xticks(list(range(0,len(BJS.dealer_states),2)))
ax2.set_xticklabels([BJS.dealer_states[x] for x in range(0,len(BJS.dealer_states),2)])
ax2.set_yticks(list(range(0,len(BJS.agent_states),2)))
ax2.set_yticklabels([BJS.agent_states[x] for x in range(0,len(BJS.agent_states),2)])
ax2.invert_yaxis()
# --- STATE VALUE ---
fig = plt.figure()
X, Y = np.meshgrid(BJS.agent_states, np.flipud(BJS.dealer_states))
# Axis 1: usable ace
Z = np.transpose(np.reshape(BJS.state_value_usable, [len(BJS.agent_states), len(BJS.dealer_states)]))
ax1 = fig.add_subplot(121, projection='3d')
surf1 = ax1.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax1.set_xlim([BJS.agent_states[0], BJS.agent_states[-1]])
ax1.set_ylim([BJS.dealer_states[0], BJS.dealer_states[-1]])
ax1.set_zlim([-1, 1])
ax1.set_xlabel("Agent's states")
ax1.set_ylabel("Dealer's states")
ax1.set_zlabel('Value')
ax1.set_zticks([-1, 0, 1])
ax1.set_title('Usable ace')
ax1.invert_yaxis()
# Axis 2: unusable ace
Z = np.transpose(np.reshape(BJS.state_value_unusable, [len(BJS.agent_states), len(BJS.dealer_states)]))
ax2 = fig.add_subplot(122, projection='3d')
surf2 = ax2.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax2.set_xlim([BJS.agent_states[0], BJS.agent_states[-1]])
ax2.set_ylim([BJS.dealer_states[0], BJS.dealer_states[-1]])
ax2.set_zlim([-1, 1])
ax2.set_xlabel("Agent's states")
ax2.set_ylabel("Dealer's states")
ax2.set_zlabel('Value')
ax2.set_zticks([-1, 0, 1])
ax2.set_title('Unusable ace')
ax2.invert_yaxis()
""" |
e2572da8bcaf1dc0489eb12a6c7a588d183bb3bb | BenikaH/NHL_stats | /ReinforcementLearning/nArmed_bandit/ANSON_multiarmed_bandit.py | 5,277 | 3.8125 | 4 | """
multiarmed_bandit.py (author: Anson Wong / git: ankonzoid)
Classical epsilon-greedy agent solving the multi-armed bandit problem.
Given a set of bandits with a probability distribution of success, we
maximize our collection of rewards with an agent that explores with
epsilon probability, and exploits the action of highest value estimate
for the remaining probability. This experiment is performed many times
and averaged out and plotted as an averaged reward history.
The update rule for the values is via an incremental implementation of:
V(a;k+1) = V(a;k) + alpha*(R(a) - V(a;k))
where
k = # of times action "a" (essentially bandit here) was chosen in the past
V(a;k) = value of action "a"
R(a) = reward for choosing action (bandit) "a"
alpha = 1/k
Note that the reward R(a) is stochastic in this example and follows the probability
of the distributions provided by the user in the variable "bandits".
"""
import numpy as np
import matplotlib.pyplot as plt
def main():
# =========================
# Settings
# =========================
bandits = [0.1, 0.4, 0.5, 0.9, 0.1, 0.2, 0.8] # bandit probabilities of success
N_experiments = 1000 # number of experiments to perform
N_pulls = 2000 # number of pulls per experiment
epsilon = 0.01 # probability of random exploration (fraction)
save_fig = False # if false -> plot, if true save as file in same directory
# =========================
# Define bandit class
# =========================
N_bandits = len(bandits)
class Bandit:
def __init__(self, bandits):
self.prob = bandits # probabilities of success
self.n = np.zeros(N_bandits) # number of times bandit was pulled
self.V = np.zeros(N_bandits) # estimated value
def get_reward(self, action):
rand = np.random.random()
if rand < self.prob[action]:
reward = 1 # success
else:
reward = 0 # failure
return reward
# choose action based on epsilon-greedy agent
def choose_action(self, epsilon):
rand = np.random.random() # random float in [0.0,1.0)
if rand < epsilon:
return np.random.randint(N_bandits) # explore
else:
return np.argmax(self.V) # exploit
def update_V(self, action, reward):
# Update action counter
self.n[action] += 1
# Update V via an incremental implementation
# V(a;k+1) = V(a;k) + alpha*(R(a) - V(a;k))
# alpha = 1/k
# where
# V(a;k) is the value of action a
# k is the number of times action was chosen in the past
alpha = 1./self.n[action]
self.V[action] += alpha * (reward - self.V[action])
# =========================
# Define out experiment procedure
# =========================
def experiment(bandit, Npulls, epsilon):
action_history = []
reward_history = []
for i in range(Npulls):
# Choose action, collect reward, and update value estimates
action = bandit.choose_action(epsilon) # choose action (we use epsilon-greedy approach)
reward = bandit.get_reward(action) # pick up reward for chosen action
bandit.update_V(action, reward) # update our value V estimates for (reward, action)
# Track action and reward history
action_history.append(action)
reward_history.append(reward)
return (np.array(action_history), np.array(reward_history))
# =========================
#
# Start multi-armed bandit simulation
#
# =========================
print("Running multi-armed bandit simulation with epsilon = {}".format(epsilon))
reward_history_avg = np.zeros(N_pulls) # reward history experiment-averaged
for i in range(N_experiments):
# Initialize our bandit configuration
bandit = Bandit(bandits)
# Perform experiment with epsilon-greedy agent (updates V, and reward history)
(action_history, reward_history) = experiment(bandit, N_pulls, epsilon)
if (i+1) % (N_experiments/20) == 0:
print("[{}/{}] reward history = {}".format(i+1, N_experiments, reward_history))
# Sum up experiment reward (later to be divided to represent an average)
reward_history_avg += reward_history
reward_history_avg /= np.float(N_experiments)
print("reward history avg = {}".format(reward_history_avg))
# =========================
# Plot average reward history results
# =========================
plt.plot(reward_history_avg)
plt.xlabel("iteration #")
plt.ylabel("average reward (over {} experiments)".format(N_experiments))
plt.title("Multi-armed bandit with epsilon-greedy agent (epsilon = {})".format(epsilon))
if save_fig:
output_file = "multiarmed_bandit_reward_history_avg.pdf"
plt.savefig(output_file, bbox_inches="tight")
else:
plt.show()
# Driver
if __name__ == "__main__":
main() |
ccdb6e2205b1c98e3131c6e9b389fda5c0cd9aca | diksha12p/DSA_Textbooks | /Chapter 2/SumLists.py | 611 | 3.5 | 4 | import math
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self,l1, l2):
root = ans_ll = ListNode(-math.inf)
carry, val = 0, 0
while l1 or l2 or carry:
val1, val2 = 0, 0
if l1:
val1 = l1.val
l1 = l1.next
if l2:
val2 = l2.val
l2 = l2.next
carry, val = divmod(l1.val + l2.val + carry,10)
ans_ll.next = ListNode(val)
ans_ll = ans_ll.next
return root.next
|
34c9fef6c63a0bca1885a32dc43d4e12d0adec14 | diksha12p/DSA_Textbooks | /Chapter 2/Partition.py | 751 | 3.671875 | 4 | import math
class Node:
def __init__(self, val):
self.value = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_val):
new_node = Node(new_val)
new_node.next = self.head
self.head = new_node
class Solution:
def partition(self, head: Node, x: int) -> Node:
head_l1 = l1 = Node(-math.inf)
head_l2 = l2 = Node(-math.inf)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = head_l2.next
return head_l1.next
|
3add715e7ec491c2b16bca54448fa5aa5ff80e56 | diksha12p/DSA_Textbooks | /Chapter1/PalindromePermutation.py | 989 | 3.8125 | 4 | from collections import Counter
# Using inbuilt Counter() method
def palindrome_permutation(s):
d = Counter(s.lower().replace(" ",""))
count = 0
for value in d.values():
if value % 2: count += 1
return count <= 1
# Without using inbuilt Counter() method
# Without using lower() and replace() methods
def char_number(c):
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
val = ord(c)
if a <= val <= z:
return val - a
elif A <= val <= Z:
return val - A
return -1
def alt_palindrome_permutation(s):
data_log = [0 for _ in range(ord('a'), ord('z') + 1)]
count = 0
for char in s:
char_val = char_number(char)
if char_val != -1:
data_log[char_val] += 1
if data_log[char_val] % 2:
count += 1
else:
count -= 1
return count <= 1
s = "Tact Coa"
print(palindrome_permutation(s))
print(alt_palindrome_permutation(s)) |
935884e2264b4dc42e9582fdbea52b4189de634b | diksha12p/DSA_Textbooks | /Chapter1/IsUnique.py | 322 | 4.0625 | 4 | def is_unique(str):
if len(str) > 128: # Assuming ASCII character set
return False
is_unique_list = list()
for char in str:
if char in is_unique_list:
return False
else:
is_unique_list.append(char)
return True
string = "dikshaa"
print(is_unique(string))
|
3e12a5468443748b0ab61c3af2e106fc2d561112 | diksha12p/DSA_Textbooks | /Chapter1/OneIsPermutationOfOther.py | 553 | 3.859375 | 4 | def check_permutation_symetric(str1, str2):
# Type of string? ASCII / Unicode? Assume, ASCII.
# Thus, character set length = 128
if len(str1) != len(str2):
return False
char_count = [0] * 128
for char in str1:
char_count[ord(char)] += 1
for char in str2:
char_count[ord(char)] -= 1
if char_count[ord(char)] < 0:
return False
return True
s1 = "dog "
s2 = "dog"
print(check_permutation_symetric(s1,s2))
print(s1.strip().upper())
# for char in s1:
# print(ord(char))
|
9f68e7fd902b128ddb5a25df19964eec6f775f9f | diksha12p/DSA_Textbooks | /Chapter3/AnimalShelter.py | 2,321 | 3.6875 | 4 | class Animal(object):
def __init__(self, name=None, type=None):
self.name = name
self.type = type
self.timestamp = 0
self.next = None
class AnimalShelter(object):
def __init__(self):
self.cat_head = None
self.cat_tail = None
self.dog_head = None
self.dog_tail = None
self.order = 0
def enqueue(self, animal_name, animal_type):
self.order += 1
new_animal = Animal(animal_name, animal_type)
new_animal.timestamp = self.order
if new_animal.type == 'cat':
if not self.cat_head:
self.cat_head = new_animal
if self.cat_tail:
self.cat_tail.next = new_animal
self.cat_tail = new_animal
if new_animal.type == 'dog':
if not self.dog_head:
self.dog_head = new_animal
if self.dog_tail:
self.dog_tail.next = new_animal
self.dog_tail = new_animal
def deque_cat(self):
if self.cat_head:
new_animal = self.cat_head
self.cat_head = new_animal.next
return str(new_animal.name)
else:
raise Exception('No cat left!')
def deque_dog(self):
if self.dog_head:
new_animal = self.dog_head
self.dog_head = new_animal.next
return str(new_animal.name)
else:
raise Exception('No dog left!')
def deque_any(self):
if self.cat_head and not self.dog_head:
return self.deque_cat()
elif self.dog_head and not self.cat_head:
return self.deque_dog()
elif self.cat_head:
if self.cat_head.timestamp < self.dog_head.timestamp:
return self.deque_cat()
else:
return self.deque_dog()
else:
raise Exception('No animal left!')
if __name__ == "__main__":
AS = AnimalShelter()
AS.enqueue('mia', 'cat')
AS.enqueue('tommy', 'dog')
AS.enqueue('lisa', 'cat')
AS.enqueue('bruno', 'dog')
AS.enqueue('brando', 'dog')
AS.enqueue('molly', 'cat')
print("\nSelect a cat")
print(AS.deque_cat())
print("\nSelect a dog")
print(AS.deque_dog())
print("\nSelect any animal")
print(AS.deque_any())
|
84d6bfe4e4fe89f4a08d2e8ca73631d950c86fcf | KarthickM89/basicPython | /loops.py | 236 | 4.28125 | 4 | #for i in [0, 1, 2, 3, 4, 5]:
# print(i)
#for i in range(6):
# print(i)
# Defining names
names = ["karthick", "kaviya", "kavinilaa"]
name1 = "kannan"
# Looping and Printing
for name in names:
print(name)
for n in name1:
print(n) |
083ecb47745d21c03137430c25b4be5341685e9b | TaiPhillips/concurrency-in-python-with-asyncio | /chapter_08/listing_8_3.py | 863 | 3.515625 | 4 | import asyncio
from asyncio import StreamReader
from typing import AsyncGenerator
async def read_until_empty(stream_reader: StreamReader) -> AsyncGenerator[str, None]:
while response := await stream_reader.readline(): #A
yield response.decode()
async def main():
host: str = 'www.example.com'
request: str = f"GET / HTTP/1.1\r\n" \
f"Connection: close\r\n" \
f"Host: {host}\r\n\r\n"
stream_reader, stream_writer = await asyncio.open_connection('www.example.com', 80)
try:
stream_writer.write(request.encode()) #B
await stream_writer.drain()
responses = [response async for response in read_until_empty(stream_reader)] #C
print(''.join(responses))
finally:
stream_writer.close() #D
await stream_writer.wait_closed()
asyncio.run(main())
|
3d3b20035e27eb4889b83004bc3e638005e371d4 | PazBruna/Python_POO | /herancaMultipla.py | 1,107 | 3.734375 | 4 | class Funcionario:
def __init__(self, nome):
self.nome = nome
def registra_hora(self, horas):
print('Horas registradas...')
def mostrar_tarefas(self):
print('Fez muita coisa..')
class Caelum(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Caelumer')
def busca_cursos_do_mes(self, mes = None):
print(f'Mostrando cursos - {mes}' if mes else 'mostrando cursos desse mes')
class Alura(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Alurete')
def busca_perguntas_sem_resposta(self):
print('Mostrando perguntas não respondidas do forúm')
class Hipster:
def __str__(self):
return f'Hipster, {self.nome}'
class Junior(Alura):
pass
class Pleno(Caelum, Alura):
pass
class Senior(Alura, Caelum, Hipster):
pass
#MRO
#good head (hierarquia especifica) - Verifica se há outra classe na hierarquia, no caso do pleno, se não houver o metodo na classe Caelum ele irá imprimir o método de Alura.
ricardo = Senior('Ricardo')
print(ricardo)
|
386dc342370fed024bcf3641747c7a398bef37da | simonecorbo99/Hacktoberfest-2020-LeetCode-Problems | /problems/nehalabhasetwar-RemoveKdigits-python.py | 1,820 | 3.765625 | 4 | '''
* Solution to Remove K Digits at LeetCode in Python
*
* author: Neha Labhasetwar
* ref: https://leetcode.com/problems/remove-k-digits/
'''
'''PROBLEM:
Given a non-negative integer num represented as a string,
remove k digits from the number so that the new number is the smallest possible.
EXPLANATION:-
Suppose If we have num 1543, k = 2
Traverse through each digit in num,
if you found, previous digit is greater than the current digit, delete it.
Suppose given num = 14329 and k = 2
Do the following steps to get least number:-
1. Traverse through each digit in num
2. Now, pop stack
while k > 0 top of the stack is greater than current digit.
this is beacuse if stack has 1 4
then, current digit is 3, then 4 > 3 so, pop 4.
because, the number starting with 13 is smaller than 14.
That's why we need to pop stack while top is
greater than current digit.
3. After traversing through all the digits,
then stack looks like this = 1 2 9
if k > 0
pop k times
because we need to delete k digits from the number.
4. Now, create a string variable,
then insert every digit in stack at the beginning.
This is because,
while popping stack 9 will first come out, then 2, and then 1.
So, add digits in reverse.
Here, I am adding digits at starting position.
So,
when 9 is popped, str = 9
when 2 is popped str = 29
when 1 is popped str = 129.
that's how we will get number in reverse order.
5. Now, Del any leading zeros are in string.
6. return smallest string.
'''
class Solution:
def removeKdigits( self , num: str, k: int) -> str:
stack = []
for digit in num:
while k > 0 and len(stack) > 0 and stack[-1] > digit:
k -= 1
stack.pop()
stack.append(digit)
if k > 0:
stack = stack[:-k]
return "".join(stack).lstrip("0") or "0"
|
82c3c88acbdead18b0c8e96111b413d2508251ee | zdimon/wezom-python-course | /students/Kolya/hometask/shah.py | 1,218 | 3.5 | 4 | import random
cards = [2,3,4,5,6,7,8,9,10]
coloda = []
vzyal = []
chisla = 0
def it():
while True:
i = random.randint(0, 35)
if i not in vzyal:
break
vzyal.append(i)
else:
continue
return i
for row in cards:
for r in range(4):
coloda.append(row)
random.shuffle(coloda)
for row in range(2):
i = random.randint(0, 35)
print('Ваше число - ' + str(coloda[i]))
chisla += coloda[i]
vzyal.append(i)
print('Общий счёт - ' + str(chisla))
while True:
a = input('Хотите ли взять ещё карту? ')
if a == 'да':
i = it()
print('Ваше число - ' + str(coloda[i]))
chisla += coloda[i]
print('Общий счёт - ' + str(chisla))
if chisla < 22:
continue
else:
print('Вы проиграли :(')
break
else:
fl = coloda[it()]
sl = coloda[it()]
chisla2 = fl + sl
while chisla2 < 22:
irr = it()
chisla2 + coloda[irr]
if chisla2 > 21:
print('Вы победили :)')
chisla2 = 0
break
else:
break
print(chisla2)
if chisla > chisla2:
print('Вы победили :)')
break
elif chisla < chisla2:
print('Вы проиграли :(')
break
else:
print('Ничья -_-')
break
|
c8efb09db7c8fccd725e0004fe16b74ea22030c9 | mingzidouzhemenanqi/Getting-started-with-python-code | /Files from MOOC/Python实例/第一期MOOC实例/实例十三:体育竞技模拟/体育竞技模拟.py | 1,294 | 3.640625 | 4 | #体育竞技分析:
import random as r
def monibisai(an,bn,n):
aj,bj=0,0
for i in range(n):
jieguo=danju(an,bn,i)
if jieguo=='a':
aj+=1
else:
bj+=1
return aj,bj
def danju(an,bn,n):
af,bf=0,0
#qiu=faqiu(n)
qiu='A'
while (af<=15 and bf<=15):
if qiu=='A':
if r.random()<an:
af+=1
else:
qiu='B'
else:
if r.random()<bn:
bf+=1
else:
qiu='A'
if af>bf:
return 'a'
else:
return 'b'
def jieshu(af,bf):
return (af<=15 and bf<=15)
def faqiu(n):
if n%2==0:
return 'A'
else :
return 'B'
def fenxi(aj,bj,n):
print("A的胜率为{},B的胜率为{}".format(aj/n,bj/n))
def huoqu():
print("该程序用于简易模拟分析A,B两个球员的胜率")
a=eval(input("请输入A的能力值(0,1):"))
b=eval(input("请输入B的能力值(0,1):"))
n=eval(input("请输入模拟局数:"))
return a,b,n
def main():
a,b,n=huoqu()
aj,bj=monibisai(a,b,n)
fenxi(aj,bj,n)
main()
|
ec0df6caf03f776cc37829b1ee29fafabbc560de | mingzidouzhemenanqi/Getting-started-with-python-code | /Files from MOOC/Python实例/第一期MOOC实例/实例四:简易文本进度条/简易进度条模拟.py | 198 | 3.578125 | 4 | #简易文本进度条模拟
import time as t
jindu=10
for i in range(jindu+1):
a=i*'*'
b=(jindu-i)*'.'
c=i*10
print("{:^3.0f}%[{}->{}]".format(c,a,b))
t.sleep(2)
|
2d62805a6c3d2b0c044e0848e150e58e0a16beae | dfialho/pico-adapters | /adapters/configs/base.py | 1,912 | 3.828125 | 4 | from logger import Logging
class LoadError(Exception):
""" Raised when an error occurs while loading the config file. """
class BaseConfiguration:
"""
Abstracts the access to the configuration file. This is the base class
to access configuration files. It accepts any parameter key and value.
The responsibility to check the validity of parameters and values is given
to the specific implementations.
"""
def __init__(self, config_file):
self.config_file = config_file
def load(self):
"""
Loads the configuration file. Raises LoadError if the config file
is corrupted.
"""
log_file = None # will store the loaded path to the log file
with open(self.config_file) as file:
for i, line in enumerate(file):
try:
line = line.rstrip('\n\r')
key, value = line.split(':')
except ValueError:
raise LoadError("error in line %d" % i)
if key == 'log':
log_file = value
continue
self._add_param(key, value)
Logging.setup(log_file)
self._finished_loading()
def _add_param(self, param_key, param_value):
"""
Adds a new parameter to the list of loaded parameters. This must be
implemented by the configuration subclasses. If the parameter key or
value are not valid it must raise a LoadError.
"""
pass
def _finished_loading(self):
"""
Called in the end of the load() method, once the loading of the
configuration file finishes. Subclasses should implement this method
accordingly if they want to take any action after loading. May raise
a LoadError if the implementation detects a loading error at this point.
"""
pass
|
cfa1923fa38c9bd1653164e5989698e03748dfe5 | zebleck/SheetDownloader | /inputter.py | 2,308 | 3.59375 | 4 | import tkinter as tk
from tkinter import filedialog
import getpass
import os.path
class Inputter:
def GetInput(self):
root = tk.Tk()
root.withdraw()
name = input("Dein Name: ")
if not(os.path.isfile(name + ".txt")):
self.Setup(name)
return name
def Setup(self, name):
print("""Wilkommen. Dieses Programm wird für dich Skripte und Übungsblätter
für Theoretische Physik 1, Experimentalphysik 1, Lineare Algebra 1 oder Analysis 1
herunterladen.
Benutzername und Passwort der Übungsgruppenverwaltung/Moodle
werden dafür offensichtlich benötigt. Diese Daten werden in %s.txt
im Ordner dieses Programms gespeichert, um zukünftig schnell
darauf zugreifen zu können (mehr nicht).
Übungsgruppenverwaltung: https://uebungen.physik.uni-heidelberg.de/uebungen/
Moodle: https://elearning2.uni-heidelberg.de/\n""" % (name))
f = open(name + ".txt", 'w')
f.write(input("Übungsgruppenverwaltung-Benutzername: ") + "\n")
f.write(getpass.getpass("Übungsgruppenverwaltung-Passwort: ") + "\n")
f.write(input("Moodle-Benutzername: ") + "\n")
f.write(getpass.getpass("Moodle-Passwort: ") + "\n")
doesAna = self.GetYesNo("Nimmst du an Analysis 1 teil [Y/N]? ")
f.write(doesAna + "\n")
dirPrompts = ['Theo1 Übungsblätter',
'Ex1 Skripte', 'Ex1 Übungsblätter', 'Alles andere bezüglich Ex1',
'La1 Skripte', 'La1 Übungsblätter', 'Alles andere bezüglich La1']
anaPrompts = ['Ana1 Skripte', 'Ana1 Übungsblätter', 'Alles andere bezüglich Ana1']
print("Wähle den Ordner für:")
for prompt in dirPrompts:
print("-" + prompt)
f.write(filedialog.askdirectory(title=prompt) + "\n")
if doesAna == "y":
for prompt in anaPrompts:
print("-" + prompt)
f.write(filedialog.askdirectory(title=prompt) + "\n")
else:
for i in range(3):
f.write("-\n")
f.close()
def GetYesNo(self, question):
while True:
answer = input(question)
if answer.lower() == 'y' or answer.lower() == 'n':
return answer.lower()
|
6b5045fe8bd561467f4412a5c4bb7063bef7349e | zhouyuq6/CSC180-190-Labs | /CSC180/lab3/redfibo.py | 311 | 3.609375 | 4 | def fibo(n):
if n==0:
return 1
elif n==1:
return 1
else:
return fibo(n-1)+fibo(n-2)
def fiboL(n):
fibol=[]
for i in range(0,n+1):
fibol=fibol+[fibo(i)]
return fibol
def redfibo(n):
Fibol=list(fiboL(n))
def reducingMulti(a,b):
return a*b
redFibo=reduce(reducingMulti,Fibol)
return redFibo
|
789a38742b091176b8c9a16d80f84d1810fb02f0 | joshuasturre/TryPy | /montyhallsim.py | 446 | 3.546875 | 4 | from random import randint
import time
while True:
x = 0
y = int(input('How many array\'s would you like created?'))
while x < y:
myList = [0, 0, 0]
toChange = randint(0, 2)
if toChange == 0:
myList[0] = 1
if toChange == 1:
myList[1] = 1
if toChange == 2:
myList[2] = 1
print(myList)
x = x + 1
|
96b4061196c3dc36646c9f3b88a004890db47edf | KostaSav/Tic-Tac-Toe | /console.py | 1,231 | 4.1875 | 4 | ########## Imports ##########
import config
# Initialize the Game Board and print it in console
board = [
[" ", "|", " ", "|", " "],
["-", "+", "-", "+", "-"],
[" ", "|", " ", "|", " "],
["-", "+", "-", "+", "-"],
[" ", "|", " ", "|", " "],
]
## Print the Game Board in console
def print_board():
for line in board:
for char in line:
print(char, end="")
print()
## Reset the board to empty
def reset_board():
for line in board:
for i in range(len(line)):
if line[i] == "X" or line[i] == "O":
line[i] = " "
## Draw the played piece on the board
def place_piece(pos, first_player_turn, piece):
if first_player_turn:
config.player1_positions.add(pos)
else:
config.player2_positions.add(pos)
if pos == 1:
board[0][0] = piece
elif pos == 2:
board[0][2] = piece
elif pos == 3:
board[0][4] = piece
elif pos == 4:
board[2][0] = piece
elif pos == 5:
board[2][2] = piece
elif pos == 6:
board[2][4] = piece
elif pos == 7:
board[4][0] = piece
elif pos == 8:
board[4][2] = piece
elif pos == 9:
board[4][4] = piece |
80e4683b931fc26be362d562862bedd83d78fead | Studia-AMW/oor | /Lab_2 - procesy/Lab2 - kolejka procesów.py | 1,769 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import time
import multiprocessing
def ciąg_fibannaciego(n):
if n < 0: # nie można obliczyć ciągu Fibannaciego dla liczb ujemnych
raise ValueError
if n < 2:
return n
return ciąg_fibannaciego(n-1)+ciąg_fibannaciego(n-2) #rekurencyjne wywołanie funkcji
def fibonacci(do_kolejki, z_kolejki):
while True:
n = do_kolejki.get()
if n == None:
break
czas_rozpoczęcia = time.time() # czas rozpoczęcia obliczania ciągu
wynik = ciąg_fibannaciego(n) # wynik ciągy
czas_zakończenia = time.time() # czas zakończenia obliczania ciągu
z_kolejki.put((n, wynik, czas_zakończenia-czas_rozpoczęcia))
z_kolejki.put((None, None, None))
def main():
czas_rozpoczęcia = time.time()
do_kolejki = multiprocessing.Queue()
z_kolejki = multiprocessing.Queue()
numer_procesu = multiprocessing.cpu_count()
for _ in range(numer_procesu):
multiprocessing.Process(target=fibonacci,
args=(do_kolejki, z_kolejki)).start()
for i in range(28, 36): # Obliczanie ciągu Fibannaciego dla kolejnych liczb w zakresie 28-35
do_kolejki.put(i)
for _ in range(numer_procesu):
do_kolejki.put(None)
while True:
n, wynik, czas_wyliczenia = z_kolejki.get()
if n == None:
numer_procesu -= 1
if numer_procesu == 0: break
else:
print ("Ciąg Fibannaciego z liczby: %3d = %7d wyliczenie zajęło: %0.3fs" % ( n, wynik, czas_wyliczenia))
czas_zakończenia = time.time()
print ("Całkowity czas obliczeń: %0.3fs" % (czas_zakończenia - czas_rozpoczęcia))
if __name__ == "__main__":
main()
|
c03e3f76b690c87b8939f726faeac5c0d6107b93 | Anwar91-TechKnow/PythonPratice-Set2 | /Swipe two numbers.py | 1,648 | 4.4375 | 4 | # ANWAR SHAIKH
# Python program set2/001
# Title: Swipe two Numbers
'''This is python progaramm where i am doing swapping of two number using two approches.
1. with hardcorded values
2. Values taken from user
also in this i have added how to use temporary variable as well as without delcaring
temporary varibale.
============================================================
'''
# Please commentout the rest approches and use only one approch at the time of execution.
import time
#1. with hardcorded values
num1=55
num2=30
print("Value of num1 before swapping : ",num1)
print("Value of num2 before swapping : ",num2)
time.sleep(2)
#now here created temporary varibale to store value of numbers.
a = num1 #it will store value in variable called a
num1=num2 #here num2 will replace with num1 value
num2=a #here num2 value swapped with num1 which
#swapping is done
print("Value of num1 After swapping : ",num1)
print("Value of num2 after swapping : ",num2)
time.sleep(3)
#second example:
#2. Values taken from user
#we can take input from user also
num_one=input("Enter first number : ")
num_two=input("Enter Second number : ")
time.sleep(3)
b = num_one
num_one=num_two
num_two=b
print("Value of first number After swapping : ",num_one)
print("Value of second number swapping : ",num_two)
time.sleep(3)
#without delcaring temporary variable.
num1=20
num2=5
print("Value of num1 before swapping : ",num1)
print("Value of num2 before swapping : ",num2)
time.sleep(3)
num1,num2=num2,num1
#swapping is done
print("Value of num1 After swapping : ",num1)
print("Value of num2 after swapping : ",num2)
time.sleep(3) |
e61a0695fa87299f9263befc6aa54c304991d020 | NVillafane05/ronronear-paradigmas | /tp integrador/main.py | 993 | 3.90625 | 4 | from Tweet import *
from Ronronear import *
class Main():
ronronear = Ronronear()
usuario = "@"+input("Ingrese su usuario: ")
print("Bienvenido/a "+usuario+"\n")
while (True):
try:
op = int(input("1. Add tweet\n2. Cambiar de usuario\n3. Ver usuarios - tweets\n4. Salir\n"))
if(op==4):
break
else:
if (op==2):
usuario = "@"+input("Ingrese su usuario: ")
print("Bienvenido/a "+usuario+"\n")
elif (op==1):
myTweet = input("Add tweet: ")
if (len(myTweet.split(' '))>15):
print ("Por favor, el tweet debe tener solo 15 palabras")
else:
ronronear.recibirTweet(usuario,myTweet)
elif (op==3):
ronronear.printTweets()
except ValueError:
print ("Por favor, ingrese una opción correcta")
print ("¡Hasta la próxima!")
# tweet = Tweet('HOLA @sspalisa', 'sspalisa')
# print(tweet.mensaje)
# print(tweet.user)
# print(tweet.longitudInvalida())
# print(tweet.tweetDirigido())
# print(tweet.aQuienSeDirige())
|
f64823d386ece3c87d07b7d1d5b0f10fef136df3 | Umbreon19/PythonHw | /chatbot.py | 329 | 3.828125 | 4 | def introuduction():
Name=input('What is your Name')
print('How are you doing?,'+Name+'')
Candy=input('What Candy do you like?')
print('Nice! I like '+Candy+' too!')
Cheese=input('What kind of Cheese do you like best?')
print('I could eat '+Cheese+' all the time!')
print('sorry I have to go now...')
|
4fe6d681d8f6fb36a4e6feddbc89f3921e155ea3 | ArseniyKichkin/2021_Kichkin_infa | /exercise_12.py | 311 | 3.5 | 4 | import turtle
turtle.speed(0)
turtle.shape('turtle')
turtle.left(90)
i = 0
while i < 4:
n = 0
while n < 180:
turtle.forward(1)
turtle.right(1)
n = n + 1
n = 1
while n < 180:
turtle.forward(0.15)
turtle.right(1)
n = n + 1
i = i + 1
input()
|
0acb335f3eeb203429541747b2c86d89dab378c0 | ArseniyKichkin/2021_Kichkin_infa | /exercise_6.py | 259 | 4 | 4 | import turtle as t
n = int(input('Введите количество лап' + '\n'))
t.shape("turtle")
t.color("blue")
t.width(2)
for i in range(n):
t.forward(80)
t.stamp()
t.backward(80)
t.left(180)
t.left(180 * (n - 2) // n)
input()
|
21a3132034b1fc55a409efc63222da273727a919 | jven2/advocatia | /ml.py | 5,751 | 3.53125 | 4 | import numpy as np
import pandas as pd
import pickle
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn import preprocessing
"""
load_data(adv_data_name, county_level_name)
Loads the provided filenames into pandas dataframes, then returns the dataframes
Calls subfunctions to create and manipulate the dataframes
"""
def load_data(adv_data_name, county_level_name):
adv_data_df = load_adv_data(adv_data_name)
county_level_df = load_county_data(county_level_name)
return adv_data_df, county_level_df
"""
load_adv_data(adv_data_name)
Loads the data from the Medicaid_Most_Recent_1000.txt file.
Manipulates the data to remove spaces from the county column
Replaces Male and Female in the Sex column with 0 and 1, respectively
Filters out any rows where the income is zero or there is no county listed
Returns a pandas dataframe
"""
def load_adv_data(adv_data_name):
adv_data_df = pd.read_csv(adv_data_name)
adv_data_df = adv_data_df.sample(frac=1)
return adv_data_df
"""
load_county_data(county_level_name)
Reads the relevant data from the est16all.csv file into a pandas dataframe
Manipulates the county column to remove spaces
Returns a pandas dataframe
"""
def load_county_data(county_level_name):
county_level_df = pd.read_csv(county_level_name, quotechar='"', skipinitialspace=True, header=3, usecols=[2,3,7,22])
county_level_df.columns = ['state_id', 'county', 'poverty_percent','median_income']
county_level_df['county'] = county_level_df['county'].str.replace(" ","")
return county_level_df
"""
create_feature_arr(adv_data_df, county_level_df)
This function creates the array of features (value used to predict)
First, an ndarray (numpy array) of the required size is initialized to all zeros.
Next, county level income values and poverty percentages corresponding to the county of each person in the advocatia data is placed into the array.
Various other values from the advocatia data are placed into the array.
Returns a numpy ndarray
"""
def create_feature_arr(adv_data_df, county_level_df):
number_of_features = 7
feature_arr = np.zeros((adv_data_df.shape[0],number_of_features), np.int32)
for index, row in adv_data_df.iterrows():
#feature_arr.put(index*number_of_features, int((county_level_df.query('state_id == \'' + str(row['StateId']) + '\' and county == \'' + str(row['County']) +'\'').iloc[0]['median_income']).replace(',','')))
feature_arr.put(index*number_of_features, float((county_level_df.query('state_id == \'' + str(row['StateId']) + '\' and county == \'' + str(row['County']) +'\'').iloc[0]['poverty_percent']).replace(',','')))
feature_arr[:,1]=adv_data_df['AgeAsOfNow']
feature_arr[:,2]=adv_data_df['HouseholdSize']
feature_arr[:,3]=adv_data_df['UsCitizen']
feature_arr[:,4]=adv_data_df['lat']
feature_arr[:,5]=adv_data_df['lng']
feature_arr[:,6]=adv_data_df['TotalIncome']
return feature_arr
"""
create_value_arr(adv_data_df)
Creates the class array (values we are trying to predict)
Returns a numpy ndarray.
"""
def create_value_arr(adv_data_df):
return adv_data_df["MedicaidEligible"]
"""
split_arrs(feature_arr, value_arr)
Splits the feature and value arrays into training and testing subsets.
Returns a tuple containing training and testing subsets of both arrays.
"""
def split_arrs(feature_arr, value_arr):
feature_train_arr, feature_test_arr = np.split(feature_arr,[feature_arr.shape[0]-1])
value_train_arr, value_test_arr = np.split(value_arr,[value_arr.shape[0]-1])
return (feature_train_arr, value_train_arr, feature_test_arr, value_test_arr)
def split_arrs_test(feature_arr, value_arr):
feature_train_arr, feature_test_arr = np.split(feature_arr,[4700])
value_train_arr, value_test_arr = np.split(value_arr,[4700])
return (feature_train_arr, value_train_arr, feature_test_arr, value_test_arr)
def preprocess_data(arr_tuple):
scaler = preprocessing.StandardScaler().fit(arr_tuple[0].astype('float'))
scaled_train=scaler.transform(arr_tuple[0].astype('float'))
scaled_test=scaler.transform(arr_tuple[2].astype('float'))
return (scaled_train,arr_tuple[1].astype('int'),scaled_test,arr_tuple[3].astype('int')), scaler
def knn_model(arr_tuple):
neigh=KNeighborsClassifier(n_neighbors=13)
neigh.fit(arr_tuple[0].astype('float'),arr_tuple[1].astype('float'))
score = neigh.score(arr_tuple[2].astype('float'),arr_tuple[3].astype('float'))
return score
def knregressor(arr_tuple, scaler):
neigh = KNeighborsRegressor(n_neighbors = 13)
neigh.fit(arr_tuple[0],arr_tuple[1])
file_Name = "model.pkl"
fileObject = open(file_Name, 'wb')
pickle.dump((neigh,scaler),fileObject)
fileObject.close()
def run_classifiers(adv_data_df, county_level_df):
feature_arr = create_feature_arr(adv_data_df, county_level_df)
value_arr = create_value_arr(adv_data_df)
arr_tuple = split_arrs_test(feature_arr, value_arr)
arr_tuple, scaler = preprocess_data(arr_tuple)
print "KNN score: " + str(knn_model(arr_tuple))
print np.sum(arr_tuple[3])
def run_regressions(adv_data_df, county_level_df):
feature_arr = create_feature_arr(adv_data_df, county_level_df)
value_arr = create_value_arr(adv_data_df)
arr_tuple = split_arrs(feature_arr, value_arr)
arr_tuple, scaler = preprocess_data(arr_tuple)
knregressor(arr_tuple, scaler)
def main():
adv_data_df,county_level_df = load_data("data_with_latlng.csv", "est16all.csv")
#run_classifiers(adv_data_df, county_level_df)
run_regressions(adv_data_df, county_level_df)
if __name__ == "__main__":
main() |
601d9595f5f555b81b740c3d47ffa9c187ccdc2f | jonalynnA-cs29/cs-module-project-algorithms | /rock_paper_scissors/rps.py | 1,083 | 3.859375 | 4 | #!/usr/bin/python
import sys
import random
def rock_paper_scissors(n):
global all_combinations
all_combinations = []
move_options = ['rock', 'paper', 'scissors']
def build_moves(countdown, piece_being_built):
if countdown == 0:
all_combinations.append(piece_being_built)
return
for move in move_options:
new_piece_result = piece_being_built + [move]
build_moves(countdown - 1, new_piece_result)
build_moves(n, [])
return all_combinations
if __name__ == "__main__":
num_of_people = random.randrange(6)
if num_of_people > 1:
num_of_people = num_of_people
print(f"\nIf you were to play with \033[34m{num_of_people} people,\033[37m the possible combinations would be: \n\n", rock_paper_scissors(
num_of_people))
print("\nThat is a total of: \033[32m" +
str(len(all_combinations)) + " combinations\n")
else:
print(
f"\n\033[31mUsage: rps.py number of players was: {num_of_people}. Must be greater than 2.\n")
|
4d3b2db61b80cb7b0027a4fda67a878050b132dc | LandersAtLambda/Sprint-Challenge--Data-Structures-Python | /ring_buffer/ring_buffer.py | 863 | 3.5 | 4 | class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.current = 0
self.storage = [None]*capacity
def append(self, item):
self.storage[self.current] = item
if self.current == len(self.storage)-1:
self.current = 0
else:
self.current += 1
def get(self):
return [i for i in self.storage if i]
# The following was for my own testing
buffer = RingBuffer(3)
print(buffer.get()) # should return []
buffer.append('a')
buffer.append('b')
buffer.append('c')
print(buffer.get()) # should return ['a', 'b', 'c']
# 'd' overwrites the) oldest value in the ring buffer, which is 'a'
buffer.append('d')
print(buffer.get()) # should return ['d', 'b', 'c']
buffer.append('e')
buffer.append('f')
print(buffer.get()) # should return ['d', 'e', 'f']
|
ee94ba8cde5e3529ce36f88a4be45dacf89805f8 | MonikaJayakumar-nj/TICTACTOE | /main.py | 3,779 | 4.0625 | 4 | # This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
# -----Global Variables-----
# play_game
# display_board
# handle_turn
# check_game_still_going
# Flip_player
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
winner = None
game_still_goes = True
current_player = "X"
def play_game():
display_board()
while game_still_goes:
handle_turn(current_player)
check_game_over()
flip_player()
if winner == "X" or winner == "O":
print(winner + " Won.")
elif winner == None:
print("Tie.")
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
print("\n")
def handle_turn(player):
print(player + "'s turn.")
position = input("Enter the position from 1-9: ")
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Invalid Input. Enter a position from 1-9: ")
position = int(position) - 1
if board[position] == "-":
valid = True
else:
print("You can't go there. Go again")
board[position] = player
display_board()
def check_game_over():
check_for_win()
check_for_tie()
def check_for_win():
global winner
# check_row
row_winner = check_rows()
# check_columns
column_winner = check_columns()
# check_diagonal
diagonal_winner = check_diagonal()
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
def check_rows():
global game_still_goes
row1 = board[0] == board[1] == board[2] != "-"
row2 = board[3] == board[4] == board[5] != "-"
row3 = board[6] == board[7] == board[8] != "-"
if row1 or row2 or row3:
game_still_goes = False
if row1:
return board[0]
elif row2:
return board[3]
elif row3:
return board[6]
else:
return None
def check_columns():
global game_still_goes
column1 = board[0] == board[3] == board[6] != "-"
column2 = board[1] == board[4] == board[7] != "-"
column3 = board[2] == board[5] == board[8] != "-"
if column1 or column2 or column3:
game_still_goes = False
if column1:
return board[0]
elif column2:
return board[1]
elif column3:
return board[2]
else:
return None
def check_diagonal():
global game_still_goes
diagonal1 = board[0] == board[4] == board[8] != "-"
diagonal2 = board[2] == board[4] == board[6] != "-"
if diagonal1 or diagonal2:
game_still_goes = False
if diagonal1:
return board[0]
elif diagonal2:
return board[2]
else:
return None
def check_for_tie():
global game_still_goes
if "-" not in board:
game_still_goes = False
return True
else:
return False
def flip_player():
global current_player
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
play_game()
|
af8cae1d855a8cb9d4edd5196658cf448dc96da0 | kuronori/self_taught | /ch22 | 1,919 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 12:40:06 2020
@author: TakahiroKurokawa
"""
#FizzBuzz
def FizzBuzz():
for i in range(1,101):
if (i%3==0) & (i%5==0):
print("FizzBuzz")
elif i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
else:
print(i)
a=FizzBuzz()
import random
def linear_search(to_match):
cards=[]
for i in range(1,101):
cards+=[i]
random.shuffle(cards)
index=1
while len(cards)>0:
a=cards.pop()
if a==to_match:
print("{0} is in index{1}".format(to_match,index))
break
else:
print(a)
index+=1
a=linear_search(50)
def rotating_sentence(string):
string_to_list=list(string)
while len(string_to_list)>1:
initial=string_to_list.pop(0)
end=string_to_list.pop()
if initial != end:
return False
break
else:
return True
a=rotating_sentence("BaB")
def palindrom(string):
string=string.lower()
return string[::-1]==string
b=palindrom("aba")
def anaglam(string1,string2):
string1=string1.lower()
string2=string2.lower()
return sorted(string1)==sorted(string2)
c=anaglam("anaglam","nagmaal")
from collections import defaultdict
def count_letter(string):
dic=defaultdict(int)
string=string.lower()
string=string.replace(" ","")
for letter in string:
dic[letter]+=1
return dic
a=count_letter("Noriaki Kurokawa")
def bottles_of_beer(bob):
if bob<1:
print("No more bottles")
return
tmp=bob
bob-=1
print("""
{} bottles of beer on the wall.
{} bottles of beer.
Take one down,pass it around,
{} bottles of beer on the wall.
""".format(tmp,tmp,bob))
bottles_of_beer(bob)
a=bottles_of_beer(99) |
ae521e01fed4ce8af959aed4797403e0e72b57b1 | kuronori/self_taught | /ch14 | 909 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 14:49:56 2020
@author: TakahiroKurokawa
"""
class Shape:
def __init__(self):
pass
def what_am_i(self):
return "I am a shape"
class Square(Shape):
square_list=[]
def __init__(self,l):
self.name="Square"
self.l=l
self.square_list.append(self)
def calculate_perimeter(self):
return self.l*4
def __repr__(self):
return self.name
def change_size(self,x):
if self.l+x<0:
print("Alert:lenght minus value")
else:
self.l=self.l+x
def __repr__(self):
return "{} by {} by {} by {}".format(self.l,self.l,self.l,self.l)
Squ1=Square(1)
print(Squ1)
def get_two_para(p1,p2):
if p1 is p2:
return True
else:
return False
Squ1=Square(10)
Squ2=Square(5)
a=get_two_para(Squ1,Squ2)
|
e180bf719676bc8d11fd7c0c26096f59a9752f00 | abankalarm/Data-structures-in-cplusplus | /array/1 unsorted array.py | 210 | 3.609375 | 4 | def findelement(arr, n,key):
for i in range (n):
if (arr[i])==key:
return i+1
else:
continue
arr = [1,2,4,2,3,1,5,6,3,1]
n = len(arr)
print(findelement(arr, n , 5))
|
e1c4f9c2034a1fa3f8f4535e68f394af0e6f2d7d | paulo-sk/python-crash-course-2019 | /c6_dictionaries/loop_dictionaries.py | 943 | 4.3125 | 4 | """
vc pode dar loop em dicionarios de 3 formas:
loop nas keys:
loop nos values:
loop nos key , values:
"""
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
# loop nas keys;
for name in favorite_languages.keys():
print(name.title())
# loop nos values:
for languages in favorite_languages.values():
print(languages.title())
# loop key, values:
for name,language in favorite_languages.items():
print(f"Name:{name},language:{language}")
# loop de forma ordenada (essa esta em ordem alfabetica)
for name in sorted(favorite_languages.keys()):
print(name.title())
# verificando e imprimindo valores nao repetidos com metodo set()
# perceba que no dicionario, o valor python aparece 2 vezes, com o set so vai mostrar valores unicos
print("\nLiguagens de programaçao mencionadas:")
for language in set(favorite_languages.values()):
print(language) |
a5dcfbb508c112b3184f4c65c0425573b4c2c043 | paulo-sk/python-crash-course-2019 | /c10_files_and_exceptions/exceptions/division_calculator.py | 805 | 4.28125 | 4 | # programa tenta fazer o que vc quer, se nao de, ele manda uma mensagem de erro mais amigavel
# e o programa continua rodando
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero.")
print("\n-------------------------------------------------------")
# outro exemplo
print("\nGive me 2 numbers, and i'll divide them:")
print("Enter 'q' to quit.\n")
while True:
first_number = input("Enter the first number> ")
if first_number == 'q':
break
second_number = input("Enter the second number> ")
if second_number == 'q':
break
# try-except-else block
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"answer: {answer}")
|
ba97749fa33b5684395bb4be576c96ea0760725e | paulo-sk/python-crash-course-2019 | /c8_funcoes/passando_lista.py | 1,367 | 3.546875 | 4 | def greet_users(names):
for name in names:
msg = f"hello {name.title()}, you wellcome"
print(msg)
user_names = ['apk','shiit','crep','big mak']
greet_users(user_names)
# mdelos de pintura
modelos_nao_finalizados = ['a','b','c','d','e']
modelos_finalizados = []
while modelos_nao_finalizados:
modelo_feito = modelos_nao_finalizados.pop()
print(f"Printing model: {modelo_feito}")
modelos_finalizados.append(modelo_feito)
print(f"\nTodos os modelos prontos: ")
for modelo_pronto in modelos_finalizados:
print(modelo_pronto)
print("---------------------------------------------")
print("\n\nMostrado modelos usando funcoes:")
# modelos usando funcoes
modelos_nao_finalizados2 = ['a','b','c','d','e']
modelos_finalizados2 = []
def print_modelos(modelos_finalizados2,modelos_nao_finalizados2):
while modelos_nao_finalizados2:
modelo_feito = modelos_nao_finalizados2.pop()
print(f"Printing model: {modelo_feito}")
modelos_finalizados2.append(modelo_feito)
def show_completed_models(modelos_finalizados2):
for modelo_pronto in modelos_finalizados2:
print(modelo_pronto)
print("\nPrintado modelos")
print_modelos(modelos_finalizados2,modelos_nao_finalizados2)
print("\nMostrando modelos finalizados")
show_completed_models(modelos_finalizados2)
# para copiar uma lista ------> list_name[:] |
0ecf99a10390cf56feed039f8d0c55ed502d66ef | paulo-sk/python-crash-course-2019 | /c9_classes/try_it_yourself/4_number_serverd.py | 1,173 | 3.921875 | 4 | class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name = restaurant_name
self.cuisine = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f"Restaurant name: {self.name}")
print(f"Restaurant cuisine type: {self.cuisine}")
def open_restaurant(self):
print("Restaurante is now open!")
def read_number_served(self):
print(f"The number os costumers served is {self.number_served}")
def set_number_served(self,number):
self.number_served = number
def increment_number_serverd(self,increment):
self.number_served += increment
my_restaurant = Restaurant('Dope','colombiana')
my_restaurant.read_number_served()
# mudando o valor de number_serverd diretamente na propriedade
my_restaurant.number_served = 2
my_restaurant.read_number_served()
# mudando o valor de number_served atraves de um metodo
my_restaurant.set_number_served(4)
my_restaurant.read_number_served()
# aumentado (somando) o valor de number served atraves de um metodo
my_restaurant.increment_number_serverd(3)
my_restaurant.read_number_served() |
533f6cf00c60770635346c9ab60eb3100c8cbfcd | michal12334/python-snake | /main.py | 1,180 | 3.515625 | 4 | import pygame
from window import *
from snake import *
from apple import *
pygame.font.init()
def showYouLost(window):
font = pygame.font.SysFont("comicsans", 60)
text = font.render("You lost", 1, (255, 255, 255))
window.blit(text, (420, 200))
def main():
window = Window(900, 900)
window.setTitle("Snake")
window.setFrameRateLimit(60)
isOpen = True
snake = Snake()
apple = Apple()
isDead = False
counter = 0
counterMax = 3 * 60
while isOpen:
for event in pygame.event.get():
if event.type == pygame.QUIT:
isOpen = False
if snake.isAppleEaten(apple.getPosition()):
apple.setPosition(snake.generateNewPositionForApple())
snake.addNewPart()
snake.update()
window.clear()
if not isDead:
window.draw(snake)
window.draw(apple)
isDead = snake.isDead()
else:
counter += 1
if counter >= counterMax:
isOpen = False
showYouLost(window.getPygameSurface())
window.display()
main() |
cf641a406a6d1cbca03458e55b32d8d64b3a523f | adityad30/Strings-2 | /97FindAnagrams.py | 1,434 | 3.5625 | 4 | """
// Time Complexity :T = O(M) + O(N)
// Space Complexity :O(n)
// Did this code successfully run on Leetcode : YES
// Any problem you faced while coding this : NA
add all the pattern characters in hashmap with default value 1
in character -> reduce its count in hashmap; if the cout is 0, increase match
out character -> increase its count by 1 in hashmap; if count in hashmap == 1,decrease match
if match == len(hashmap) it means anagram is found, add index
"""
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
hashMap = {}
result = []
match = 0
for i in range(len(p)):
hashMap[p[i]] =hashMap.get(p[i],0)+ 1
for i in range(len(s)):
"""
in character
"""
inchar = s[i]
if inchar in hashMap:
cnt = hashMap.get(inchar) - 1
if cnt == 0: match += 1
hashMap[inchar] = cnt
"""
out char
"""
if i > len(p)-1:
outchar = s[i - len(p)]
if outchar in hashMap:
cnt = hashMap.get(outchar) + 1
if cnt == 1: match -= 1
hashMap[outchar] = cnt
if match == len(hashMap):
index = i - len(p) + 1
result.append(index)
return (result)
|
591983d40b7c967e5173cc5cff2693d2bd61d397 | icofalc/critto-scripts | /modulo.py | 272 | 4 | 4 |
def modulo(numero,modulo):
risultato = numero % modulo
return risultato
while 1:
num=input("dammi il numero :")
num=int(num)
mod=input("dammi il modulo :")
mod=int(mod)
ris=modulo(num,mod)
print("viene "+str(ris))
|
9c49ab889ce786a73f22841b04941d53cd76db22 | OpenSource-Programming/PythonTraining012021 | /melanierosson_py_regex_012721.py | 1,119 | 3.921875 | 4 | # importing re
import re
# opening file
filename = 'regex_sum_1136998.txt'
filetxt = open(filename)
# declarations
regex = '[0-9]+'
sumInts = 0
countInts = 0
integers = []
newIntList = []
newIntItemStr = ''
# stripping whitespace and finding integers in each line of the file
for line in filetxt :
line = line.rstrip()
integers.append(re.findall(regex, line))
# removing empty list items in the file line lists (lines that had no integers)
onlyInts = [listItems for listItems in integers if listItems]
# stringifying everything (there are currently list items within the larger list)
for eachItem in onlyInts :
for insideEach in eachItem :
newIntItemStr = newIntItemStr + ' ' + insideEach
newIntList = newIntItemStr
# splitting separate items into a single list based on spaces
numList = newIntList.split()
# getting final numbers from final integer list
for numItems in numList :
# list item count
countInts += 1
# list items sum
sumInts += int(numItems)
print('The total integer count is ' + str(countInts))
print('The sum of all integers is ' + str(sumInts))
|
8aebc7b45a1bb15fff8574d8cc5c8efc9c099480 | OpenSource-Programming/PythonTraining012021 | /Mo/RegularExpressions/mopen_py_readdnumbers_012021.py | 579 | 4 | 4 | # Exercise 2: Write a program to look for lines of the form
# `New Revision: 39772`
# and extract the number from each of the lines using a regular expression and
# the findall() method. Compute the average of the numbers and print out the
# average.
# Enter file:mbox.txt
# 38549.7949721
# Enter file:mbox-short.txt
# 39756.9259259
import re
filename = input("Enter file: ")
fhand = open(filename, 'r')
nums = []
for line in fhand:
match = re.search("group\s(\d+)", line)
if match:
nums.append(int(match.group(1)))
print(sum(nums)/len(nums))
print(sum(nums)) |
fa2ab66b00fc188f974de5ea62a24580f6dda2ae | OpenSource-Programming/PythonTraining012021 | /frank-quoc_py_dictionaries_012021.py | 509 | 3.84375 | 4 | # Excercise 9.4
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email_count = {}
for line in handle:
line = line.rstrip()
words = line.split()
if len(words) == 0:
continue
if words[0] == "From":
email_count[words[1]] = email_count.get(words[1], 0) + 1
max_count = 0
max_email = None
for email, count in email_count.items():
if count > max_count:
max_count = count
max_email = email
print( max_email, max_count) |
33773ca76cae7fa478321fe358def9e371735fae | OpenSource-Programming/PythonTraining012021 | /frank-quoc_py_functions_012021.py | 405 | 3.96875 | 4 | # Exercise 4.6
def computepay(hours, rate):
# print("In computepay", hours, rate)
pay = hrs * rate
if hours > 40:
overtime = (hours - 40.0) * (0.5 * rate)
pay += overtime
# print("Returning", pay)
return pay
if __name__ == '__main__':
hrs = float(input("Enter Hours: "))
rate = float(input("Enter Rate: "))
p = computepay(hrs, rate)
print("Pay", p)
|
ba954b359c6eb00aa1dfef5ca761ca3bbd4fe8b2 | ajay09/CodingPractice | /DailyCodingProblem/solutions_py/problem_002.py | 647 | 3.765625 | 4 | def productExceptSelf(nums):
numsLength = len(nums)
leftProducts, rightProducts = [0]*numsLength, [0]*numsLength
leftProducts[0] = 1
for i in range(1, numsLength):
leftProducts[i] = nums[i-1] * leftProducts[i-1]
# print(leftProducts)
rightProducts[numsLength - 1] = 1
for i in reversed(range(numsLength - 1)):
rightProducts[i] = nums[i+1] * rightProducts[i+1]
# print(rightProducts)
result = [0] * numsLength
for i in range(numsLength):
result[i] = leftProducts[i] * rightProducts[i]
return result
print(productExceptSelf([3,4,5]))
print(productExceptSelf([1,2,3,4,5])) |
358484bb7344afc9513a9173bf58a299edc785fb | gohjungho/JavaBasic | /everyone Java/Conditional_Operator.py | 468 | 3.671875 | 4 | # 삼항연산자를 사용하여 (if 사용 금지)
# 1이면 1st, 2이면 2nd, 3이면 3rd, 4이면 4th
# 를 출력하는 프로그램을 작성하시오.
ord = int(input("숫자 입력: "))
crd = (
(str(ord) + "st") if (abs(ord) % 10 == 1 and abs(ord) % 100 != 11)
else (str(ord) + "nd") if (abs(ord) % 10 == 2 and abs(ord) % 100 != 12)
else (str(ord) + "rd") if (abs(ord) % 10 == 3 and abs(ord) % 100 != 13)
else str(ord) + "th"
)
print(crd) |
0ebe2bc15f1a1dc56ccd08b7929c4703ed5fa43d | blorp77/euler | /15.py | 217 | 3.828125 | 4 | def lattice(n):
a = []
for i in range(n+1):
b = []
for j in range(n+1):
if i == 0 or j == 0 :
b.append(1)
else:
b.append(a[i-1][j] + b[-1])
a.append(b)
return a
print lattice(20)[-1][-1]
|
90dd0b20355175cb4b8edfcd95f10c6c36c3d080 | blorp77/euler | /6.py | 181 | 3.859375 | 4 | def sum_of_square(n):
total = 0
for i in range(n+1):
total += (i**2)
return total
def square_of_sum(n):
return (n*(n+1)/2)**2
print square_of_sum(100) - sum_of_square(100) |
245c2c588ac9c0b98e1d95a382091d65267eff94 | blorp77/euler | /1.py | 62 | 3.75 | 4 | a=0
for i in range(1000):
if i%3==0 or i%5==0:
a+=i
print a |
a42c623f85185a96f21af3f780fb1e229679d126 | deltonmyalil/HeartDiseasePrediction | /HeartDiseasePrediction/HeartDiseasePrediction.py | 14,014 | 3.59375 | 4 | # Heart attack for dummies
# https://www.kaggle.com/ronitf/heart-disease-uci
'''
Creators of the Dataset:
1. Hungarian Institute of Cardiology. Budapest: Andras Janosi, M.D.
2. University Hospital, Zurich, Switzerland: William Steinbrunn, M.D.
3. University Hospital, Basel, Switzerland: Matthias Pfisterer, M.D.
4. V.A. Medical Center, Long Beach and Cleveland Clinic Foundation: Robert Detrano, M.D., Ph.D.
Donor: David W. Aha (aha '@' ics.uci.edu) (714) 856-8779
'''
# Well Here we go
# Reading the data
import pandas as pd
data = pd.read_csv("heart.csv")
# Well, it looks like the heart disease guys are grouped together and the fit guys are grouped together
# I need to see if train_test_split separates them
data.info
data.info()
# Oh wow, info() and info are not the same thing, my childhood was a lie
data.describe()
# No missing values - heart attack averted
data.dtypes.value_counts()
# 13 integer features (includes the target)
# 1 float feature called oldpeak
# Whats in the head??
data.head()
# Checking for missing values
data.isnull().sum() # Glad to see all zeroes
data.isnull().any()
'''
# Doing Exploratory (Obligatory) Data Analysis
# Univariate
import seaborn as sns
import matplotlib.pyplot as plt
# Target variable
# sns.countplot(data['target']) # This will also give the same graph,
sns.countplot(x=data['target'].value_counts()) # but value_counts() will just count the value first - easy on memory
# Age
# plt.hist(data['age'])
sns.countplot(data['age']) # I'm starting to like seaborn more - me likey
# Most of the people are in their 60s, I dont intend to cross 50 anyway
# Age in bins
#data['age_bin'] = pd.cut(data.age,[29,30,35,40,45,50,55,60],labels=[30,35,40,45,50,55,60])
# Sex
plt.hist(data['sex'], bins=2) # 0 is female, 1 is male
sns.countplot(data['sex']) # This is better,
# More data from males
'''
# No null values in any columns
allColumns = data.columns.values.tolist()
numColumns = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
catColumns = [col for col in allColumns if col not in numColumns]
# In notebook, print both
# Checking for duplicate values
data[data.duplicated() == True]
# patient no 164 is duplicate
# Removing the duplicate record
data.drop_duplicates(inplace=True)
# Now checking
data[data.duplicated() == True]
# Now it returned none
# Exploratory Data Analysis
# Univariate analysis
import seaborn as sns
import matplotlib.pyplot as plt
# Target variable
# sns.countplot(data['target']) # This will also give the same graph,
plt.style.use('ggplot')
sns.set_style('whitegrid')
# Target Variable
sns.countplot(x=data['target']) # but value_counts() will just count the value first - easy on memory
# Sex
sns.countplot(data['sex'])
# Age distribution
pd.DataFrame(data['age'].describe())
data['ageBin'] = pd.cut(x=data.age, bins=[0, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80], labels=[30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80])
'''
(0, 30] -- 1
(30, 35] -- 6
etc
'''
# Here, a new col is created
# If the age is <30, the col value for that record will be 30
# Personal Note: This will be a good function to use in monte carlo simulation
print(pd.DataFrame(data['ageBin'].value_counts()))
# Visualizing the above result in sns
sns.countplot(data['ageBin'])
# Sex distribution
pd.DataFrame(data['sex'].value_counts())
sns.countplot(data['sex'])
# CP: Chest Pain type
pd.DataFrame(data['cp'].value_counts())
sns.countplot(data['cp'])
# I'm no doctor, but I guess it is nominal 4 valued categorical from the dataset documentation
# Value 1: typical angina -- Value 2: atypical angina -- Value 3: non-anginal pain -- Value 4: asymptomatic
# In dataset, value starts from 0
# Cholestrol
pd.DataFrame(data['chol'].describe())
# Min is 126(Vegan for sure), max is 564(Holy Crap, I would like his diet)
# Lets sort these into bins
'''
(125, 150],
(150, 200],
...,
(550, 600]
'''
print(range(125, 601, 50))
mylist = list(range(150, 601, 50))
mylist.append(125)
mylist.sort()
mylist
data['cholBin'] = pd.cut(data.chol, bins=mylist, labels=list(range(150, 601, 50)))
pd.DataFrame(data['cholBin'].value_counts())
sns.countplot(data['cholBin'])
# trestbps
# It is the resting blood pressure on admission at the hospital
# Numerical Value
data['trestbps'].describe() # This also works
# data.trestbps.describe() # This also works
# Min is 84 mm Hg, max is 200 mm Hg (The nurse who took his BP might be hot)
data['trestbpsBin'] = pd.cut(data.trestbps, bins=[93, 110, 120, 130, 140, 150, 160, 205], labels=[110, 120, 130, 140, 150, 160, 205])
data['trestbpsBin'].value_counts()
sns.countplot(data.trestbpsBin) # This also works
# sns.countplot(data['trestbpsBin'])
# FBS
# Will be 1 if the fasting blood sugar is higher than the normal 120 mg/dl
data.fbs.unique()
# Two values = 1 and 0
sns.countplot(data.fbs)
# restecg
# Resting ECG results
data.restecg.unique()
# We get three values
# restecg: resting electrocardiographic results -- Value 0: normal -- Value 1: having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV) -- Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria 20
# What I understood is 0 is normal, 1 is pretty bad and 2 is fucked up
# Therefore ordinal categorical
sns.countplot(data.restecg)
# thalach
# Maximum heart rate achieved
data.thalach.unique()
# Integer numerical value
data.thalach.describe()
# min is 71
# max is 202
data['thalachBin'] = pd.cut(data.thalach, bins=[70, 90, 110, 130, 150, 170, 180, 200, 203], labels=[90, 110, 130, 150, 170, 180, 200, 203])
data.thalachBin.value_counts()
sns.countplot(data.thalachBin) # Is that a normal distributioin I see?
# exang
# Exercise included?
# 1 is Yes, 0 is No
sns.countplot(data.exang)
# oldpeak
# ST depression induced due to exercise relative to rest
# ST means something Thoracic - some chest measure as I remember from data's doc and paper
data.oldpeak.describe()
# min is 0, max is 6.2
# float value
# sns.countplot(data.oldpeak) # isnt working well, need to discretize this
data['oldpeakBin'] = pd.cut(data.oldpeak,
bins=[-0.1, 0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 6.5],
labels=[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 6.5])
sns.countplot(data.oldpeakBin)
# Slope
# the slope of the peak exercise ST segment -- Value 1: upsloping -- Value 2: flat -- Value 3: downsloping
# I'm guessing ordinal categorical
sns.countplot(data.slope)
# ca
# number of major vessels (0-3) colored by flourosopy
data.ca.unique()
sns.countplot(data.ca)
# thal
# thal: 3 = normal; 6 = fixed defect; 7 = reversable defect
data.thal.unique()
sns.countplot(data.thal)
# I cant find this in the data's doc, I dont know whether to take it as ordinal or nominal
# And thus the univariate analysis is complete
# Multivariate Analysis
# Age with respect to heart disease
target1 = data[data['target']==1]['ageBin'].value_counts()
target0 = data[data['target']==0]['ageBin'].value_counts()
temp = pd.DataFrame([target0, target1])
temp.index = ['Healthy', 'Disease']
temp.plot(kind='bar', stacked=True)
# Sex with respect to heart disease
target1 = data[data['target']==1]['sex'].value_counts()
target0 = data[data['target']==0]['sex'].value_counts()
tempDf = pd.DataFrame([target0, target1])
tempDf.index = ['Healthy', 'Disease']
tempDf.plot(kind='bar', stacked=True)
# Relationship between age and trestbps
data.plot(kind='scatter', x='age', y='trestbps', color='green', alpha=0.5)
# More people will have higher blood pressure as they age
# Relationship between age and maximum heartrate acheived
data.plot(kind='scatter', x='age', y='thalach', color='blue', alpha=0.5)
# As you age, the maximum heart rate you can achieve will gradually reduce
# Relationships between age, cholestrol, ca and oldpeak
sns.pairplot(data.loc[:, ['age', 'chol', 'ca', 'oldpeak']])
# Correlation Matrix
dataCorr = data.corr()['target'][:-1] # Last row is the target
# Now take the most correlated features
goldFeaturesList = dataCorr[abs(dataCorr) > 0.1].sort_values()
# So the strongly correlated features with the target are
goldFeaturesList
# Drawing the correlation matrix
corr = data.corr()
plt.figure(figsize=(12, 12))
sns.heatmap(data=corr[abs(corr) > 0.1], vmin=-1, vmax=1, cmap='summer', annot=True, cbar=True, square=True)
# Modeling
# Again importing data
data = pd.read_csv('heart.csv')
y = data['target']
X = data.drop(['target'], axis=1)
# Train-Test Split
from sklearn.model_selection import train_test_split
Xtrain, Xtest, yTrain, yTest = train_test_split(X, y, test_size=0.25, random_state=0)
# Yep, train test split will randomize (obviously, what was I thinking)
# Evaluating the results
# First, lets make a function to evaluate the results of prediction
from sklearn.metrics import confusion_matrix
# Precision = tp/(tp+fp) ie out of all predicted positive, how many actually have heartDisease
from sklearn.metrics import precision_score
# Recall = tp/(tp+fn) ie out of all heart disease patients, how many are detected by our MLalgo
from sklearn.metrics import recall_score
from sklearn.metrics import roc_curve, auc
def evaluateModel(yTrue, yPredicted, modelName):
print("=====================================================")
print("Result of prediction for the model - ", modelName)
confMatrix = confusion_matrix(yTrue, yPredicted)
print("Confusion Matrix")
print(confMatrix)
precision = round(precision_score(yTrue, yPredicted), 4)
print("Precision is ", precision)
print("Out of all predicted as Heart Patients, {} percent actually have Heart Disease".format(precision*100))
recall = round(recall_score(yTrue, yPredicted), 4)
print("Recall is ", recall)
print("Out of all actual heart patients, {0} is able to detect {1} percent of them".format(modelName, recall*100))
print("Drawing the ROC")
fpr, tpr, thresholds = roc_curve(yPredicted, yTrue)
roc_auc = round(auc(fpr, tpr), 3) # I only need three decimal places
plt.figure(figsize=(10, 6))
plt.plot(fpr, tpr, color='darkorange', lw=1, label="{0}, area={1}".format(modelName, roc_auc))
plt.plot([0, 1], [0, 1], color='blue', lw=1, linestyle='--') # Apparently this is line between (0,0) and (1,1)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel("Flase Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Receiver Operating Characteristic for {}".format(modelName))
plt.legend(loc="lower right")
plt.show()
print("=====================================================")
# Modeling
# Traditional Models
# Logistic Regression
from sklearn.linear_model import LogisticRegression
logisticRegression = LogisticRegression(random_state=0)
logisticRegression.fit(Xtrain, yTrain)
yPredLogReg = logisticRegression.predict(Xtest)
# Evaluating Logistic Regression
evaluateModel(yTest, yPredLogReg, "Logistic Regression")
# Naive Bayes
from sklearn.naive_bayes import GaussianNB
naiveBayes = GaussianNB(priors=None)
naiveBayes.fit(Xtrain, yTrain)
yPredNaiveBayes = naiveBayes.predict(Xtest)
# Evaluating Naive Bayes
evaluateModel(yTest, yPredNaiveBayes, "Naive Bayes")
# Decision Tree Classifier
from sklearn.tree import DecisionTreeClassifier
decTree = DecisionTreeClassifier(criterion='entropy', random_state=0)
decTree.fit(Xtrain, yTrain)
yPredDecTree = decTree.predict(Xtest)
# Evaluating Decision Tree
evaluateModel(yTest, yPredDecTree, "Decision Tree")
# Using Ensemble Methods
# Now let us use Bagging Methods
# Random Forest Classifier
from sklearn.ensemble import RandomForestClassifier
randForest = RandomForestClassifier(criterion='entropy', random_state=0)
randForest.fit(Xtrain, yTrain)
yPredRandForest = randForest.predict(Xtest)
# Evaluating Random Forest
evaluateModel(yTest, yPredRandForest, "Random Forest")
# Extra Trees Classifier
# Extremely Randomized Trees Classifier
# ET algorithm is quite similar to Random Forest - but splits are selected on random instead of using some criterions.
from sklearn.ensemble import ExtraTreesClassifier
extraTrees = ExtraTreesClassifier(n_estimators=10, criterion='entropy', bootstrap=False, random_state=0)
# If bootstrap is false, whole dataset is used to build the tree, if true, samples are drawn with replacement
# 10 individual decision trees running based on entropy and information gain
extraTrees.fit(Xtrain, yTrain)
yPredExtraTrees = extraTrees.predict(Xtest)
# Evaluating Extra Trees
evaluateModel(yTest, yPredExtraTrees, "Extra Trees")
# Bagging using individual logistic regression models
from sklearn.ensemble import BaggingClassifier
# Make a Logistic Regression Classifier
logRegModelToBag = LogisticRegression(random_state=0)
logRegBagging = BaggingClassifier(base_estimator=logRegModelToBag, n_estimators=10, bootstrap=True, random_state=0)
logRegBagging.fit(Xtrain, yTrain)
yPredLogRegBag = logRegBagging.predict(Xtest)
# Evaluating bagging using individual logistic regression models
evaluateModel(yTest, yPredLogRegBag, "Logreg Bagging")
# Boosting
# Gradient Boosting
from sklearn.ensemble import GradientBoostingClassifier
gradBoost = GradientBoostingClassifier(random_state=0)
gradBoost.fit(Xtrain, yTrain)
yPredGradBoost = gradBoost.predict(Xtest)
# Evaluating Gradient Boosting Classifier
evaluateModel(yTest, yPredGradBoost , "Gradient Boosting")
# Extreme Gradient Boosting
# Note: Need to install xgboost in conda
# conda install -c conda-forge xgboost
from xgboost import XGBClassifier
xgbClassifier = XGBClassifier(n_estimators=100, random_state=0)
xgbClassifier.fit(Xtrain, yTrain)
yPredXgb = xgbClassifier.predict(Xtest)
# Evaluating xg Boost
evaluateModel(yTest, yPredXgb, "XG Boost")
# AdaBoost on Decision Tree Similar to above
from sklearn.ensemble import AdaBoostClassifier
decTreeAdaBoostModel = DecisionTreeClassifier(criterion='entropy', random_state=0)
adaBoost = AdaBoostClassifier(base_estimator=decTreeAdaBoostModel, random_state=0)
adaBoost.fit(Xtrain, yTrain)
yPredAdaBoost = adaBoost.predict(Xtest)
# Evaluating Adaboost
evaluateModel(yTest, yPredAdaBoost, "AdaBoost on Decision Tree")
|
c60b92f07a23bac432242e35441cfcdad2d6dfb5 | KavinSelvarasu/Python_Beginer_projects | /dies_rolling.py | 356 | 3.953125 | 4 | # importing random number generator
import random
play = input('would you like to roll dies: ').strip().lower()
if play == 'yes':
rolls = int(input("Enter number of dies to roll: "))
def diesRoll(rolls):
for i in range(0, rolls):
dies = random.randint(1, 6)
print(dies)
diesRoll(rolls)
else:
exit()
|
87d19ef751bdb5bd5e305d8a18c634ebf08c39a8 | VladSquared/SoftUni---Programming-Basics-with-Python | /01. Problem.py | 805 | 4.125 | 4 | email = input()
while True:
cmd = input()
if cmd == "Complete":
break
elif "Make Upper" in cmd:
email = email.upper()
print(email)
elif "Make Lower" in cmd:
email = email.lower()
print(email)
elif "GetDomain" in cmd:
count = int(cmd.split()[1])
print(email[-count:])
elif "GetUsername" in cmd:
if not "@" in email:
print(f"The email {email} doesn't contain the @ symbol.")
continue
at_char = int(email.index("@"))
print(email[:at_char])
elif "Replace" in cmd:
char = cmd.split()[1]
email = email.replace(char, "-")
print(email)
elif "Encrypt" in cmd:
for char in email:
print(ord(char), end=" ")
|
8ae6cf66956ff74fc103584e9f9b4c94ec6653ef | Jacob-Bordelon/CSC_442 | /Timelock/Timelock/timelock.py | 4,632 | 3.734375 | 4 | # File: timelock.py
# Team: Johnmichael Book, Jacob Bordelon, Tyler Nelson,
# Logan Simmons, Eboni Williams, Breno Yamada Riquieri
# Version: 10.13.19
# Usage: Use python 2.7
# Example: python timelock.py < epoch.txt
# Github: https://github.com/Jacob-Bordelon/CSC_442.git
# Descr: This program
# Reads the epoch from stdin in the format YYYY MM DD HH mm SS
# Use the systems current time to calculate the elloted time of epoch and current
# and sends the calculated 4-character code to stdout.
#
# NOTE: you may need to install pytz
from datetime import datetime, timedelta
from hashlib import md5
import pytz
import sys
# This class creates an element dubbed utcTime
# upon instance, it will take a string as input, given the format 'year month day hour minute second'
# it will then create a datetime instance to convert the current time - epoch time in seconds
# if utcTime is printed, it will return the seconds elapsed since january 1 1970
# the dst function adjusts the time for day light savings time so when the time is caluculated, its accurate
class utcTime:
def __init__(self,sInput):
self.input = [int(i) for i in sInput.split(' ')] # convert the string to an array by spaces
self.utc = datetime(self.input[0],self.input[1],self.input[2],self.input[3],self.input[4],self.input[5]) # create the date time instance with the input
if self.dst() == True: # test for daylight savings time
self.utc = self.utc - timedelta(hours=1) # change if so
self.seconds = int((self.utc-datetime(1970, 1, 1)).total_seconds()) # give the seconds elapsed since the begining
# NOTE: this time thats elapsed is not the user inputed epoch time, but rather january 1 1970
# test for daylight savings time
def dst(self):
localtime = pytz.timezone('US/Central')
a = localtime.localize(self.utc)
return bool(a.dst())
# return the integer of seconds so it can be calculated
def __int__(self):
return self.seconds
# print out the elapsed seconds
def __str__(self):
return str(self.seconds)
# convert the hashed value to a 4 bit string
# of first 2 letters and last 3 digits
# NOTE: This checks for if there are no letters or numbers and will return the appropriate output
def fourBit(hashed):
# separate the values of hashed into two groups, letters(l) or digits(d)
# separate the values but maintain order
# reverse the order of the digits
d = [i for i in hashed if i.isdigit()][::-1]
l = [i for i in hashed if i.isalpha()]
# if it reads both lists are over 2 values each, then add the first two objects to the string
# this works since the d list is already reversed, so, it will be in proper order
# lastly, join all the elements together into one string
if len(d) >= 2 and len(l) >= 2:
return ''.join(l[:2]+d[:2])
elif len(d) < 2: # if only 1 or no digits exist, append what is there to the end of 3 to 4 characters of l
return ''.join(l[:4-len(d)]+d)
elif len(l) < 2:# # if only 1 or no letters exist, append what is there to the begging of 3 to 4 characters of d
return ''.join(l+d[:4-len(l)])
if __name__ == "__main__":
# Get the epoch time from stdin
epochInput = sys.stdin.read()
# get the current system time
# NOTE Change c to change the current time
#/////////////////////////////////////////////////////////
currentTime = datetime.now().strftime("%Y %m %d %H %M %S") # use for normal timelock.py
# c = open('current.txt','r').read() #use for test.py
# c = "2017 04 23 18 02 30" # use for testing
#/////////////////////////////////////////////////////////
# Create a utcTime element of both epoch and current
# this creates a datetime instance that is then converted to seconds since january 1 1970
# it will also adjust for day light savings time, since it will need to subtrace an hour to adjust for the time difference
epoch = utcTime(epochInput)
current = utcTime(currentTime)
# the elapsed time takes the current seconds in utc and
elapsed = current.seconds - epoch.seconds
# this line is md5 of an md5 of the starting time.
# NOTE: elapsed - elapsed%60 is giving the exact time at the begging of the minute rather than the end
# cause it will affect the output
hashed = md5(md5(str(elapsed-(elapsed%60)).encode()).hexdigest()).hexdigest()
# give output through stdout
sys.stdout.write(fourBit(hashed))
|
3b59d43556d9a314b59c67defc25d860bab7eb60 | Jacob-Bordelon/CSC_442 | /CYBERSTORM/XOR/xor.py | 2,471 | 3.609375 | 4 |
# File: xor.py
# Team: Johnmichael Book, Jacob Bordelon, Tyler Nelson,
# Logan Simmons, Eboni Williams, Breno Yamada Riquieri
# Version: 10.12.19
# Usage: Use python 2.7
# Example: python xor.py < ciphertext
# python xor.py < plaintext > ciphertext
# Github: https://github.com/Jacob-Bordelon/CSC_442.git
# Descr: This program reads a text file from stdin and a key in the current directory
# it will compare the binary value of the text and key, xor'ing each binary bit
# them return the xor'd data to stdout
import sys
from binascii import unhexlify, hexlify
import argparse
parser = argparse.ArgumentParser(prog='xor.py',conflict_handler="resolve")
parser.add_argument("text",metavar="text",nargs="+",help="Add name of text file")
parser.add_argument("key",metavar="key",nargs="+",help="Add name of key file")
args = parser.parse_args()
# this function takes one character as input and returns the binary equivalent as a string
def binary(byte):
return "{0:08b}".format(int(hex(ord(byte)),16))
# the toAscii function takes a string of binary bytes and converts it to character strings
# it then returns the string as a bytearray
def toAscii(byte):
b = ""
i=0
while i < len(byte):
b+=chr(int(byte[i:i+8],2))
i+=8
return bytearray(b)
# the xor program takes two binary strings as the parameters and returns the xor'd value
# the strings can be any length
def xor(t,k):
h = ""
for i in range(len(t)):
h+=str(int(t[i])^int(k[i]))
return h
# text takes either the ciphertext or plaintext as the parameter from stdin
# key must be a file in the current directory
# NOTE: use 'cp [name of key] key' to change the key you want to use
text = open(args.text[0],'rb').read() if args.text != None else sys.stdin.read()
key = open(args.key[0],'rb').read() if args.key != None else open('key','rb').read()
# convert both files from character files to binary files
# the ''.join() combines all the values of the list
# NOTE: if either the key or text file is already a binary file, just comment that like out and write k=key or t = text
t = ''.join([binary(i) for i in text])
k = ''.join([binary(i) for i in key])
#xor the two converted and joined binary strings
x = xor(t,k)
# convert the xor'd binary string to an array
a = toAscii(x)
# send the converted ascii key to standard output
sys.stdout.write(a)
|
c8e0402ed35781a249c86874ecb7072a74a0b608 | vivekc/python_excercises | /focusvision/focusvision_interview_question_1.py | 340 | 3.84375 | 4 | """
What would be the output
"""
def f(chars):
for c in chars:
yield c
for elt in f(chars):
for c in chars:
yield elt + c
g = f('cat')
print g.next() # 'c'
print g.next() # 'cc'
print g.next() # 'ca'
print g.next() # 'ct'
print g.next() #
print g.next()
print g.next()
print g.next()
print g.next()
|
bc0dcbab4f7dd94e98c2591fe4f684b164a40ec0 | sonamrana2908/pythonprograms | /DiceRolling.py | 402 | 3.765625 | 4 |
# coding: utf-8
# In[2]:
# Dice Rolling Simulator : https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/
import random
RollDice=input('Do you want to roll the dice:')
RollDice = RollDice.upper()
while(RollDice == 'YES'):
print(random.randint(1,6))
RollDice=input('Do you want to roll the dice again:')
RollDice = RollDice.upper()
|
c51b19cb920cd158bcc88b19b74f57690a243ff8 | ganpatagarwal/python-scripts | /test/string_sort.py | 516 | 3.5 | 4 | a = "heblloza"
l1= []
l2= []
for i in range(0,len(a)):
l1.append(a[i])
while(l1):
print l1
min_val = l1[0]
for j in range(0,len(l1)):
if l1[j] < min_val:
min_val = l1[j]
print min_val
l2.append(min_val)
l1.remove(min_val)
print ''.join(l2)
def sorastring(strr):
strr = [strr]
print 'first',strr
dev = []
d=''
for i in range(0, len(strr)):
print i
print strr[i]
if strr[i]<strr[i+1]:
print strr[i]
strr[i], strr[i+1] = strr[i+1], strr[i]
print 'second',strr
sorastring("banana") |
297bb287787a7389fe6b765c3dd37fb6d65a31fe | ganpatagarwal/python-scripts | /memo_fib.py | 708 | 3.546875 | 4 | import functools
def memoize(func):
cache = func.cache = {}
@functools.wraps(func)
def memoized_func(*args, **kwargs):
key = str(args) + str(kwargs)
print key
print cache
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return memoized_func
@memoize
def fib(n):
if n == 0:return 0
if n == 1:return 1
else: return fib(n-1) + fib(n-2)
print fib(10)
def memoized_fib(n, cache={}):
if n in cache:
result = cache[n]
elif n <= 2:
result = 1
cache[n] = result
else:
result = memoized_fib(n - 2) + memoized_fib(n - 1)
cache[n] = result
return result
|
cb49784d1f95205fb3152e9e3ff05f2bc585ff17 | rakeshsingh/my-euler | /euler/utils.py | 1,623 | 4.25 | 4 | #!/usr/bin/python
import math
from math import gcd
def my_gcd(a, b):
'''
returns: str
gcd for two given numbers
'''
if a == b or b == 0:
return a
elif a > b:
return gcd(a-b, b)
else:
return gcd(b-a, a)
def lcm(a, b):
''''''
return a * b // gcd(a, b)
def get_prime_factors(n):
'''
returns a list of prime factors of a number
'''
factors = []
for i in get_next_prime(1):
if n % i == 0:
factors.append(i)
if i > n:
return factors
def is_prime(n):
'''
Check whether a number is prime or not
'''
if n > 1:
if n == 2:
return True
if n % 2 == 0:
return False
for current in range(3, int(math.sqrt(n) + 1), 2):
if n % current == 0:
return False
return True
else:
return False
def get_next_prime(n):
while True:
n = n+1
if is_prime(n):
return n
def get_primes(n):
while True:
if is_prime(n):
yield n
n = n+1
def fibonacci_generator():
"""Fibonacci numbers generator"""
a, b = 1, 1
while True:
yield a
a, b = b, a + b
def fibonacci(n):
"""
Fibonacci numbers
returns: int
"""
counter = 0
for fib in fibonacci_generator():
if counter == n:
return fib
counter = counter + 1
def hello():
print('Hello World !')
if __name__ == '__main__':
for i in fibonacci_generator():
print(i)
if i > 150:
break
|
6992125aaa69d5f6163a13d434807f1239618acc | rakeshsingh/my-euler | /003_largest_prime_factor.py | 514 | 3.875 | 4 | #!/usr/bin/python
from myutil import is_prime, get_next_prime
def largest_prime_factor(n):
if n <= 2:
raise(RuntimeError('number should be greater than 2'))
else:
factor = get_next_prime(1)
while True:
if is_prime(n):
return (n)
if n % factor == 0:
n = n // factor
else:
factor = get_next_prime(factor)
return factor
if __name__ == '__main__':
print(largest_prime_factor(600851475143))
|
f2cf792150bca055c71b45ee8e46f08b3b45ee8b | Kalunge/python_challenges | /new.py | 18,879 | 4.46875 | 4 | # TASK 1
# Write a program which accepts a string as input to print "Yes" if the string is "yes", "YES" or "Yes", otherwise print "No".
# Hint: Use input () to get the persons input
# TASK2
# Implement a function that takes as input three variables,
# and returns the largest of the three. Do this
# without using the Python max () function!
# The goal of this exercise is to think about some internals that
# Python normally takes care of for us.
# TASK3
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes
# a new list of only the first and last
# elements of the given list. For practice, write this code inside a function
# TASK 4
# Ask the user for a number. Depending on whether the number is even or odd,
# print out an appropriate message to the user.
# Hint: how does an even / odd number react differently when divided by 2?
# If the number is a multiple of 4, print out a different message.
# TASK 5
# With a given tuple (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
# write a program to print the first half values in one line and
# the last half values in one line.
# sample output => 12345
# 678910
# MILESTONE TASK
# Create a class called Payroll whose major task is to calculate an individual’s Net Salary
# by getting the inputs basic salary and benefits. Create 5 different class methods which will
# calculate the payee (i.e. Tax), NHIFDeductions, NSSFDeductions, grossSalary and netSalary.
# NB: Use KRA, NHIF and NSSF values provided in the link below.
# https://www.aren.co.ke/payroll/taxrates.htm
# https://calculator.co.ke/kra-salary-income-tax-paye-calculator
# Task 6
# LIST METHODS
task_list = [23, 'Jane', ['Lesson 23', 560, {'currency' : 'KES'}], 987, (76,'John')]
# Determing type of variable in task_list using an inbuilt function
# Task 6a
# Print KES
# Task 6b
# Print 560
# Task 6c
# Use a function to determine the length of taksList
# Task 6d
# Change 987 to 789 without using an inbuilt -method or Assignment
# Task 6e
# Change the name “John” to “Jane” .
# Task 7
# Check for password length using if else conditional statements
# if less than 5 print too short
# if greater than 15 print too many characters
# if in between print login successful
# TASK8
# create a GRADING SYSTEM
# ask for students marks in five subjects
# calculate the average and grade them ABCD depending on their performance
# TASK9
# create a page to login to facebook
# have three variables for username, email and pasword
# let the user enter their username
# if true enter ask for their email email if true ask for their password
# if invald respond
# if any detail is wrong notify the user. proceed only if details are correct
# TASK 10
# BUY AIRTIME APPLICATION
# have users balance
# let them buy airtime if balance is okay
# ask them for the amount they want to spend and display their balance after transaction
# TASK 11
#ask for two numbers and print the greatest
# Task 12
# A student will not be allowed to sit in exam if his/her attendence is less than 75%.
# Take following input from user
# Number of classes held
# Number of classes attended.
# And print
# percentage of class attended
# Is student is allowed to sit in exam or not.
# TASK12 b
# 3.Modify the above question to allow student to sit if he/she has medical cause.
# Ask user if he/she has medical cause or not ( 'Y' or 'N' ) and print accordingly.
# TASK 13
# 4.A shop will give discount of 10% if the cost of purchased quantity is more than 1000.
# Ask user for quantity
# Suppose, one unit will cost 100.
# Judge and print total cost for user.
# TASK 14
# Accept two int values from the user and return their product.
# If the product is greater than 1000, then return their sum
# TASK 15
# Write a Python program to check if all dictionaries in a list are empty or not.
# Sample list : [{},{},{}]
# Return value : True
# Sample list : [{1,2},{},{}]
# Return value : False
# TASK 16
# Write a program that prints the numbers 1-100, each on a new line
# For each number that is a multiple of 3, print “Fizz” instead of the number
# For each number that is a multiple of 5, print “Buzz” instead of the number
# For each number that is a multiple of both 3 and 5, print “FizzBuzz” instead of the number
# if doesnt fall in any category print the number
# Now that you know what you need to write, you can get started!
# name = input('What is your name: ')
# TASK 17
# Abigail and Benson are playing Rock, Paper, Scissors.
# Each game is represented by an array of length 2, where the first element represents what Abigail played and the second element represents what Benson played.
# Given a sequence of games, determine who wins the most number of matches. If they tie, output "Tie".
# R stands for Rock
# P stands for Paper
# S stands for Scissors
# EXAMPLE:
# calculate_score([["R", "P"], ["R", "S"], ["S", "P"]]) ➞ "Abigail"
# Ben wins the first game (Paper beats Rock).
# Abigail wins the second game (Rock beats Scissors).
# Abigail wins the third game (Scissors beats Paper).
# Abigail wins 2/3.
# calculate_score([["R", "R"], ["S", "S"]]) ➞ "Tie"
# calculate_score([["S", "R"], ["R", "S"], ["R", "R"]]) ➞ "Tie"
# # TASK 18
# Write a Python program to count the number of even and odd numbers from a series of numbers.
# Sample numbers : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# Expected Output :
# Number of even numbers : 5
# Number of odd numbers : 4
# TASK 19
# Write a Python program that accepts a word from the user and reverse it.
# TASK20
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
# Note : Use 'continue' statement.
# Expected Output : 0 1 2 4 5
# TASK21
# Write a Python program to get the Fibonacci series between 0 to 50.
# Note : The Fibonacci Sequence is the series of numbers :
# 0, 1, 1, 2, 3, 5, 8, 13, 21, ....
# Every next number is found by adding up the two numbers before it.
# Expected Output : 1 1 2 3 5 8 13 21 34
# TASK 22
# Write a Python program which iterates the integers from 1 to 100. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
# Sample Output :
# fizzbuzz
# 1
# 2
# fizz
# 4
# buzz
# TASK 23
# Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array.
# The element value in the i-th row and j-th column of the array should be i*j.
# Note :
# i = 0,1.., m-1
# j = 0,1, n-1.
# Test Data : Rows = 3, Columns = 4
# Expected Result : [[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]]
# TASK 24
# Write a Python program that accepts a sequence of lines (blank line to terminate)
# as input and prints the lines as output (all characters in lower case).
# TASK 25
# Write a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers
# that are divisible by 5 in a comma separated sequence.
# Sample Data : 0100,0011,1010,1001,1100,1001
# Expected Output : 1010
# TASK 26
# Write a Python program that accepts a string and calculate the number of digits and letters.
# Sample Data : Python 3.2
# Expected Output :
# Letters 6
# Digits 2
# TASK 27
# Write a Python program to check the validity of password input by users.
# Validation :
# At least 1 letter between [a-z] and 1 letter between [A-Z].
# At least 1 number between [0-9].
# At least 1 character from [$#@].
# Minimum length 6 characters.
# Maximum length 16 characters.
# TASK 28
# Write a Python program to find numbers between 100 and 400 (both included) where each digit of a number is an even number.
# The numbers obtained should be printed in a comma-separated sequence
# TASK 29
# Write a Python program to print alphabet pattern 'A'.
# Expected Output:
# ***
# * *
# * *
# *****
# * *
# * *
# * *
# 29b. 'L'
# *
# *
# *
# *
# *
# *
# *****
# 29c. 'M'
# * *
# * *
# * * * *
# * * *
# * *
# * *
# * *
# 29d. 'o'
# ***
# * *
# * *
# * *
# * *
# * *
# ***
# 29e. 'P'
# ****
# * *
# * *
# ****
# *
# *
# *
# 29f. 'R'
# ****
# * *
# * *
# ****
# * *
# * *
# * *
# 29g. the following patterns
# ****
# *
# *
# ***
# *
# *
# ****
# ooooooooooooooooo
# ooooooooooooooooo
# ooooooooooooooooo
# oooo
# oooo
# oooo
# ooooooooooooooooo
# ooooooooooooooooo
# ooooooooooooooooo
# oooo
# oooo
# oooo
# ooooooooooooooooo
# ooooooooooooooooo
# ooooooooooooooooo
# *****
# *
# *
# *
# *
# *
# *
# * *
# * *
# * *
# * *
# * *
# * *
# ***
# * *
# * *
# * *
# *
# * *
# * *
# * *
# *******
# *
# *
# *
# *
# *
# *******
# TASK 30
# Write a Python program to calculate a dog's age in dog's years.
# Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years.
# Expected Output:
# Input a dog's age in human years: 15
# The dog's age in dog's years is 73
# Task 31
# Write a Python program to check whether an alphabet is a vowel or consonant.
# Expected Output:
# Input a letter of the alphabet: k
# k is a consonant.
# TASK 32
# Write a Python program to convert month name to a number of days.
# Expected Output:
# List of months: January, February, March, April, May, June, July, August
# , September, October, November, December
# Input the name of Month: February
# No. of days: 28/29 days
# TASK 33
# Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
# TASK 34
# Write a Python program to check a string represent an integer or not.
# Expected Output:
# Input a string: Python
# The string is not an integer.
# TASK 35.
Write a Python program to check a triangle is equilateral, isosceles or scalene.
# Note :
# An equilateral triangle is a triangle in which all three sides are equal.
# A scalene triangle is a triangle that has three unequal sides.
# An isosceles triangle is a triangle with (at least) two equal sides.
# Expected Output:
# Input lengths of the triangle sides:
# x: 6
# y: 8
# z: 12
# Scalene triangle
# TASK 36
# Write a Python program that reads two integers representing a month and day and prints the season for that month and day
# Expected Output:
# Input the month (e.g. January, February etc.): july
# Input the day: 31
# Season is autumn
# TASK 37.
# Write a Python program to display astrological sign for given date of birth.
# Expected Output:
# Input birthday: 15
# Input month of birth (e.g. march, july etc): may
# Your Astrological sign is : Taurus
# TASK 38.
# Write a Python program to display the sign of the Chinese Zodiac for given year in which you were born. Go to the editor
# Expected Output:
# Input your birth year: 1973
# Your Zodiac sign : Ox
# TASK 39.
# Write a Python program to find the median of three values. Go to the editor
# Expected Output:
# Input first number: 15
# Input second number: 26
# Input third number: 29
# The median is 26.0
# TASK 40.
# Write a Python program to get next day of a given date.
# Expected Output:
# Input a year: 2016
# Input a month [1-12]: 08
# Input a day [1-31]: 23
# The next date is [yyyy-mm-dd] 2016-8-24
# TASK 41.
# Write a Python program to calculate the sum and average of n integer numbers (input from the user). Input 0 to finish.
# TASK 42.
# Write a Python program to create the multiplication table (from 1 to 10) of a number.
# Expected Output:
# Input a number: 6
# 6 x 1 = 6
# 6 x 2 = 12
# 6 x 3 = 18
# 6 x 4 = 24
# 6 x 5 = 30
# 6 x 6 = 36
# 6 x 7 = 42
# 6 x 8 = 48
# 6 x 9 = 54
# 6 x 10 = 60
# TASK 43.
# Write a Python program to construct the following pattern, using a nested loop number.
# Expected Output:
# 1
# 22
# 333
# 4444
# 55555
# 666666
# 7777777
# 88888888
# 999999999 |
e29926d522ce32f376f349263cae0043ae37885c | fredmeews/adventofcode | /2020/19/bin.py | 241 | 3.59375 | 4 | with open('testinputMatches2-bin.txt') as f:
for line in f.readlines():
line = line.strip()
if line and not line[0] == "#":
print("{} ==> {}".format(line, int(line, 2)))
else:
print(line)
|
4461774ea09b7a388f925fb65395c288cadd70e4 | CourchesneA/ProjectEuler | /Euler17.py | 2,183 | 3.765625 | 4 | import sys
import math
sys.setrecursionlimit(1200)
def test(x):
print("test function")
return
def printNumbers(num):
if (num == 0 ):
return 0 #Base case
if (num == 1000):
print("onethousand "+str(len("onethousand")))
return len("onethousand")+printNumbers(num-1)
hundred = 0
tens = 0
units = 0
if (num > 99):
hundred = int(math.floor(num/100))
if (num > 9):
tens = int(math.floor(num/10) % 10 )
units = int( num % 10 )
# Independent digits sets, start print code
# Handling less than 100 in the next 2 blocks
if (tens < 2): #get special syntax
val = int(str(tens)+str(units)) #get value of 2 last digits
s = smallToString(val)
else:
s = tensToString(tens)+unitsToString(units)
#Handling hundreds
if(hundred != 0):
hval = unitsToString(hundred)
if(tens == 0 and units == 0):
s = hval+"hundred"
else:
s =hval+"hundred"+"and"+s
print(s) + " " + str(len(s))
return len(s)+printNumbers(num-1)
def smallToString(num):
if(num < 0 or num > 19):
raise ValueError(str(num)+': Not a little number')
return {
0:'',
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',
10:'ten',
11:'eleven',
12:'twelve',
13:'thirteen',
14:'fourteen',
15:'fifteen',
16:'sixteen',
17:'seventeen',
18:'eighteen',
19:'nineteen'
}[num]
def tensToString(tens):
if(tens < 0 or tens > 9 ):
raise ValueError(str(ten)+'is not one digit')
elif(tens == 1):
raise ValueError("Use special syntax for tens value of 1")
return {
2:'twenty',
3:'thirty',
4:'forty',
5:'fifty',
6:'sixty',
7:'seventy',
8:'eighty',
9:'ninety'
}[tens]
def unitsToString(units):
if(units < 0 or units > 9):
raise ValueError(str(units)+ 'is not one digit')
return smallToString(units)
print("Answer: "+str(printNumbers(1000)))
|
17623ff0c97ec66377b72c821874dee2ac15ff1d | xxiang13/python | /stack_reverse_char_in_string.py | 587 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 13
@author: Xiang Li
IDE: Spyder Python 3.4
"""
from data_structures import Stack
def revstring(mystr):
"""
:type mystr: string
:rtype: string
use Stack Last In First Out feature to reverse a string
"""
aStack = Stack()
for i in list(mystr):
aStack.push(i)
revstr = ''
while not aStack.isEmpty():
revstr += aStack.pop()
return revstr
#%%test
print(revstring('apple'))
print(revstring('x'))
print(revstring('1234567890'))
print(revstring('desserts'))
|
b7f3c312114f3068500221b4b93ef03166717394 | xxiang13/python | /find_alphabet_sub.py | 1,079 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 14:04:06 2015
@author: Shawn Li
IDE: Spyder python 3.4
"""
def findAlphabetSub(s):
'''Find longest alphabet substrings
Argus:
String: string with all lower cases
Return:
String: substring
'''
charList = list(s)
alphabetSubMax = []
i = 0
while i < len(charList):
alphabetSub = []
find = False
while not find and i < len(charList):
if i != len(charList)-1:
if charList[i] <= charList[i+1]:
alphabetSub.append(charList[i])
i += 1
else:
find = True
alphabetSub.append(charList[i])
else:
alphabetSub.append(charList[i])
find = True
if len(alphabetSub) > len(alphabetSubMax):
alphabetSubMax = alphabetSub
i += 1
return str(''.join(alphabetSubMax))
#%%Test findAlphabetSub
s = 'rlkxqobqnty'
findAlphabetSub(s) |
860788ccf0cfc0a5a878822fbf5f3e0a28abb8d2 | JamesHullCS/CodeWars-Solutions | /CodeWars/Python/Hex to Decimal.py | 187 | 3.5 | 4 | # https://www.codewars.com/kata/57a4d500e298a7952100035d/train/python
# Original Solution
def hex_to_dec(s):
# we use 16 as it's the base for hex as a base
return int(s, 16) |
0aa9f9f1e42b930b26c9cc96dad4d954c35ebe0b | zhipingx/EECS349_MachineLearning | /hw4_collaborative filtering_&_params_experiment/item_cf.py | 2,726 | 3.5625 | 4 | Starter code for item-based collaborative filtering
# Complete the function item_based_cf below. Do not change its name, arguments and return variables.
# Do not change main() function,
# import modules you need here.
import sys
import numpy as np
from loader import *
from helper import *
def item_based_cf(datafile, userid, movieid, distance, k, iFlag, numOfUsers, numOfItems):
'''
build item-based collaborative filter that predicts the rating
of a user for a movie.
This function returns the predicted rating and its actual rating.
Parameters
----------
<datafile> - a fully specified path to a file formatted like the MovieLens100K data file u.data
<userid> - a userId in the MovieLens100K data
<movieid> - a movieID in the MovieLens 100K data set
<distance> - a Boolean. If set to 0, use Pearson's correlation as the distance measure. If 1, use Manhattan distance.
<k> - The number of nearest neighbors to consider
<iFlag> - A Boolean value. If set to 0 for user-based collaborative filtering,
only users that have actual (ie non-0) ratings for the movie are considered in your top K.
For item-based, use only movies that have actual ratings by the user in your top K.
If set to 1, simply use the top K regardless of whether the top K contain actual or filled-in ratings.
returns
-------
trueRating: <userid>'s actual rating for <movieid>
predictedRating: <userid>'s rating predicted by collaborative filter for <movieid>
AUTHOR: Zhiping Xiu
'''
# re.sub(r'(\d+)')
# Please Check out:
# manhattanDistance(), pearsonrDistance() and kNNRating()
# at
# helper.py
#
# because those three functions are identical for both item-based and user-based KNN
# Switch userid and movieid, then transpose the matrix
# that's the only change need to do to switch to item based KNN
matrix = read(datafile).transpose()
# print userid, movieid
predictedRating = kNNRating(movieid, userid, matrix, distance, k, iFlag)
trueRating = matrix[movieid][userid]
return trueRating, predictedRating
# python item_cf.py 'ml-100k/u.data' 196 242 0 10 0
def main():
datafile = sys.argv[1]
userid = int(sys.argv[2])
movieid = int(sys.argv[3])
distance = int(sys.argv[4])
k = int(sys.argv[5])
i = int(sys.argv[6])
numOfUsers = 943
numOfItems = 1682
trueRating, predictedRating = item_based_cf(datafile, userid, movieid, distance, k, i, numOfUsers, numOfItems)
print 'userID:{} movieID:{} trueRating:{} predictedRating:{} distance:{} K:{} I:{}'\
.format(userid, movieid, trueRating, predictedRating, distance, k, i)
if __name__ == "__main__":
main()
|
be54e71d297bcc85988b424e62e329f24d8f4583 | boonth/scripts | /image_diff.py | 1,961 | 3.90625 | 4 | # compare two images. create a third image showing the difference between the
# two. in the diff image, black pixels means same color, and white pixels means
# different colors. can also optionally output a text file listing all the
# different pixels.
import Image
import sys
def diff(input1, input2, output, output_text):
im1 = Image.open(input1)
im2 = Image.open(input2)
im = Image.new('RGB', im1.size)
if output_text is not None:
f = open(output_text, 'w')
max_diff = 0
count = 0
for x in range(im1.size[0]):
for y in range(im2.size[1]):
p1 = im2.getpixel((x, y))
p2 = im1.getpixel((x, y))
if p1 != p2:
im.putpixel((x, y), (255, 255, 255))
count += 1
difference = 0
for i in range(3):
difference += abs(p1[i] - p2[i])
max_diff = max(difference, max_diff)
if output_text is not None:
f.write('-'*70 + '\n')
f.write('p1: %i %i %i %i\n' %
(p1[0], p1[1], p1[2], difference))
f.write('p2: %i %i %i %i\n' %
(p2[0], p2[1], p2[2], difference))
f.write('-'*70 + '\n')
else:
im.putpixel((x, y), (0, 0, 0))
im.save(output)
print 'done! -- output written to', output
print count, 'pixels are different'
print 'max difference is:', max_diff
if output_text is not None:
f.close()
print 'output text written to:', output_text
if __name__ == '__main__':
if len(sys.argv) < 4:
print 'usage: <input1> <input2> <output> [output_text]'
else:
if len(sys.argv) == 4:
diff(sys.argv[1], sys.argv[2], sys.argv[3], None)
else:
diff(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
|
cebc454080deeafa8b8de23dbcab5c3e7e24526d | iosifsag/python2016 | /square .py | 200 | 3.703125 | 4 |
x=input("give a number: ")
if(x<=0):
print "wrong data"
elif (x**0.5 % 1 == 0) :
akeraios =True
else:
akeraios = False
print akeraios
|
843b72befb84665342193505b511a3faeef04588 | jnguyen1192/advent_of_code | /2018/Day 14/Part two/TestDay14part2.py | 5,208 | 3.71875 | 4 | import unittest
def input_file():
# return the input_test file in a text
file = open('input', 'r')
lines = [line.rstrip('\n') for line in file]
file.close()
return lines
def output_file():
# read line of output_1 file
file = open('output', 'r')
res = file.read()
file.close()
return res
class Elve:
"""
An Elve has a recipe position and value
"""
def __init__(self, current_recipe_position, current_recipe_value):
"""
An Elf use those parameter build new recipe
:param current_recipe_position:
:param current_recipe_value:
"""
self.current_recipe_position = current_recipe_position
self.current_recipe_value = current_recipe_value
def get_current_recipe_position(self):
"""
:return: the current recipe position
"""
return self.current_recipe_position
def get_current_recipe_value(self):
"""
:return: the current recipe value
"""
return self.current_recipe_value
def set_current_recipe_position(self, position):
"""
set the current recipe position
"""
self.current_recipe_position = position
def set_current_recipe_value(self, value):
"""
set the current recipe value
"""
self.current_recipe_value = value
class ChocolateChartsManager:
"""
Chocolate charts manager permits us to know what happened each turn
"""
def __init__(self, after_number_recipe=9, first_recipe=3, second_recipe=7):
"""
The value of the first recipe are 3 and 7 for the two elves
:param after_number_recipe: number of recipe from the beginning of recipe list
:param first_recipe: recipe of the first elve
:param second_recipe: recipe of the second elve
"""
self.after_number_recipe = after_number_recipe
self.first_elve = Elve(0, first_recipe)
self.second_elve = Elve(1, second_recipe)
self.recipes = str(first_recipe) + str(second_recipe)
def sum_recipes(self):
"""
Calculate the sum of recipe value of both elves
:return: the sum of recipe
"""
return self.first_elve.get_current_recipe_value() + self.second_elve.get_current_recipe_value()
def next_elves_position(self):
"""
Move the two elves using the rule that
the next position is the current recipe
value plus the current position plus one
in the list of recipe
"""
first_elve_move = (self.first_elve.get_current_recipe_position() + self.first_elve.get_current_recipe_value() + 1) % len(self.recipes)
self.first_elve.set_current_recipe_position(first_elve_move)
self.first_elve.set_current_recipe_value(int(self.recipes[first_elve_move]))
second_elve_move = (self.second_elve.get_current_recipe_position() + self.second_elve.get_current_recipe_value() + 1) % len(self.recipes)
self.second_elve.set_current_recipe_position(second_elve_move)
self.second_elve.set_current_recipe_value(int(self.recipes[second_elve_move]))
def execute(self, debug=False):
# process on recipes
i = 0
# exit when the input_test found
while i < 30000000:
# sum of two elves recipe
sum_ = self.sum_recipes()
# add the number
self.recipes = self.recipes + str(sum_)
# move the elves
self.next_elves_position()
#print(i)
i += 1
if debug:
if i > 999999 and i % 1000000 == 0:
print(i, " ", len(self.recipes))
#self.print_step(i)
def print_step(self, i):
"""
print each step
"""
#print(self.recipes)
def visualize(self):
"""
Get the index of first 5 digits of the ten digits score found
:return:ten digits in string format
"""
return len(self.recipes) - len(str(self.after_number_recipe))
def data_retrieve(lines):
# return the new lines traited
return lines
def data_preparation(data):
# return the value of input_test
return int(data[0])
def day_14_part_2(lines):
# data retrieve
data = data_retrieve(lines)
# data preparation
number_after_recipe = data_preparation(data)
# data modelisation
chocolate_charts_manager = ChocolateChartsManager(number_after_recipe)
# data analyse
chocolate_charts_manager.execute(True)
# data visualize
number_of_recipe_on_the_left_score_found = chocolate_charts_manager.visualize()
return number_of_recipe_on_the_left_score_found
class TestDay14part2(unittest.TestCase):
def test_day_14_part_2(self):
lines = input_file()
res = output_file()
pred = day_14_part_2(lines)
print(pred)
#assert(pred == res)
def test_chain_code(self):
from itertools import chain
string = "hello world"
for c in chain(string):
print(c)
print((chain(string)))
print(chain(string)[0])
if __name__ == '__main__':
unittest.main()
|
fb203e55e8653490e4919d883f688fadb1572436 | jnguyen1192/advent_of_code | /2020/Day 12/Test.py | 7,861 | 4.03125 | 4 | import unittest
def input_file(suffix):
file = open('input_' + suffix, 'r')
lines = [line.rstrip('\n') for line in file]
file.close()
return lines
def output_file(number):
file = open('output_'+str(number), 'r')
res = [line.rstrip('\n') for line in file]
file.close()
return res
def get_differences(lines):
adapters = []
for line in lines:
adapters.append(int(line))
adapters.sort()
#print(adapters)
differences = {1: 1,
2: 1,
3: 1}
for index, adapter in enumerate(adapters[:-1]): # count difference
#print(adapter, adapters[index + 1], abs(adapter - adapters[index + 1]))
differences[abs(adapter - adapters[index + 1])] += 1
return differences[1], differences[3]
def get_manhattan_distance_from_starting_point(lines):
manhattan_distance_from_starting_point = 0
"""
Action N means to move north by the given value.
Action S means to move south by the given value.
Action E means to move east by the given value.
Action W means to move west by the given value.
Action L means to turn left the given number of degrees.
Action R means to turn right the given number of degrees.
Action F means to move forward by the given value in the direction the ship is currently facing.
"""
class Ship:
def __init__(self, lines, waypoint=(0, (10, -1)), pos=(0, 0), facing=0):
self.lines = lines
self.pos = pos
self.waypoint = waypoint
self.facing = facing
self.move_rule = {"N": (3, (0, -1)),
"S": (1, (0, 1)),
"E": (0, (1, 0)),
"W": (2, (-1, 0)),
"L": -1,
"R": 1,
"F": None}
def update_facing(self, code, number):
if code in "NSEW":
self.facing = self.move_rule[code][0]
else:
self.facing = int((self.facing + self.move_rule[code] * (number / 90)) % 4)
def update_waypoint(self, code, number):
if code in "NSEW":
# TODO add on the correct direction
self.facing = self.move_rule[code][0]
else:
self.facing = int((self.facing + self.move_rule[code] * (number / 90)) % 4)
def move(self, line):
code = line[0]
number = int(line[1:])
if code in "NSEW":
self.pos = (self.pos[0] + (self.move_rule[code][1][0] * number),
self.pos[1] + (self.move_rule[code][1][1] * number))
#self.update_facing(code, number)
elif code in "F":
self.pos = (self.pos[0] + (self.move_rule[self.facing][0] * number),
self.pos[1] + (self.move_rule[self.facing][1] * number))
else:
self.update_facing(code, number)
print(line, self.facing, (self.pos[0]), (self.pos[1]))
def run(self):
for line in lines:
self.move(line)
def update_facing_part_2(self, code, number):
# TODO use waypoint
if code in "NSEW":
self.facing = self.move_rule[code[1]]
else:
self.facing = int((self.facing + self.move_rule[code] * (number / 90)) % 4)
def move_part_2(self, line):
code = line[0]
number = int(line[1:])
if code in "NSEW":
# update waypoint
if code == "E":
self.waypoint = (self.waypoint[0], (self.waypoint[1][0] + number, self.waypoint[1][1]))
elif code == "W":
self.waypoint = (self.waypoint[0], (self.waypoint[1][0] - number, self.waypoint[1][1]))
elif code == "S":
self.waypoint = (self.waypoint[0], (self.waypoint[1][0], self.waypoint[1][1] + number))
elif code == "N":
self.waypoint = (self.waypoint[0], (self.waypoint[1][0], self.waypoint[1][1] - number))
#self.update_facing(code, number)
elif code in "F":
# use waypoint to move
self.pos = (self.pos[0] + (number * self.waypoint[1][0]),
self.pos[1] + (number * self.waypoint[1][1]))
else:
before_waypoint = self.waypoint[0]
self.waypoint = (int((self.waypoint[0] + self.move_rule[code] * (number / 90)) % 4), self.waypoint[1]) # use waypoint
print(self.waypoint[0] - before_waypoint)
test = (self.waypoint[0] - before_waypoint) % 4
if test == 1:
self.waypoint = (self.waypoint[0],
(-self.waypoint[1][1], self.waypoint[1][0])) # use waypoint
elif test == 2:
self.waypoint = (self.waypoint[0],
(-self.waypoint[1][0], -self.waypoint[1][1])) # use waypoint
elif test == 3:
self.waypoint = (self.waypoint[0],
(-self.waypoint[1][1], self.waypoint[1][0])) # use waypoint
print(line, self.waypoint, self.pos)
def run_part_2(self):
for line in lines:
self.move_part_2(line)
def get_manhattan_distance_from_starting_point(self):
print(abs(self.pos[0]), abs(self.pos[1]))
return abs(self.pos[0]) + abs(self.pos[1])
s = Ship(lines)
#s.run()
s.run_part_2()
return s.get_manhattan_distance_from_starting_point() # "OK"
class Test(unittest.TestCase):
def test_part_1(self):
lines = input_file("day") # get input_test
lines = input_file("test") # get input_test
res = output_file("test_1") # get output_1
#res = output_file("test_1") # get output_1
pred = get_manhattan_distance_from_starting_point(lines) # process
print(pred) # print
assert(str(pred) == res[0]) # check
def test_part_2(self):
lines = input_file("test") # get input_test
lines = input_file("day") # get input_test
sin = {0: 0, 90: 1, 180: 0, 270: -1}
cos = {0: 1, 90: 0, 180: -1, 270: 0}
x = y = dir = 0
wx = 10
wy = 1
for op, val in [(x[:1], int(x[1:])) for x in lines]: # https://topaz.github.io/paste/#XQAAAQAOAwAAAAAAAAARiAinOloyihUu1b5x+73YwmpOl2G0L3PQlPHtFchCsp3Z7fUfQnunIDN8t+CJJX3YseRhG+W9EstmUaAJ3c8sTWSPKH/H6JKPyEXwJ8pTNI+0BhsSzgpK93UvN1JWllIh6QiaBJxla1SCg1epHogeNHQ8sMbtcaesPLvn3DKfBdk9MmMnQgof2ekO9FBH+15NMLrG6AFgivSo6FJXf9p8m2ksvr1xMAUTy9YXYAPJsHESdD+KLz0vdz3VtJeNYZNaNZJqIO8DxS/LhDLeyjSWXdxkxkqA3IrMtUoUo74s91uAsBgtevi51LXvS6ToW7/RDD9cCfMU5LnAT9rmFBF3An2PvI0a62WZ9dKqygvmpu1CZzlj8/BkrwExEZIDUmdOpp7z7fKB9dAuGYLylYimJGWH1yANdPtTpSQxeewYNHSAlYKmk0uz1Whgf8p8swByDRLupcuCn/+6V1Iv
if op == 'N':
wy += val
elif op == 'S':
wy -= val
elif op == 'E':
wx += val
elif op == 'W':
wx -= val
elif op == 'R':
nwx = wx * cos[-val % 360] - wy * sin[-val % 360]
nwy = wx * sin[-val % 360] + wy * cos[-val % 360]
wx, wy = nwx, nwy
elif op == 'L':
nwx = wx * cos[val % 360] - wy * sin[val % 360]
nwy = wx * sin[val % 360] + wy * cos[val % 360]
wx, wy = nwx, nwy
else:
x += val * wx
y += val * wy
# print(wx, wy)
print(abs(x) + abs(y))
res = output_file("test_2") # get output_1
pred = get_manhattan_distance_from_starting_point(lines) # process
print(pred) # print
assert(str(pred) == res[0]) # check
if __name__ == '__main__':
unittest.main()
|
971094a287ae7f104e4a373bbfd30f42d3fcb277 | jnguyen1192/advent_of_code | /2020/Day 1/Day 1 -/TestDay1part1.py | 1,570 | 3.703125 | 4 | import unittest
from collections import Counter
def input_file():
file = open('input', 'r')
lines = [line.rstrip('\n') for line in file]
file.close()
return lines
def output_file():
file = open('output', 'r')
res = [line.rstrip('\n') for line in file]
file.close()
return res
def find_sum_2020(lines):
numbers = []
first = -1
for line in lines: # browse each lines
tmp = int(line) # convert string to int
numbers.append(tmp) # add on list
if len(numbers) == 1: # case it is the first number
first = tmp # intitialise first for the first time
continue # loop again
if first + tmp == 2020: # check the sum of two numbers
return first * tmp # special case at the first iteration
for i, v in enumerate(numbers): # browse using index
if i == 0: # case it is the first iteration
continue # loop again
for j, w in enumerate(numbers): # browse using index
if j > i: # case the second number is less than the first number
if v + w == 2020: # check the sum
return v * w # return the product
return -1 # case it won't work
class TestDay1part1(unittest.TestCase):
def test_day_1_part_1(self):
lines = input_file() # get input_test
res = output_file() # get output_1
pred = find_sum_2020(lines) # process
print(pred) # print
assert(str(pred) == res[0]) # check
if __name__ == '__main__':
unittest.main()
|
c1bf2014cb245ec29b50901423e55d98dc9540d0 | moose-pop/learning | /courses/wireless_communication/3-8.py | 567 | 3.53125 | 4 | from math import exp
import numpy as np
from scipy.special import j0
def p_z(z):
"""PDF of Rician fading distribution"""
return exp(-1-(z**2)*10**8)*j0(2*z*10**4)*z
def cdf_rician(lower, upper, step):
"""Approximate CDF of Rician fading distribution"""
interval = int((upper-lower)/step)
result = 0
for i in range(interval):
result += step*p_z(lower+i*step)
return result*2*10**8
def main():
lower = 0
upper = 10**(-4)
step = 10**(-10)
print cdf_rician(lower, upper, step)
if __name__ == "__main__":
main()
|
9973b5bf601e78dc64fe18f225478fb2da2c51d9 | samuelcm/estrutura_lista | /idade_altura.py | 988 | 4.03125 | 4 | #Faça um Programa que peça a idade e a altura de 5 pessoas,
#armazene cada informação no seu respectivo vetor. Imprima a idade e
#a altura na ordem inversa a da ordem lida.
pessoa1_id = int(input("Qual a idade?\n"))
pessoa1_alt = float(input("Qual a altura?\n"))
pessoa1 = [pessoa1_id, pessoa1_alt]
pessoa2_id = int(input("Qual a idade?\n"))
pessoa2_alt = float(input("Qual a altura?\n"))
pessoa2 = [pessoa2_id, pessoa2_alt]
pessoa3_id = int(input("Qual a idade?\n"))
pessoa3_alt = float(input("Qual a altura?\n"))
pessoa3 = [pessoa3_id, pessoa3_alt]
pessoa4_id = int(input("Qual a idade?\n"))
pessoa4_alt = float(input("Qual a altura?\n"))
pessoa4 = [pessoa4_id, pessoa4_alt]
pessoa5_id = int(input("Qual a idade?\n"))
pessoa5_alt = float(input("Qual a altura?\n"))
pessoa5 = [pessoa5_id, pessoa5_alt]
pessoa1.reverse()
print(pessoa1)
pessoa2.reverse()
print(pessoa2)
pessoa3.reverse()
print(pessoa3)
pessoa4.reverse()
print (pessoa4)
pessoa5.reverse()
print(pessoa5)
|
45aaab06a70161e300a77aad17ad3a1f58e54228 | skounah/etsinf3 | /SAR/Lab3/SAR_p3_monkey_evolved.py | 1,093 | 3.6875 | 4 | #! -*- encoding: utf8 -*-
# inspired by Lluís Ulzurrun and Víctor Grau work
"""
3-. El Mono Infinito, parte 2: generador de frases
Alemany Ibor, Sergio
Galindo Jiménez, Carlos Santiago
"""
import sys
import pickle
import random
def load_object(file_name):
with open(file_name, 'rb') as fh:
obj = pickle.load(fh)
return obj
def generate_sentence(file_name):
aux = load_object(file_name)
freq = aux[0]
dic = aux[1]
count = 1
sentence = "$"
word = "$"
while (count < 25):
ran = random.randint(1, freq[word])
for next_word, next_count in dic[word].items():
if ran <= next_count:
word = next_word
sentence += " " + next_word
count += 1
break
else:
ran -= next_count
if word == "$": break
if count == 25: sentence += " $"
return sentence
def syntax():
print ("\n%s indexfilename\n" % sys.argv[0])
sys.exit()
if __name__ == "__main__":
if len(sys.argv) < 2:
syntax()
index = sys.argv[1]
print(generate_sentence(index))
|
b570662e20ed9130b2d6eb5507fb2afdcef4477b | sulemanmahmoodsparta/Data24Repo | /ControlFlows/WhileLoops.py | 534 | 3.859375 | 4 | # x = 0
#
# while x < 10:
# print(f"it's working --> {x}")
# if x == 4:
# break
# x += 1
# print("What is your age?")
# age = input()
#
# while age.isnumeric() == False:
# print("Please reenter your age as a number")
#
# else:
# print(f"Your age is {age}")
user_prompt = True
while user_prompt:
age = input ("What is your age? ")
if age.isdigit() and int(age) < 120:
user_prompt = False
print(f"Your age is {age}!")
else:
print("Please provide your answer in digits") |
e989154ef97031eca99db043575b6c26c8e61903 | sulemanmahmoodsparta/Data24Repo | /Variables/main.py | 303 | 4.09375 | 4 | # a = 1
# b = 6
# c = 3.5
# hi = "Hello World!"
#print(hi)
# print(type(hi)) ---- Allows for printing the type for the function.
print("What is your name?")
name = input()
print("Hi")
print(name)
print("What is your DOB?")
DOB = input()
print("Wow you are born on the,")
print(DOB)
print(type(DOB))
|
e8eb1ee408ddcc96e83ceef3e62b6e636479c2b7 | sulemanmahmoodsparta/Data24Repo | /Football_Game/a_Players.py | 2,812 | 3.9375 | 4 | import random # for player generation
from abc import ABC, abstractmethod
PlayerPositions = ["Goalkeeper", "Defender", "Midfielder", "Attacker"]
# An Abstract class that cannot be initialised
class Players(ABC):
@abstractmethod
def __init__(self, fname, lname, value, position, score):
self.id = 0
self.first_name = fname
self.last_name = lname
self.value = value
self.position = position
self.score = score
class Goalkeeper(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Goalkeeper", score)
class Defender(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Defender", score)
class Midfielder(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Midfielder", score)
class Striker(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Striker", score)
# Random Name Generation
fnames = ["Liam", "Noah", "Oliver", "Elijah", "William",
"James", "Benjamin", "Lucas", "Henry", "Alexander",
"Albert", "Ake", "Alf", "Alfons", "Alfred", "Alrik",
"Anders","Ankers", "Annar", "Axel", "Basmus", "Christian",
"Clemens", "David", "Davin","Felipe", "Gabrio", "Hector",
"Helio", "Hugo", "Ismael", "Jago", "Patricio", "Ras", "Sancho",
"Valentino", "Zacarias", "Alessandro", "Alexius", "Emiliano",
"Gianni", "Leonardo", "Marco", "Patrick", "Roberto"]
lnames = ["Smith","Jones","Brown","Taylor","Wilson",
"Davies","Evans","Johnson","Thomas","Roberts",
"Silva", "Garcia", "Martin", "Murphy","Hansen", "Johansson",
"Korhonen", "Jensen", "De Jong", "Peeters", "Müller",
"Gruber", "Rossi", "Borg", "Novák", "Horvath", "Nowak",
"Kazlauskas", "Bērziņš", "Ivanov", "Zajac", "Melnyk",
"Popa", "Nagy", "Novak", "Horvat","Petrović", "Hodžić",
"Dimitrov", "Papadopoulos","Öztürk", "Conti", "Costa",
"Mancini", "Giordano", "Rizzo"]
def generate_name():
index = random.randint(0, len(fnames) - 1)
fname = fnames[index]
index = random.randint(0, len(lnames) - 1)
lname = lnames[index]
return fname, lname
def generate_player(position):
fname, lname = generate_name()
value = random.randint(75, 125)
if position == "Goalkeeper":
return Goalkeeper(fname, lname, value, position)
return Players(fname,lname, value, position)
|
d1c235ff99255777046a7a5f732d8c7fb2a6e80d | sulemanmahmoodsparta/Data24Repo | /WorkingwithFiles/WritingToFile.py | 255 | 3.890625 | 4 | def write_to_file(file, order_item):
try:
with open(file, "w") as file:
file.write(order_item + "\n")
except FileNotFoundError:
print(f"The file {file} does not exist!")
write_to_file("writing_orders.txt", "banana")
|
429dbe436598424878afa1aeee7f5238e2682c57 | sulemanmahmoodsparta/Data24Repo | /Football_Game/Match.py | 1,093 | 3.71875 | 4 | from s_Teams import Teams
import random
class Match:
def __init__(self, team1: Teams, team2: Teams):
self.team1 = team1
self.team2 = team2
self.winner = None # determined after play_match is called
def play_match(self):
# Determine which teams wins the match. Team 2 is favoured when its comes to draws.
if self.team1.team_score + random.randint(-5, 5) > self.team2.team_score + random.randint(-5, 5):
self.winner = self.team1
self.team1.team_budget += random.randint(5, 10)
self.team2.team_budget += random.randint(1, 3)
print(f"Your new budget is {self.team1.team_budget}")
else:
self.winner = self.team2
self.team2.team_budget += random.randint(5, 10)
self.team1.team_budget += random.randint(1, 3)
self.winner.points += 3
def match_result(self):
return self.winner
def add_points(self):
pass
def print_match_details(self):
print(f"{self.team1.team_name} is playing against {self.team2.team_name}")
|
618fb72bdf38974b157f55bee8eb86f8bae31e93 | sulemanmahmoodsparta/Data24Repo | /Databall/a_Players.py | 1,514 | 3.859375 | 4 | import random # for player generation
from abc import ABC, abstractmethod
# An Abstract class that cannot be initialised
class Players(ABC):
@abstractmethod
def __init__(self, fname, lname, value, position, score):
self.__first_name = fname
self.__last_name = lname
self.__value = value
self.__position = position
self.__score = score
@property
def name(self):
return f"{self.__first_name} {self.__last_name}"
@property
def value(self):
return self.__value
@property
def cost(self):
return self.__value
@property
def position(self):
return self.__position
@property
def score(self):
return self.__score
class Goalkeeper(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Goalkeeper", score)
class Defender(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Defender", score)
class Midfielder(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Midfielder", score)
class Striker(Players):
# Overriding base class abstract initialiser
def __init__(self, fname, lname, value, score):
super().__init__(fname, lname, value, "Striker", score) |
858031d131f1ba4ce058049f447bc469af31aec6 | adkhune/aditya-codes | /pythonscripts/Regular Expressions/regEx3.py | 438 | 3.703125 | 4 | # digit string manipulation example
# 122399404427 if this is input then output
#12399404427 12239404427 12239940427
# and give me the largest number
import re
from collections import Counter
def main():
str = '1223999404427'
print("you gave me", str)
numRegex = re.compile(r'(\d)\1*')
num = numRegex.findall(str)
c = Counter(re.findall(r'\d',str))
print(c)
if __name__=="__main__": main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.