blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2709f78507de09c7bc7a812798ff1a3cfab829db
arabae/ALGORITHM
/SW Expert Academy/1948.py
543
3.53125
4
def kalender(first_month, first_day, second_month, second_day): days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] answer = 0 if first_month == second_month: answer = second_day-first_day + 1 else: answer += days[first_month-1] - first_day + 1 for j in days[first_month:second_month-1]: answer += j answer += second_day return answer T = int(input()) for i in range(1, T+1): m1, d1, m2, d2 = map(int, input().split()) print('#%d %d'%(i, kalender(m1, d1, m2, d2)))
a4851fc8ba496d155e85f2f106078e0a88cfb00e
StRobertCHSCS/fabroa-PHRZORO
/Working/PracticeQuestions/2_4_6_logical_operators.py
202
4.0625
4
number_1 = int(input("Enter the first number: ")) number_2 = int(input("Enter the second number: ")) if number_1 == number_2: print((number_1 + number_2) * 2) else: print(number_1 + number_2)
eb1946fc30366686020db1d74d881a6e7df6082a
JestemStefan/AdventOfCode2020
/10/10.py
1,477
3.609375
4
import cProfile def main(): processed_input = [] with open("10/Input.txt") as input_file: for line in input_file.readlines(): line = line.strip() processed_input.append(int(line)) processed_input.append(max(processed_input) + 3) processed_input = sorted(processed_input) amount_of_one_jolts = 0 amount_of_three_jolts = 0 for i, adapter in enumerate(processed_input): #print(adapter) difference = 0 if i == 0: difference = adapter else: difference = (adapter - processed_input[i-1]) if difference < 3: amount_of_one_jolts += 1 else: amount_of_three_jolts += 1 print("Answer: " + str(amount_of_one_jolts) + " * " + str(amount_of_three_jolts) + " = " + str(amount_of_one_jolts * amount_of_three_jolts)) #print(amount_of_one_jolts * amount_of_three_jolts) solution = {0:1} for line in processed_input: solution[line] = 0 if line - 1 in solution: solution[line] += solution[line-1] #print(solution[line]) if line - 2 in solution: solution[line] += solution[line-2] #print(solution[line]) if line - 3 in solution: solution[line] += solution[line-3] #print(solution[line]) print(solution[max(processed_input)]) #cProfile.run("main()") main()
060029226c8cfa3018cbf785c73c57590052ec12
minseunghwang/algorithm
/programmers/2019 KAKAO BLIND RECRUITMENT 오픈채팅방.py
677
3.65625
4
def solution(record): answer = [] dict = {} for i in record: m = i.split() if m[0] == 'Change': dict[m[1]] = m[2] elif m[0] == 'Leave': answer.append([m[1],0]) elif m[0] == 'Enter': dict[m[1]] = m[2] answer.append([m[1],1]) temp = [] for i in answer: if i[1] == 1: temp.append(dict[i[0]] + '님이 들어왔습니다.') else: temp.append(dict[i[0]] + '님이 나갔습니다.') return temp record = ["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"] print(solution(record))
7a449cc09fe15f42e10ea92a5fe0c8bfbe24b386
shrikantpadhy18/interview-techdev-guide
/Algorithms/Searching & Sorting/Bubble Sort/bubble_sort.py
344
4.21875
4
def bubble_sort(arr): while True: swap_count = 0 for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swap_count += 1 if swap_count == 0: break return arr if __name__ == "__main__": arr = [1, 6, 2, 8, 2, 3] print(f"sorted array is {bubble_sort(arr)}")
3732f70b9cc39e3b4734ff6f8804cb4552de3988
catalinc/advent-of-code-2017
/day_5.py
1,314
3.609375
4
# Solution to https://adventofcode.com/2017/day/5 import unittest import sys def count_jumps(program, max_offset=0): jumps, pc = 0, 0 while 0 <= pc < len(program): offset = program[pc] if not max_offset: program[pc] += 1 else: if abs(offset) >= max_offset: if offset > 0: program[pc] -= 1 else: program[pc] += 1 else: program[pc] += 1 pc += offset jumps += 1 return jumps def load_program(name): program = [] with open(name, 'r') as infile: for line in infile: program.append(int(line)) return program class Test(unittest.TestCase): def test_count_jumps(self): test_program = [0, 3, 0, 1, -3] self.assertEqual(5, count_jumps(test_program)) test_program = [0, 3, 0, 1, -3] self.assertEqual(10, count_jumps(test_program, max_offset=3)) def main(): if len(sys.argv) >= 2: for name in sys.argv[1:]: program = load_program(name) print("program '%s' -> %d" % (name, count_jumps(program, max_offset=3))) else: unittest.main() if __name__ == '__main__': main()
2b64e91b6f1d9749e81d6ee2b8c96ce2b29b9b7a
GeoregTraynro/Homeauto-stuff
/button.py
377
3.5
4
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)#button GPIO.setwarnings(False) if GPIO.input(20) == False: print('Button Pressed') time.sleep(0.2) GPIO.setup(16, GPIO.OUT) GPIO.output(16, GPIO.HIGH) sleep(30) # Waits for half a second GPIO.output(16, GPIO.LOW) GPIO.cleanup()
54fdc9658248db4e3b20de31283ae23f3030aaa6
kopok2/Algorithms
/DynamicProgramming/NonDecreasingNDigits.py
468
3.515625
4
# coding=utf-8 """Non decreasing n-digits dynamic programming solution Python implementation.""" def ndnd(n): dp = [[0] * 10 for x in range(n + 1)] for i in range(10): dp[1][i] = 1 for digit in range(10): for l in range(2, n + 1): for x in range(digit + 1): dp[l][digit] += dp[l - 1][x] cnt = 0 for i in range(10): cnt += dp[n][i] return cnt if __name__ == "__main__": print(ndnd(3))
d489ee67d3e15943303e13359bfd8eef7159f38d
SupremeSadat/Scientific-Computing
/time calculator/time_calculator.py
1,148
3.5625
4
def add_time(start, duration,startDay=''): time, period = start.split() hour, minutes = map(int, time.split(":")) if period == 'PM': hour = hour + 12 daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] newDay = '' hourAdded, minutesAdded = map(int, duration.split(":")) finalminutes = minutes + minutesAdded hourAdded = hourAdded + (finalminutes // 60) finalminutes = finalminutes % 60 finalHour = hour + hourAdded days = finalHour // 24 finalHour = finalHour % 24 if finalHour < 12: period = 'AM' else: period = 'PM' if finalHour > 12: finalHour = finalHour - 12 if finalHour == 0: finalHour = 12 msg = '' if days != 0: if days == 1: msg = ' (next day)' else: msg = ' (' + str(days) + ' days later)' if startDay != '': currentDay = startDay.title() newDay = ', ' + daysOfWeek[(daysOfWeek.index(currentDay) + days) % 7] return str(finalHour) + ':' + str(finalminutes).rjust(2,'0') + ' ' + period + newDay + msg
42878f16c964b8120d43b9021ed71275103b62c4
gabriellaec/desoft-analise-exercicios
/backup/user_301/ch20_2019_03_12_22_28_56_298536.py
118
3.671875
4
a=input("qual eh seu nome?) if a==Chris return "Todo mundo odeia o Chris" else return ("Olá,{0}".format(a))
bc687d1a0315519b6ea181da7e6954e24a24c2db
Deekshith76/Cpp-programs
/python/find_binary.py
234
3.859375
4
def findBinary(num, res=""): if num == 0: return res res = str(num%2) + res return findBinary(num//2, res) num1 = 233 num2 = 32 num3 = 156 print(findBinary(num1)) print(findBinary(num2)) print(findBinary(num3))
bd4065b6272210517c3ab53f5b8101d973f4f4a9
nik24g/Python
/time module.py
729
4.0625
4
import time # import datetime initial = time.time() # this function is used to get total ticks with the help of ticks we can calculate programme execution time print(initial) list1 = ["Nitin", "Shayna", "Nik", "Kimmi"] for a in list1: print(a) print(f"For loop ran in {time.time() - initial} seconds") print("\nwhile loop start") initial2 = time.time() a = 0 while a < 4: print(list1[a]) a = a + 1 print(f"While loop ran in {time.time() - initial2} seconds") print(time.time()) time.sleep(3) # this function is used to delay the programme localtime = time.asctime(time.localtime(time.time())) # this function is used to get local time print(localtime) # hour = int(datetime.datetime.now().hour) # print(hour)
6b059fad2b6dda78c3766a8d20f6f23316fcfcd6
dani3l8200/100-days-of-python
/day5-loops/exercise5.4/main.py
274
3.59375
4
for fizz_buzz_game in range(0, 101): if fizz_buzz_game % 3 == 0 and fizz_buzz_game % 5 == 0: print('FizzBuzz') elif fizz_buzz_game % 3 == 0: print('Fizz') elif fizz_buzz_game % 5 == 0: print('Buzz') else: print(fizz_buzz_game)
d9fe554a95153c9928aa65a6ac0b154b18594cc0
mschober/algorithms
/LinkedList/python/singly_linked_list/remove_duplicates.py
1,753
3.609375
4
class LL: def __init__(self, data, next=None): self.data = data self.next = next def append(self, node): node.next = self #self.next = node return node def __repr__(self): #print 'before loop' curr = self rtr = str(curr.data) while curr.next != None: curr = curr.next rtr += str(curr.data) #print 'in loop' return rtr def __str__(self): return self.__repr__() lls = [ [3, LL(1).append(LL(3)).append(LL(4)), LL(1).append(LL(4))], [3, LL(1).append(LL(3)).append(LL(3)).append(LL(4)), LL(1).append(LL(4))], [3, None, None], [3, LL(1), LL(1)], [3, LL(3), None], [3, LL(3).append(LL(3)).append(LL(3)).append(LL(4)), LL(4)], [4, LL(4).append(LL(4)), None], [6, LL(6).append(LL(1)), LL(1)], [6, LL(1).append(LL(6)), LL(1)], [5, LL(1).append(LL(5)).append(LL(5)), LL(1)] ] def remove_match(ll, rm): if not ll: return None curr = ll while curr.data == rm and curr.next: curr = curr.next ll = curr while curr.next != None: if curr.next.data == rm: #print 'remove %s' % curr.next.data curr.next = curr.next.next else: curr = curr.next if not curr.next and curr.data == rm: return None return ll for test in lls: print "running %s" % str(test[1]) run_result = remove_match(test[1], test[0]) fail_string = "Testing %s should be %s, but was %s" % (str(test[1]), str(test[2]), str(run_result)) assert str(test[2]) == str(run_result), fail_string
929340da89139f302500938bbe6fdf38ef9b6a96
DenisYavetsky/PythonBasic
/lesson8/task7.py
1,178
3.921875
4
# 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число», реализуйте перегрузку # методов сложения и умножения комплексных чисел. Проверьте работу проекта, создав экземпляры класса (комплексные числа) # и выполнив сложение и умножение созданных экземпляров. Проверьте корректность полученного результата. class MyComplex: def __init__(self, imaginary, real): self.imaginary = imaginary self.real = real def __add__(self, other): return MyComplex(self.imaginary + other.imaginary, self.real + other.real) def __mul__(self, other): return MyComplex(self.imaginary * other.imaginary - self.real * other.real, self.imaginary * other.real + self.real * other.imaginary) def __str__(self): return f'{self.imaginary} + {self.real}j' a = MyComplex(2, 1) b = MyComplex(3, 4) print(a+b) print(a*b)
72d9d486034a6a03eb8c39e935791c5df90f6bbf
Mahesh552001/RSA-encryption-and-decryption
/RoughPy/4_rev_vowel.py
415
3.8125
4
#4-Reversing the Vowels def check_vowel(s): if (s=="a" or s=="e" or s=="i" or s=="o" or s=="u"): return True print("Enter the string:") string=str(input()) arr=[] vow_arr=[] for i in string: arr.append(i) for i in string: if check_vowel(i): vow_arr.append(i) for i in range(len(arr)): if check_vowel(arr[i]): arr[i]=vow_arr.pop() print("".join(arr))
2769731ff8b4ea9ddb88e7c29c95df4460f0c8d3
ksoltan/invent_with_python
/nameV2.py
743
4.125
4
# This gives you a new name import random import time def intro(myName): print('Hi, '+myName+'. Would you like a new name?') new=input() print('Hello, what is your name?')#This is where everything begins. myName=input() intro(myName) def newName(name): print('Well, '+myName+', your new name is '+name+'.') time.sleep(1) print('Hello '+name+'. Do you like your new name?') likeName=input() new='yes' if new=='yes': name=random.randint(1, 4) if name==1: name="Geb" if name==2: name=="Shu" if name==3: name="Ra" if name==4: name="Bast" newName(name) likeName='no' if likeName=='no': intro(myName) newName(name)
cfe654ca48b920038864bf8f881c6c522355c2af
lukadimnik/test-data-creator
/query_timer.py
676
3.5625
4
# script to test execution times of queries import sqlite3 import random import time # open database conn = sqlite3.connect('Movies.sqlite') cur = conn.cursor() count = 0 start_time = time.time() while count < 100: count = count + 1 random_year = random.randint(1900, 2000) # result = cur.execute( # f'SELECT COUNT(*) FROM Movie WHERE year = ${random_year}') query = cur.execute( 'SELECT COUNT(*) FROM Movie WHERE year = ?', (random_year,)) fetch_query = query.fetchall() result = fetch_query[0][0] # print(f"There was {result} movies in year {random_year}") end_time = time.time() print("Elapsed time: ", end_time - start_time)
8cc7776e6788bad1fb5ce63630521a094c39ca82
CPE202-PAR/project-1-enzosison
/bears.py
756
3.59375
4
# int -> booelan # Given integer n, returns True or False based on reachabilty of goal def bears(n): by_2 = n % 2 by_3 = n % 3 by_4 = n % 4 by_5 = n % 5 if n < 42: return False elif n == 42: return True if by_2 == 0: test = bears(n - n/2) if test == True: return True if by_3 == 0 or by_4 == 0: last = n % 10 second_last = (((n % 100) - last)/10) if last == 0 or second_last == 0: return False test = bears(n - (last*second_last)) if test == True: return True if by_5 == 0: test = bears(n - 42) if test == True: return True else: return False
e1ec43c6fdb2a3b47b31b64680d91cf3a9a5d4c0
LekhanaWhat/Launchpad-assignments
/program3.py
151
3.859375
4
a_list=[1,1,2,4,5,3,6,3] elem=3 b_list=[] for i in range(len(a_list)): if a_list[i]==elem: b_list.append(i) print(b_list)
2baf5b29ab47526061112932bbff36b751e4f086
dbswl4951/programmers
/programmers_level2/타겟 넘버_dfs.py
613
3.625
4
result=0 def dfs(idx,target,numbers,val,n): global result #target에 도달하면 방법의 수(result)+1하고 return if n==idx and target==val: result+=1 return #numbers의 모든 수를 사용했지만 target을 만들지 못했을 때 바로 return if n==idx: return #numbers의 모든 수를 아직 다 사용하지 않았다면 dfs(idx+1,target,numbers,val+numbers[idx],n) dfs(idx+1,target,numbers,val-numbers[idx],n) def solution(numbers, target): global result dfs(0,target,numbers,0,len(numbers)) return result #print(solution([1,1,1,1,1],3))
6dd32ff92423c42594a07cc8d23036abdd6d7419
devashish9599/PythonPractice
/s.py
397
3.609375
4
a=input("enter the string") l=input("enter the second string") z=len(l) b=input("enter the character to be searched in first string") count2=0 c=input("enter the character to be searched in second string") x=len(a) count=0 for i in range(0,x): if(a[i]==b): count=count+1 print count,"times is",b for j in range(0,z): if(l[j]==c): count2=count2+1 print count2,"times is",c
5df5e1d4984f428280d63318ee5c52d90c51a3c4
telnettech/Python
/ForLoops.py
1,942
4.34375
4
# Columns: Name, Day/Month, Celebrates, Age BIRTHDAYS = ( ("James", "9/8", True, 9), ("Shawna", "12/6", True, 22), ("Amaya", "28/2", False, 8), ("Kamal", "29/4", True, 19), ("Sam", "16/7", False, 22), ("Xan", "14/3", False, 34), ) # Problem 1: Celebrations # Loop through all of the people in BIRTHDAYS # If they celebrate their birthday, print out # "Happy Birthday" and their name print("Celebrations:") # Solution 1 here for person in BIRTHDAYS: if person[2]: print("Happy Birthday, {}".format(person[0])) print("-"*20) # Problem 2: Half birthdays # Loop through all of the people in BIRTHDAYS # Calculate their half birthday (six months later) # Print out their name and half birthday print("Half birthdays:") # Solution 2 here for person in BIRTHDAYS: name = person[0] birthdate = person[1].split('/') birthdate[1] = int(birthdate[1]) + 6 if birthdate[1] > 12: birthdate[1] = birthdate[1] - 12 birthdate[1] = str(birthdate[1]) print(name, "/".join(birthdate)) print("-"*20) # Problem 3: Only school year birthdays # Loop through the people in BIRTHDAYS # If their birthday is between September (9) # And June (6), print their name print("School birthdays:") # Solution 3 here for person in BIRTHDAYS: name = person[0] birthdate = person[1].split('/') birthdate[1] = int(birthdate[1]) if birthdate[1] in range(1, 7) or birthdate[1] in range(9, 13): print(name) print("-"*20) # Problem 4: Wishing stars # Loop through BIRTHDAYS # If the person celebrates their birthday, # AND their age is 10 or less, # Print out their name and as many stars as their age print("Stars:") # Solution 4 here for person in BIRTHDAYS: name = person[0] age = person[-1] celebrates = person[-2] if celebrates and age <= 10: stars = '' for star in range(age): stars += '*' print(name, stars) print("-"*20)
b1072da3306320b119b8ead8fe386b41eabf11e6
guhaigg/python
/month01/day07/homework/exercise04.py
1,274
3.921875
4
""" 彩票:双色球 红色:6个 1--33之间的整数 不能重复 蓝色:1个 1--16之间的整数 1) 随机产生一注彩票(列表(前六个是红色,最后一个蓝色)) 2) 在终端中录入一支彩票 要求:满足彩票的规则. """ import random # 1) 随机产生一注彩票(列表(前六个是红色,最后一个蓝色)) list_ticket = [] # 前六个红球 while len(list_ticket) < 6: number = random.randint(1, 33) if number not in list_ticket: list_ticket.append(number) # 第七个蓝球 list_ticket.append(random.randint(1, 16)) print(list_ticket) # 2) 在终端中录入一支彩票 list_ticket = [] while len(list_ticket) < 6: # number = int(input("请输入第%d个红球号码:" % (len(list_ticket) + 1))) number = int(input(f"请输入第{len(list_ticket) + 1}个红球号码:")) if number in list_ticket: print("号码已经存在") elif number < 1 or number > 33: print("号码不在范围内") else: list_ticket.append(number) while len(list_ticket) < 7: number = int(input("请输入蓝球号码:")) if number < 1 or number > 16: print("号码不在范围内") else: list_ticket.append(number) print(list_ticket)
5a629500d2eb8815cc824f210a2a0d4f4c04bf27
nihathalici/Break-The-Ice-With-Python
/Python-Files/Day-2/Question-6-alternative-solution-5.py
953
3.84375
4
""" Question 6 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 _ C _ D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. For example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26). In case of input data being supplied to the question, it should be assumed to be a console input. """ '''Solution by: saxenaharsh24 ''' my_list = [ int(x) for x in input('').split(',')] C, H, x = 50, 30, [] for D in my_list: Q = ((2*C*D) /H) ** (1/2) x.append(round(Q)) print(','.join(map(str, x)))
97ae49648ffdfb1a94fb7a9e92fa5a4b2975f622
jeff87b/Python-module-1
/Day 1-5/029.py
1,025
3.90625
4
import turtle myTurtle = turtle.Turtle() averageTemperatureList = [3, 4, 6, 9, 14, 17, 18, 17, 8, 2] numberOfRainyDays = [22, 19, 19, 18, 17] def drawRectangle(): for i in range(0, len(averageTemperatureList)): myTurtle.left(90) myTurtle.forward(20) myTurtle.left(90) myTurtle.forward(averageTemperatureList[i]) myTurtle.left(90) turtle.done() def pulse(height, width): #myTurtle.penup() #myTurtle.setpos(-300, 0) #myTurtle.pendown() #myTurtle.color('red') #myTurtle.pensize(3) #myTurtle.speed(100) myTurtle.left(90) myTurtle.forward(height*10) myTurtle.right(90) myTurtle.forward(width) myTurtle.right(90) myTurtle.forward(height*10) myTurtle.left(90) myTurtle.forward(40) #return myTurtle #drawRectangle() for temp in averageTemperatureList: print("temp now is :", temp) if temp > 10: myTurtle.color('red') else: myTurtle.color('black') pulse(temp, 25) turtle.done()
d89ce191766063948943bc7d369a42b417f69f45
emerisly/python_data_science
/list.py
889
4.0625
4
# lists are like array # is not sorted x = [3, 5, 4, 9, 7, 10] print(x) print(x[0]) print(x[3]) y = ['max', 1, 15.5, [3, 2]] print(y[3]) print(len(y)) y.insert(1, 'tom') print(y) y.remove('tom') print(y) del y[0] print(y) # pop removes the last index of a list print(y.pop()) print("pop", y) del y # error print(y) x.clear() print("x is now", x) x.append(1) print("x is now", x) y = x.copy() print("y is now", y) y.append(1) print("how many 1 in y:", y.count(1)) y=[1, 2, 3, 4] for x in y: print(x) thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist) list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 list1.extend(list2) print(list3) list1 = ["a", "b" , "c"] list2 = [1, 2, 3] for x in list2: list1.append(x) print(list1) list = [0] * 5 print(list) listc= [0, 0, 0, 0, 0] print(listc)
0c98b289ce2e931818603439e0a396ea917b857c
gauravkunwar/PyPractice
/PyExamples/dict.py
203
3.953125
4
dict={} dict[1]="This is one" dict[2]="This is two" tinydict= {"name": "Ram","value": 3 ,"address": "kathmandu"} print dict[1] print dict[2] print tinydict print tinydict.keys() print tinydict.values()
c32075aa79a491d657066446eb64392f048390d1
Anupmor1998/DSA-in-python
/Array/28.py
415
3.75
4
# Triplet Sum in Array def find3Numbers(A, n, X): A.sort() for i in range(n-2): low = i + 1 high = n - 1 while low < high: if A[i] + A[low] + A[high] == X: return "Yes" elif A[i] + A[low] + A[high] < X: low += 1 else: high -= 1 return "No" print(find3Numbers([1, 4, 45, 6, 10, 8], 6, 13))
1dccba708fe89f8852b19ed0a58b542952fdbe89
antran2123153/AssignmentPPL
/src/main/d95/utils/AST.py
6,769
3.703125
4
from abc import ABC def printlist(lst): return f"[{','.join([str(x) for x in lst])}]" def printIfThenStmt(stmt): return f"({str(stmt[0])},{printlist(stmt[1])})" class AST(ABC): pass class Program(AST): # const: List[ConstDecl] # nonconst: List[NonConstDecl] def __init__(self, const, nonconst): self.const = const self.nonconst = nonconst def __str__(self): return f"Program({printlist(self.const)},{printlist(self.nonconst)})" def accept(self, v, param): return v.visitProgram(self, param) class Decl(AST): pass class Stmt(AST): pass class ConstDecl(Decl): # id: Id # value: Expr def __init__(self, id, value): self.id = id self.value = value def __str__(self): return f"ConstDecl({str(self.id)},{str(self.value)})" def accept(self, v, param): return v.visitConstDecl(self, param) class NonConstDecl(Decl): pass class Assign(NonConstDecl, Stmt): # Used for variable declaration and assignment statement # lhs: LHS # rhs: Exp def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return f"Assign({str(self.lhs)},{str(self.rhs)})" def accept(self, v, param): return v.visitAssign(self, param) class ParamDecl(Decl): # id: Id def __init__(self, id): self.id = id def __str__(self): return f"ParamDecl({str(self.id)})" def accept(self, v, param): return v.visitParamDecl(self, param) class FuncDecl(NonConstDecl): # name: Id # param: List[ParamDecl] # body: List[Statement] def __init__(self, name, param, body): self.name = name self.param = param self.body = body def __str__(self): return f"FuncDecl({str(self.name)},{printlist(self.param)},{printlist(self.body)})" def accept(self, v, param): return v.visitFuncDecl(self, param) class ForEach(Stmt): # arr: Exp # key: Id # value: Id # body: List[Stmt] def __init__(self, arr, key, value, body): self.arr = arr self.key = key self.value = value self.body = body def __str__(self): return f"ForEach({str(self.arr)},{self.key},{self.value},{printlist(self.body)})" def accept(self, v, param): return v.visitForEach(self, param) class While(Stmt): # cond: Exp # body: List[Stmt] def __init__(self, cond, body): self.cond = cond self.body = body def __str__(self): return f"While({str(self.cond)},{printlist(self.body)})" def accept(self, v, param): return v.visitWhile(self, param) class Break(Stmt): def __str__(self): return f"Break()" def accept(self, v, param): return v.visitBreak(self, param) class Continue(Stmt): def __str__(self): return f"Continue()" def accept(self, v, param): return v.visitContinue(self, param) class Return(Stmt): # exp: Exp or None if empty def __init__(self, exp): self.exp = exp def __str__(self): return f"Return({str(self.exp) if self.exp else ''})" def accept(self, v, param): return v.visitReturn(self, param) class Exp(AST): pass class LHS(Exp): pass class Id(LHS): # name: str def __init__(self, name): self.name = name def __str__(self): return f"Id({self.name})" def accept(self, v, param): return v.visitId(self, param) class ArrayAccess(LHS): # id: Id # idx: List[Expr] def __init__(self, id, idx): self.id = id self.idx = idx def __str__(self): return f"ArrayAccess({str(self.id)},{printlist(self.idx)})" def accept(self, v, param): return v.visitArrayAccess(self, param) class BinExp(Exp): # op: str # left: Exp # right: Exp def __init__(self, op, left, right): self.op = op self.left = left self.right = right def __str__(self): return f"BinExp({self.op},{str(self.left)},{str(self.right)})" def accept(self, v, param): return v.visitBinExp(self, param) class UnExp(Exp): # op: str # exp: Exp def __init__(self, op, exp): self.op = op self.exp = exp def __str__(self): return f"UnExp({self.op},{str(self.exp)})" def accept(self, v, param): return v.visitUnExp(self, param) class AssocExp(Exp): # key: Exp # value: Exp def __init__(self, key, value): self.key, self.value = key, value def __str__(self): return f"AssocExp({self.key},{str(self.value)})" def accept(self, v, param): return v.visitAssocExp(self, param) class IntLit(Exp): # value: int def __init__(self, value): self.value = value def __str__(self): return f"IntLit({str(self.value)})" def accept(self, v, param): return v.visitIntLit(self, param) class FloatLit(Exp): #value: float def __init__(self, value): self.value = value def __str__(self): return f"FloatLit({str(self.value)})" def accept(self, v, param): return v.visitFloatLit(self, param) class BoolLit(Exp): # value: bool def __init__(self, value): self.value = value def __str__(self): return f"BoolLit({str(self.value)})" def accept(self, v, param): return v.visitBoolLit(self, param) class StringLit(Exp): # value: str def __init__(self, value): self.value = value def __str__(self): return f"StringLit({self.value})" def accept(self, v, param): return v.visitStringLit(self, param) class ArrayLit(Exp): # value: List[Exp] def __init__(self, value): self.value = value def __str__(self): return f"ArrayLit({printlist(self.value)})" def accept(self, v, param): return v.visitArrayLit(self, param) class Call(Exp, Stmt): # id: Id # param: List[Exp] def __init__(self, id, param): self.id, self.param = id, param def __str__(self): return f"Call({str(self.id)},{printlist(self.param)})" def accept(self, v, param): return v.visitCall(self, param) class If(Stmt): # ifthenStmt: List[Tuple[Expr, List[Stmt]]] # elseStmt: List[Stmt] # for Else branch, empty list if no Else def __init__(self, ifthenStmt, elseStmt): self.ifthenStmt = ifthenStmt self.elseStmt = elseStmt def __str__(self): return f"If([{','.join([printIfThenStmt(stmt) for stmt in self.ifthenStmt])}],{printlist(self.elseStmt)})" def accept(self, v, param): return v.visitIf(self, param)
bdf97fa94f977e6adc8385a1b9ce2689f28a972f
letientai299/leetcode
/py/14.longest-common-prefix.py
1,776
3.65625
4
# # @lc app=leetcode id=14 lang=python3 # # [14] Longest Common Prefix # # https://leetcode.com/problems/longest-common-prefix/description/ # # algorithms # Easy (33.00%) # Total Accepted: 417.5K # Total Submissions: 1.3M # Testcase Example: '["flower","flow","flight"]' # # Write a function to find the longest common prefix string amongst an array of # strings. # # If there is no common prefix, return an empty string "". # # Example 1: # # # Input: ["flower","flow","flight"] # Output: "fl" # # # Example 2: # # # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. # # # Note: # # All given inputs are in lowercase letters a-z. # # from typing import List class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs or len(strs) == 0: return '' if len(strs) == 1: return strs[0] max_possible_prefix_length = min([len(s) for s in strs]) i = 0 while i < max_possible_prefix_length: subset = set([s[i] for s in strs]) if len(subset) != 1: return strs[0][:i] i += 1 return strs[0][:max_possible_prefix_length] if __name__ == '__main__': tests = [ (None, ''), ([], ''), ([''], ''), (['aaa'], 'aaa'), (['a', 'aa'], 'a'), (['aa', 'a'], 'a'), (['flower', 'flow', 'flight', 'fly'], 'fl'), (['flower', 'flow', 'flight', ''], ''), (['flower', 'flow', 'floor'], 'flo'), ] for param, expected in tests: actual = Solution().longestCommonPrefix(param) if actual != expected: print(f"longestCommonPrefix({param}) == {actual} != {expected}")
bbe1e16a36825859cfac1277b9e831911e8b5f8e
wudongdong1000/Liaopractice
/practice_5.py
257
3.953125
4
#计算若干个数的积 def product(*numbers): if not numbers: return '请输入值' pro=1 for i in numbers: pro=pro*i return pro print(product(*map(int,input('请输入数值,用空格隔开:').split())))
fb569c14e3255a94a829677d3a81cb54cd2be96a
rfgrammer/NeighborPlus
/Day2.py
1,681
3.984375
4
# # IF statements # x = int(input("Please enter an integer:")) # if x < 0: # x = 0 # print('Negative changed to zero') # elif x == 0: # print('Zero') # elif x ==1: # print('Single') # else: # print('More') # # # FOR statements # words = ['cat', 'window', 'defenestrate'] # for w in words: # print(w, len(w)) # # for w in words[:]: # if len(w) > 6: # words.insert(0, w) # print(words) # # RANGE statements # for i in range(5): # print(i) # # for i in range(5, 10): # print(i) # # for i in range(0, 10, 3): # print(i) # a = ['Marry', 'had', 'a', 'little', 'lamb'] # for i in range(len(a)): # print(i, a[i]) # # for j in range(len(a)): # print("Count={0}, Value={1}".format(j, a[j])) # # for k, item in enumerate(a, 1): # print("Count={0}, Value={1}".format(k, item)) # BREAK statements # for n in range(2, 10): # for x in range(2, n): # if n % x == 0: # print('{0} equals {1} * {2}'.format(n, x, n//x)) # break # else: # print(n, 'is a prime number') # # CONTINUE statements # for num in range(0, 10): # if num % 2 == 0: # print('Found an even number : {0}'.format(num)) # continue # print('Found an odd number : {0}'.format(num)) # # # PASS statements # while True: # pass # # class MyEmptyClass: # pass # # FUNCTION statements def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() f = fib f(2000) print(f(0)) # def fib2(n): # result = [] # a, b = 0, 1 # while a < n: # result.append(a) # a, b = b, a+b # return result # # f100 = fib2(100) # print(f100)
c56c02ffaf39e82baa9afa7b3e4078e282b62405
mikkelmilo/kattis-problems
/lessThanTwoPoints/kemija.py
264
3.625
4
x = [x for x in input().split()] vowels = "aeiou" res = [] for word in x: i = 0 r = '' while i < len(word): r += word[i] if word[i] in vowels: i += 3 else: i += 1 res.append(r) print(' '.join(res))
2b084824c0bf534aa66377726aad7349ac7500e2
FinnG/pychess
/main.py
15,707
3.84375
4
#!/usr/bin/env python import operator import string class Direction(object): STRAIGHT = [[1, 0], [0, 1], [-1, 0], [0, -1]] DIAGONAL = [[1, 1], [1, -1], [-1, 1], [-1, -1]] KNIGHT = [[1, 2], [-1, 2], [1, -2], [-1, -2], [2, 1], [-2, 1], [2, -1], [-2, -1]] ALL = STRAIGHT + DIAGONAL class Color(object): class WHITE(object): pass class BLACK(object): pass class Action(object): class NONE(object): pass class MOVE(object): pass class TAKE(object): pass class CHECK(object): pass #TODO: indicates move, but also places oppo in check class CHECKMATE(object): pass #TODO: indicates move, but also checkmate class Move(object): def __init__(self, piece, position, action, captured): self.old_position = piece.position self.new_position = position self.action = action self.captured = captured self.piece = piece def __str__(self): return "%s%s%d->%s%d" % (self.piece, string.letters[self.old_position[0]], self.old_position[1] + 1, string.letters[self.new_position[0]], self.new_position[1] + 1) class Piece(object): def __init__(self, board, position, color, directions=Direction.ALL, distance=None): '''Initialise a piece. It is intended that subclasses of the Piece class will call this method with the appropriate parameters to implement most of the pieces behaviour. @param board The board on which to place this piece. @param position A tuple of size two which signifies the position to place this piece. @param color Signifies the colour of the piece, either `Color.WHITE` or `Color.BLACK`. @param direction The direction in which this piece can move. Set to all directions by default. @param distance The distance that this piece is allowed to move. ''' self.board = board self.position = position self.color = color self.directions = directions self.distance = distance self.history = [] def get_moves(self): '''Gets all legal moves that this piece can make. This method looks at the board, the directions and distance that this piece is allowed to move and determines a set of legal moves that this piece can make. @returns A list of dictionaries describing the moves that can be made. ''' moves = [] for direction in self.directions: size = self.board.size() if not self.distance else self.distance + 1 for n in range(1, size): vector = map(lambda x: x*n, direction) new_position = map(operator.add, vector, self.position) action = self.board.check_position(self, new_position) if action == Action.MOVE or action == Action.TAKE: moves.append(Move(self, new_position, action, None)) elif action == Action.NONE: break return moves def __str__(self): return '?' @property def value(self): return 3 class Pawn(Piece): def __init__(self, board, position, color): super(Pawn, self).__init__(board, position, color, [[0, 1]], 1) def get_moves(self): #TODO: will have to do something funky for en passant #TODO: add support for pawn capturing... if len(self.history) == 0: self.distance = 2 return super(Pawn, self).get_moves() def __str__(self): return 'p' @property def value(self): return 1 class Rook(Piece): def __init__(self, board, position, color): super(Rook, self).__init__(board, position, color, Direction.STRAIGHT, None) def __str__(self): return 'R' @property def value(self): return 5 class Knight(Piece): def __init__(self,board, position, color): super(Knight, self).__init__(board, position, color, Direction.KNIGHT, 1) def get_moves(self): #Implement custom get_moves as Knight can jump other pieces! moves = [] for vector in self.directions: new_position = map(operator.add, vector, self.position) action = self.board.check_position(self, new_position) if action == Action.MOVE or action == Action.TAKE: moves.append(Move(self, new_position, action, None)) break elif action == Action.NONE: break return moves def __str__(self): return 'N' class Bishop(Piece): def __init__(self, board, position, color): super(Bishop, self).__init__(board, position, color, Direction.DIAGONAL) def __str__(self): return 'B' class King(Piece): def __init__(self, board, position, color): super(King, self).__init__(board, position, color, Direction.ALL, 1) def __str__(self): return 'K' def get_moves(self): #TODO: add support for Castling return super(King, self).get_moves() class Queen(Piece): def __init__(self, board, position, color): super(Queen, self).__init__(board, position, color, Direction.ALL) def __str__(self): return 'Q' @property def value(self): return 9 class Board(object): def __init__(self): self.squares = [[None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None]] self.setup_white() self.setup_black() self.move_color = Color.WHITE self.history = {Color.WHITE: [], Color.BLACK: []} self.captured = {Color.WHITE: [], Color.BLACK: []} def size(self): return 8 def get_next_move_color(self): if self.move_color == Color.WHITE: return Color.BLACK return Color.WHITE def execute_move(self, move): #Check that we're allowed to move this piece piece = move.piece color = piece.color other_color = self.get_next_move_color() assert self.move_color == color, "got: %r expected: %r" % (color, self.move_color) #Check that the piece we're moving is where we expect it to be old_pos = move.old_position assert piece.position == old_pos assert self.squares[old_pos[0]][old_pos[1]] == piece #If this move is capturing a piece, add it to the captured list captured_piece = move.captured #TODO this is always set to None currently! if captured_piece: self.captured[color].append(captured_piece) #Actually move the piece new_pos = move.new_position self.squares[old_pos[0]][old_pos[1]] = None self.squares[new_pos[0]][new_pos[1]] = piece piece.position = new_pos #Update the board state, ready for the next move self.move_color = self.get_next_move_color() self.history[color].append(move) def unexecute_move(self): #get the last move last_color = self.get_next_move_color() move = self.history[last_color][-1] #move the piece back old_pos = move.new_position captured_piece = move.captured if captured_piece: self.captured[last_color].remove(captured_piece) new_pos = move.old_position piece = self.squares[old_pos[0]][old_pos[1]] self.squares[old_pos[0]][old_pos[1]] = captured_piece self.squares[new_pos[0]][new_pos[1]] = piece piece.position = new_pos self.move_color = self.get_next_move_color() self.history[last_color].remove(move) def setup_pieces(self, piece_row=0, pawn_row=1): for x in range(8): p = Pawn(self, [x, pawn_row], Color.WHITE) self.squares[x][pawn_row] = p r = Rook(self, [0, piece_row], Color.WHITE) self.squares[0][piece_row] = r r2 = Rook(self, [7, piece_row], Color.WHITE) self.squares[7][piece_row] = r2 n = Knight(self, [1, piece_row], Color.WHITE) self.squares[1][piece_row] = n n2 = Knight(self, [6, piece_row], Color.WHITE) self.squares[6][piece_row] = n2 b = Bishop(self, [2, piece_row], Color.WHITE) self.squares[2][piece_row] = b b2 = Bishop(self, [5, piece_row], Color.WHITE) self.squares[5][piece_row] = b2 q = Queen(self, [3, piece_row], Color.WHITE) self.squares[3][piece_row] = q k = King(self, [4, piece_row], Color.WHITE) self.squares[4][piece_row] = k def setup_white(self): self.setup_pieces(0, 1) def setup_black(self): self.setup_pieces(7, 6) def check_position(self, piece, position): x, y = position if x < 0 or x >= self.size(): return Action.NONE if y < 0 or y >= self.size(): return Action.NONE other_piece = self.squares[x][y] if other_piece != None: if other_piece.color == piece.color: return Action.NONE elif type(other_piece) == King: return Action.CHECK else: return Action.MOVE return Action.MOVE def __str__(self): #Really quick and dirty board print function result = '' for y in range(7, -1, -1): row = '' for x in range(8): if not self.squares[x][y]: row += 'x' else: row += str(self.squares[x][y]) row += ' ' result += row + "\n" return result def map(self, fn): for y in range(7, -1, -1): for x in range(8): fn(self.squares[x][y]) def evaluate(self, color): piece_values = { Pawn: 100, Knight: 320, Bishop: 330, Rook: 500, Queen: 900, King: 20000, } piece_square_values = { Pawn: [[0, 0, 0, 0, 0, 0, 0, 0], [5, 10, 10,-20,-20, 10, 10, 5,], [5, -5,-10, 0, 0,-10, -5, 5,], [0, 0, 0, 20, 20, 0, 0, 0,], [5, 5, 10, 25, 25, 10, 5, 5,], [10, 10, 20, 30, 30, 20, 10, 10,], [50, 50, 50, 50, 50, 50, 50, 50,], [0, 0, 0, 0, 0, 0, 0, 0,],], Knight: [[-50,-40,-30,-30,-30,-30,-40,-50,], [-40,-20, 0, 5, 5, 0,-20,-40,], [-30, 5, 10, 15, 15, 10, 5,-30,], [-30, 0, 15, 20, 20, 15, 0,-30,], [-30, 5, 15, 20, 20, 15, 5,-30,], [-30, 0, 10, 15, 15, 10, 0,-30,], [-40,-20, 0, 0, 0, 0,-20,-40,], [-50,-40,-30,-30,-30,-30,-40,-50,],], Bishop: [[-20,-10,-10,-10,-10,-10,-10,-20,], [-10, 5, 0, 0, 0, 0, 5,-10,], [-10, 10, 10, 10, 10, 10, 10,-10,], [-10, 0, 10, 10, 10, 10, 0,-10,], [-10, 5, 5, 10, 10, 5, 5,-10,], [-10, 0, 5, 10, 10, 5, 0,-10,], [-10, 0, 0, 0, 0, 0, 0,-10,], [-20,-10,-10,-10,-10,-10,-10,-20,],], Rook: [[0, 0, 0, 5, 5, 0, 0, 0], [-5, 0, 0, 0, 0, 0, 0, -5,], [-5, 0, 0, 0, 0, 0, 0, -5,], [-5, 0, 0, 0, 0, 0, 0, -5,], [-5, 0, 0, 0, 0, 0, 0, -5,], [-5, 0, 0, 0, 0, 0, 0, -5,], [5, 10, 10, 10, 10, 10, 10, 5,], [0, 0, 0, 0, 0, 0, 0, 0,],], Queen: [[-20,-10,-10, -5, -5,-10,-10,-20], [-10, 0, 5, 0, 0, 0, 0,-10,], [-10, 5, 5, 5, 5, 5, 0,-10,], [0, 0, 5, 5, 5, 5, 0, -5,], [-5, 0, 5, 5, 5, 5, 0, -5,], [-10, 0, 5, 5, 5, 5, 0,-10,], [-10, 0, 0, 0, 0, 0, 0,-10,], [-20,-10,-10, -5, -5,-10,-10,-20,],], King: [[20, 30, 10, 0, 0, 10, 30, 20], [20, 20, 0, 0, 0, 0, 20, 20,], [-10,-20,-20,-20,-20,-20,-20,-10,], [-20,-30,-30,-40,-40,-30,-30,-20,], [-30,-40,-40,-50,-50,-40,-40,-30,], [-30,-40,-40,-50,-50,-40,-40,-30,], [-30,-40,-40,-50,-50,-40,-40,-30,], [-30,-40,-40,-50,-50,-40,-40,-30,],], #TODO: king needs a different piece square value for endgame } pieces = self.get_pieces(color) score = 0 for piece in pieces: piece_type = type(piece) pos = piece.position score += piece_values[piece_type] + piece_square_values[piece_type][pos[0]][pos[1]] return score def get_pieces(self, color): pieces = [] for y in range(7, -1, -1): for x in range(8): piece = self.squares[x][y] if not piece: continue if piece.color == color: pieces.append(piece) return pieces def get_legal_moves(self): color = self.move_color pieces = self.get_pieces(color) moves = [] for piece in pieces: moves += piece.get_moves() return moves def get_best_moves(self): moves = self.get_legal_moves() scores = [] for move in moves: self.execute_move(move) print move, self.evaluate(Color.WHITE) scores.append(self.evaluate(Color.WHITE)) self.unexecute_move() print '--' best_moves = [] best_score = 0 for i in range(len(scores)): if scores[i] > best_score: best_moves = [moves[i]] best_score = scores[i] elif scores[i] == best_score: best_moves.append(moves[i]) return best_moves def main(): b = Board() print b moves = b.get_legal_moves() print '--' for move in moves: print move print '--' for move in b.get_best_moves(): print move # p = b.squares[1][0] # moves = p.get_moves() # print map(p.move_str, p.get_moves()) # print b.evaluate(Color.WHITE) # b.execute_move(p, moves[0]) # print b # print b.evaluate(Color.WHITE) # b.unexecute_move() # print b # print b.evaluate(Color.WHITE) if __name__ == '__main__': main()
b905432dbcca308d3624de9cc0194222a2fbe72d
BramvdnHeuvel/Batteryboys
/classes/house.py
1,010
4.03125
4
class House: """ The house class represents a house in the smart grid. Each house has an id, an x and y coordinate which determine the location of the house in the grid, and an output. """ def __init__(self, id, x, y, output): self.id = id self.x = x self.y = y self.output = output self.connected = None def __eq__(self, other): try: if self.x == other.x and self.y == other.y: return True except AttributeError: return False else: return False def connect(self, battery): """ Connect house to battery, update power, and return battery """ self.connected = battery battery.store(self.output) return self.connected def __repr__(self): """ Specify which house to use. """ return '<House id={} x={} y={} out={}>'.format(self.id,self.x,self.y,self.output)
21fc04958f040c9e4e8faaf606877f13a20ed4ae
satoshi-n/tls-warning-collector
/misc/progress_bar.py
1,563
3.53125
4
from misc.setup_logger import logger def set_progress_percentage(iteration, total): """ Counts the progress percentage. :param iteration: Order number of browser or version :param total: Total number of browsers or versions :return: Percentage number """ return float((iteration + 1) / total * 100) def print_progress(progress_percentage, cases=False, versions=False): """ Prints the progress info for cases, versions or the whole run. :param progress_percentage: Actual progress percentage number :param cases: True if printing progress for cases of particular version :param versions: True if printing progress for versions of particular browser :return: None """ if cases: logger.info("") logger.info("Cases progress: ") elif versions: logger.info("") logger.info("Versions Progress: ") else: logger.info("") logger.info("Main Progress: ") print_progress_bar(progress_percentage) def print_progress_bar(progress_percentage): """ Prints the progress bar. :param progress_percentage: Actual progress percentage number :return: None """ length = 40 perc_graph = (length * progress_percentage) / 100 output = "[" counter = 0 for i in range(int(perc_graph)): output += "=" counter += 1 for j in range((length - counter) + 1): output += " " output += "] " output += str(round(progress_percentage,2)) output += "%" logger.info(output) logger.info("")
d2af3f9c481bf5d868e446c186eb9c48efd75157
rdoherty2019/Computer_Programming
/forwards_backwards.py
1,024
4.1875
4
#setting accumulator num = 0 print("Using while loops") #Iterations while num <31: #If number is divisably by 4 and 3 if num % 4 == 0 and num % 3 == 0: #accumalte num += 3 #continue to next iterations continue #IF number is divisable by 3 print if num % 3 == 0 : print(num) #accumulate num += 3 #Setting condition nu = 30 while nu > 1: # If number is divisably by 4 and 3 if nu % 4 == 0 and nu % 3 == 0: #reduce nu -= 3 #conitune to next itteration continue # IF number is divisable by 3 print if nu % 3 == 0: print(nu) #reduce nu -= 3 print("Using for loops") #setting range, making sure 30 is included for n in range(3,31,3): if n % 4 == 0 and n % 3 == 0: continue if n % 3 == 0: print(n) #setting range #making sure 3 is included #counting backwards for n in range(30,2,-3): if n % 4 == 0 and n % 3 == 0: continue if n % 3 == 0 : print(n)
3c228c027a0f47c6a6d143caaa1dd359010de8b0
sumairhassan/Python-Basics
/lessons/03_loops.py
953
4
4
# For loops #ninjas = ['ryu', 'crystal', 'yashi', 'ken'] """for ninja in ninjas: print(ninja)""" #for ninja in ninjas[1:3]: # print(ninja) """for ninja in ninjas: if ninja == 'yashi': print(f'{ninja} -- black belt') else: print(ninja)""" """for ninja in ninjas: if ninja == 'yashi': print(f'{ninja} -- black belt') break else: print(ninja)""" ###################################################################### # While loops age=25 num=0 """ while num<age: print(num) num +=1 """ # printing only even number """ while num<age: if(num%2==0): print(num) num+=1 """ # printing till num =10 """ while num<age: if(num%2==0): print(num) if num>10: break num+=1 """ # dont want to output 0. while num<age: if num==0: num+=1 continue if(num%2==0): print(num) if num>10: break num+=1
e852721ae106749dffb22a2a86d1f38bdc69a238
ChihChaoChang/Leetcode
/035.py
1,328
4.1875
4
''' Search Insert Position Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0 ''' class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ min=nums[0] order=min i=0 while i <= (len(nums)-1): if target == nums[i]: return (i) if target not in nums: if target < nums[i]: min=target return (i) i+=1 return i ''' Better way to do it: By using binary search class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ left = 0; right = len(nums) - 1 while left <= right: mid = ( left + right ) / 2 if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid - 1 else: return mid return left '''
43d7cd8867e35b972ec49054e32fff4528878e80
ankitsingh03/code-python
/geeksforgeek/Basic Programs/compund_interest.py
181
3.65625
4
p = float(input("enter principle : ")) r = float(input("enter rate : ")) t = float(input("enter time :")) compound = p*(1+r/100)**t print(f"your compound interest is : {compound}")
a2b0a52ab313a68657bddeaf965b130b7beda59d
fazil91289/Udacity-Bikeshare-Project
/bikeshare.py
11,819
4.1875
4
import pandas as pd from datetime import datetime from datetime import timedelta import time import datetime city = '' while city.lower() not in ['chicago', 'new york', 'washington']: city = input('\nHello! Let\'s explore some US bikeshare data!\n' 'Would you like to see data for Chicago, New York, or' ' Washington?\n') if city.lower() == 'chicago': df = pd.read_csv('chicago.csv') elif city.lower() == 'new york': df = pd.read_csv('new_york_city.csv') elif city.lower() == 'washington': df = pd.read_csv('washington.csv') else: print('Sorry, I do not understand your input. Please input either ' 'Chicago, New York, or Washington.') time_period = '' while time_period.lower() not in ['month', 'day', 'none']: time_period = input('\nWould you like to filter the data by month, day,' ' or not at all? Type "none" for no time filter.\n') if time_period.lower() not in ['month', 'day', 'none']: print('Sorry, I do not understand your input.') if time_period == 'month' or time_period == 'day': month_input = '' day_input = '' months_list = ['1','2','3','4','5','6'] day_list = ['0','1','2','3','4','5','6'] if time_period == 'month': while month_input.lower() not in months_list: month_input = input('Please enter month in numbers (1 to 6),' '1 being January and 6 being June\n') if month_input.lower() not in months_list: print('Sorry, I do not understand your input. Please type in a ' 'month between January and June') elif time_period == 'day': while month_input.lower() not in months_list: month_input = input('Please enter month in numbers (1 to 6),' '1 being January and 6 being June\n') if month_input.lower() not in months_list: print('Sorry, I do not understand your input. Please type in a ' 'month between January and June') while day_input.lower() not in day_list: day_input = input('Please enter day in numbers (0 to 6),' '0 being Monday and 6 being Sunday\n') if day_input.lower() not in day_list: print('Sorry, I do not understand your input. Please type in a ' 'month between January and June') elif time_period == 'none': pass #Dropping NA values in the DataFrame df.fillna("0", inplace = True) #creating month column df['month'] = pd.DatetimeIndex(df['Start Time']).month #Creating weekday column df['weekday'] = pd.DatetimeIndex(df['Start Time']).weekday #Creating Hour column df['hour'] = pd.DatetimeIndex(df['Start Time']).hour #Creating duration_min Column df['duration_min'] = pd.to_datetime(df['Trip Duration'], unit = 's') #Creating delimiter column df['delimiter'] = "To" #Creating start_station_delimiter column df['start_station_delimiter'] = df['Start Station'] + df['delimiter'] #Creating pop trip column df['pop trip'] = df['start_station_delimiter'] + df['End Station'] #Creating age column if city == 'washington': df['Birth Year'] = 2019 df['age'] = df['Birth Year'] - 2019 df['age'] = df['age'].abs() elif city == 'chicago' or city == 'new york': df['Birth Year'] = df['Birth Year'].astype('int') df['age'] = df['Birth Year'] - 2019 df['age'] = df['age'].abs() df.loc[:, 'age'].replace([2019], [0], inplace=True) if time_period == 'month' or time_period == 'day': if month_input == '1': df = df[df['month']==1] elif month_input == '2': df = df[df['month']==2] elif month_input == '3': df = df[df['month']==3] elif month_input == '4': df = df[df['month']==4] elif month_input == '5': df = df[df['month']==5] elif month_input == '6': df = df[df['month']==6] elif month_input == '7': df = df[df['month']==7] else: pass elif time_period == 'none': pass if time_period == 'month' or time_period == 'day': if day_input == '0': df = df[df['weekday']==0] elif day_input == '1': df = df[df['weekday']==1] elif day_input == '2': df = df[df['weekday']==2] elif day_input == '3': df = df[df['weekday']==3] elif day_input == '4': df = df[df['weekday']==4] elif day_input == '5': df = df[df['weekday']==5] elif day_input == '6': df = df[df['weekday']==6] else: pass elif time_period == 'none': pass def popular_month(df): most_pop_month = int(df['month'].mode()) to_check_month = str(most_pop_month) if most_pop_month == 1: print("Most popular month is January") elif most_pop_month == 2: print("Most popular month is February") elif most_pop_month == 3: print("Most popular month is March") elif most_pop_month == 4: print("Most popular month is April") elif most_pop_month == 5: print("Most popular month is May") elif most_pop_month == 6: print("Most popular month is June") elif most_pop_month == 7: print("Most popular month is July") else: print("I dont understand") def popular_day(df): most_pop_weekday = int(df['weekday'].mode()) #to_check_weekday = str(most_pop_weekday) if most_pop_weekday == 0: print("Most popular weekday is Monday") elif most_pop_weekday == 1: print("Most popular weekday is Tuesday") elif most_pop_weekday == 2: print("Most popular weekday is Wednesday") elif most_pop_weekday == 3: print("Most popular weekday is Thurday") elif most_pop_weekday == 4: print("Most popular weekday is Friday") elif most_pop_weekday == 5: print("Most popular weekday is Saturday") elif most_pop_weekday == 6: print("Most popular weekday is Sunday") else: print("I donno ask your Mom") def popular_hour(df): df['hour'] = pd.DatetimeIndex(df['Start Time']).hour most_pop_hour = int(df['hour'].mode()) if most_pop_hour == 0: print("Most popular hour is 12 AM") elif most_pop_hour == 1: print("Most popular hour is 1 AM") elif most_pop_hour == 2: print("Most popular hour is 2 AM") elif most_pop_hour == 3: print("Most popular hour is 3 AM") elif most_pop_hour == 4: print("Most popular hour is 4 AM") elif most_pop_hour == 5: print("Most popular hour is 5 AM") elif most_pop_hour == 6: print("Most popular hour is 6 AM") elif most_pop_hour == 7: print("Most popular hour is 7 AM") elif most_pop_hour == 8: print("Most popular hour is 8 AM") elif most_pop_hour == 9: print("Most popular hour is 9 AM") elif most_pop_hour == 10: print("Most popular hour is 10 AM") elif most_pop_hour == 11: print("Most popular hour is 11 AM") elif most_pop_hour == 12: print("Most popular hour is 12 PM") elif most_pop_hour == 13: print("Most popular hour is 1 PM") elif most_pop_hour == 14: print("Most popular hour is 2 PM") elif most_pop_hour == 15: print("Most popular hour is 3 PM") elif most_pop_hour == 16: print("Most popular hour is 4 PM") elif most_pop_hour == 17: print("Most popular hour is 5 PM") elif most_pop_hour == 18: print("Most popular hour is 6 PM") elif most_pop_hour == 19: print("Most popular hour is 7 PM") elif most_pop_hour == 20: print("Most popular hour is 8 PM") elif most_pop_hour == 21: print("Most popular hour is 9 PM") elif most_pop_hour == 22: print("Most popular hour is 10 PM") elif most_pop_hour == 23: print("Most popular hour is 11 PM") else: print("I donno ask your Mom") def trip_duration(df): average_trip_duration = df['Trip Duration'].mean() average_trip_duration = int(average_trip_duration) average_trip_duration = datetime.timedelta(seconds=average_trip_duration) print('Average trip duration is :', average_trip_duration) total_trip_duration = df['Trip Duration'].sum() total_trip_duration = int(total_trip_duration) total_trip_duration_seconds = df['Trip Duration'].sum() total_trip_duration = datetime.timedelta(seconds=total_trip_duration) print('Total trip duration is :', total_trip_duration_seconds, 'seconds','i.e.', total_trip_duration, 'hours') def popular_stations(df): most_popular_start_station = df['Start Station'].mode() most_popular_start_station = str(most_popular_start_station) most_popular_start_station = most_popular_start_station[1 : : ] print('Most popular start station is : ' , most_popular_start_station) most_popular_end_station = df['End Station'].mode() most_popular_end_station = str(most_popular_end_station) most_popular_end_station = most_popular_end_station[1 : : ] print('Most popular end station is : ' , most_popular_end_station) def popular_trip(df): most_pop_trip = df['pop trip'].mode() most_pop_trip = str(most_pop_trip) #removes the 0 at the beggining most_pop_trip = most_pop_trip[1 : : ] #splits from to most_pop_trip = most_pop_trip.split("To") #joins the strings most_pop_trip = str(([most_pop_trip[0], 'to', most_pop_trip[-1] ] )) #replacing quotes most_pop_trip = most_pop_trip.replace(',', '') most_pop_trip = most_pop_trip.replace("'", '') print('The most popular trip is : ', most_pop_trip) def users(df): count_of_subscribers = df.loc[df['User Type'] == 'Subscriber', 'User Type'].count() count_of_customers = df.loc[df['User Type'] == 'Customer', 'User Type'].count() print('Total Number of Subscribers are :', count_of_subscribers) print('Total Number of Customers are :', count_of_customers) def gender(df): count_of_female = df.loc[df['Gender'] == 'Female', 'Gender'].count() count_of_male = df.loc[df['Gender'] == 'Male', 'Gender'].count() print('Total Number of Females are :', count_of_female) print('Total Number of Males are :', count_of_male) def birth_years(df): youngest = df[df['age'] > 0]['age'].min(axis=0) old_year = df[df['Birth Year'] > 0]['Birth Year'].min(axis=0) young_year = df['Birth Year'].max() oldest = df['age'].max() most_pop_birth_year = df[df['Birth Year'] > 0]['Birth Year'].mode() most_pop_birth_year = str(most_pop_birth_year) most_pop_birth_year = most_pop_birth_year[1 : : ] print("The Youngest person is", youngest, "years old, born in", young_year) print("The oldest person is", oldest, "years old, born in", old_year) print("The most popular birth year is :", most_pop_birth_year.lstrip()) def display_5lines(): if city == 'chicago': df2 = pd.read_csv('chicago.csv') print(df2.head()) elif city == 'washington': df2 = pd.read_csv('chicago.csv') print(df2.head()) elif city == 'new york': df2 = pd.read_csv('chicago.csv') print(df2.head()) popular_month(df) popular_day(df) popular_hour(df) trip_duration(df) popular_stations(df) popular_trip(df) users(df) if city == 'chicago' or city == 'new york': # What are the counts of gender? gender(df) # What are the earliest (i.e. oldest user), most recent (i.e. youngest # user), and most popular birth years? birth_years(df) validation = input('Do you want to see 5 lines of individual data?') if validation.lower() == 'yes': display_5lines() elif validation.lower() == 'no': pass else: print("I don't Understand, please type yes or no")
37b8bf20e294148cd754976af7f1ab884ce79d6f
fcu-d0449763/cryptography
/sha-1/base.py
2,308
3.671875
4
#!/usr/bin/env python #-*- coding:utf-8 -*- # convert a hex-string to it's bin code # return the bin code # retury type: str def hex_bin(hex_str): """convert hex-str to it's bin code """ hex_bin_map={ '0':'0000', '1':'0001', '2':'0010', '3':'0011', '4':'0100', '5':'0101', '6':'0110', '7':'0111', '8':'1000', '9':'1001', 'a':'1010', 'b':'1011', 'c':'1100', 'd':'1101', 'e':'1110', 'f':'1111'} return ''.join((hex_bin_map[x] for x in hex_str)) # return the converted code def dec_bin(num, nbits): """返回10进制数的二进制形式,结果为字符串,nbits表示返回的二进制位数 """ lis = [] while True: num,rem = divmod(num,2) lis.append(rem) if num == 0: break while len(lis) < nbits: lis.append(0) # 保证输出为32位的二进制 return ''.join([str(x) for x in lis[::-1]]) # -1为逆序 def bin_hex(bin_str): """将二进制字符串转化为16进制字符串 """ hex_str = hex(int(bin_str, 2))[2:] hex_str = hex_str.strip('L') while len(hex_str) < 8: hex_str = '0' + hex_str return hex_str def circle_left_shift(string, x): """circle shift the string x bits left """ return string[x:] + string[0:x] def round_fun(B, C, D, round): """每轮函数 """ B = int(B, 2) C = int(C, 2) D = int(D, 2) if round == 0: res = (B & C) | (~B & D) elif round == 1 or round == 3: res = B ^ C ^ D elif round == 2: res = (B & C) | (B & D) | (C & D) return dec_bin(res, 32) def mod32add(*binary): # 可变参数 """进行模2^32加 """ two = [] for element in binary: two.append(int(element, 2)) return dec_bin((sum(two)) % 2**32, 32) if __name__ == '__main__': print dec_bin(int('01001001001000000110110001101111',2), 32) print int('01001001001000000110110001101111',2) ^ 2223333333 print bin_hex('00000000000000000000000000001111')
4a33f2147a5eedbbff2fe23b962a1a8d7baede1d
nehabais31/LeetCode-Solutions
/sqrt_usng_binary_search.py
300
3.703125
4
# -*- coding: utf-8 -*- """ Finding the square root using Binary Search Time Complexity: O(log n) """ x = 4 low = 0 high = x + 1 while low < high: mid = low + (high - low) // 2 if mid * mid > x: high = mid else: low = mid + 1 print( low -1 )
86107d7f7576f016ec0a5ad2190ebda672beab8c
agforero/SI-PLANNING
/Plans/CSCI121S2AGF-3.5.py
2,530
4.375
4
''' While loops. Finally. 1. Write a function to print the square of all numbers from 0 to 10. 2. Write a function to print the sum of all EVEN numbers from 0 to 100. 3. Write a function to read in three numbers a, b and c, and check how many numbers between a and b are divisible by c. 4. Write a function that prints the following output: 1 99 2 98 3 97 ... 97 3 98 2 99 1 How would you do this with a while loop? How would you do this with a for loop? 5. Write a function that prints a right triangle using asterisks. For example: fn(5) --> * ** *** **** ***** 6. Write a function that prints all prime numbers between 0 and n. Have the function then return the number of numbers found. 7. Given three single-digit numbers a, b and c, write a function that prints all permutations of the three. (Next time) ''' def p1(): for i in range(11): print(i**2) n = 0 while (n < 11): print(n**2) n += 1 def sumTo(n): i = 0 counter = 0 while i <= n: counter += i i += 2 return counter def p2(n): count = 0 for i in range(int((n+2)/2)): count += i*2 return count def p3(a,b,c): count = 0 for i in range(a,b+1): if i % c == 0: count += 1 return count def p4(): x = 1 y = 99 while x < 100: print(x,y) x += 1 y -= 1 def p5(n): count = 1 str = "*" while (count <= n): print(str) str += "*" count += 1 def p5Broken(n): count = 1 str = "*" while (count <= n): print(str) str += "*" def prime(n): count = 0 for i in range(2, n-1): if n % i == 0: count += 1 # counts times a number can be divided into n if count > 0: return False else: return True def p6(n): count = 0 for i in range(n+1): if prime(i): print(i) count += 1 return count def cPrime(n): counter = 0 for i in range(2,10): while n >= 1: r = n % i if r != 0: counter += 1 print(n) n -= 1 return counter def main(): #p1() #print(sumTo(10)) #print(p2(10)) #print(p3(1,50,5)) #p4() #p5(10) print("Total prime numbers up to 100:", p6(100)) #print("Total prime numbers up to 100:", cPrime(100)) if __name__ == "__main__": main()
9e6a4d6fdbd369c43ce8fe6f1c32a1795e0d2441
ssw02238/algorithm-study
/programmers_단속카메라/answer.py
407
3.640625
4
def solution(routes): routes.sort(key=lambda x:x[0]) answer = 0 # [[-20, -15], [-18, -13], [-14, -5], [-5, -3]] while routes: tmp = routes.pop(0) while routes: if routes[0][0] <= tmp[1]: routes.pop(0) else: break answer += 1 return answer print(solution([[0,12],[1,12],[2,12],[3,12],[5,6],[6,12],[10,12]]))
0c2c19ff5ca4af7f88b5eb6817adb64a457c0fa2
EwertonLuan/Curso_em_video
/45_jo_ken_po.py
1,499
3.515625
4
from random import choice from time import sleep print('\033[1;34m=+=\033[m' * 10 + '\n JO KEN PO\n' + '\033[1;34m=*=\033[m' * 10) print('''Sua opções [1] pedra [2] papel [3] tesoura''') esco = int(input(' Escolha a sua jogada: ')) lista = ['pedra', 'papel', 'tesoura'] computa = choice(lista) print('\033[1;36mJO KEN PO...\033[m') sleep(2) if esco == 1: #pedra if computa == lista[0]: #pedra print('computador escolheu {}, voce emptou'.format(computa)) elif computa == lista[1]: #papel print('computador escolheu {}, voce perdeu'.format(computa)) elif computa == lista[2]: # tesoura print('Compudaro escolheu {}, voce ganhou'.format(computa)) else: print('Jogada inválida') if esco == 2: #papel if computa == lista[0]: # pedra print('computador escolheu {}, voce ganhou'.format(computa)) elif computa == lista[1]: #papel print('computador escolheu {}, voce empatou'.format(computa)) elif computa == lista[2]: # tesoura print('Compudaro escolheu {}, voce perdeu'.format(computa)) else: print('Jogada inválida') if esco == 3: #tesoura if computa == lista[0]: # pedra print('computador escolheu {}, voce perdeu'.format(computa)) elif computa == lista[1]: #papel print('computador escolheu {}, voce ganhou'.format(computa)) elif computa == lista[2]: # tesoura print('Compudaro escolheu {}, voce empatou'.format(computa)) else: print('Jogada inválida')
570ee5200a2372314fc276654eee553b3eed3a1f
YanHengGo/python
/39_OOP/lesson.py
382
4.03125
4
#类的共有方法 #类的私有变量 class CC: def setXY(self,x,y): self.x=x self.y=y def printXY(self): print(self.x,self.y) dd=CC() print(dd.__dict__) print(CC.__dict__) print('----------') dd.setXY(4,5) print(dd.__dict__) print(CC.__dict__) print('删除CC后printXY方法同样被调用----------') del CC dd.printXY() print(dd.__dict__)
0f44ecb5b55370f96239847af8af98447cc45d2e
EdytaBalcerzak/python-for-all
/04_chapter/cwiczenia_z_petla_for.py
134
3.6875
4
print("cwiczenia z petla for\n\n\n") for i in range (10): print("Kocham Cie, ") input("\n\n\nAby zakonczyc program , nacisnij Enter")
82bf0cf4a5d549eabe9ff8293d5aaea04d9e2723
jacindaz/bradfield_algos
/algos/duplicates.py
1,472
3.90625
4
from collections import Counter import random import time def have_duplicates_n_squared(array): for index, item in enumerate(array): for index2, item2 in enumerate(array[(index+1):]): if item == item2: return True return False def have_duplicates1(array): """ O(n) solution """ result = Counter(array) return len(array) != len(result) def have_duplicates_set(array): """ O(n) solution """ result = set(array) return len(array) != len(result) def have_duplicates2(array): """ O(n) solution, same as above, but builds dictionary manually. """ result = {} for char in array: if result.get(char): return True else: result[char] = 1 return False def have_duplicates3(array): """ O(n log n) solution """ array_sorted = sorted(array) previous_item = array_sorted[0] for index, item in enumerate(array_sorted): # if seen prevoius item if index > 0 and previous_item == item: return True return False def timing(list_length): total = 0 random_num_list = list(range(list_length)) start = time.time() have_duplicates3(random_num_list) end = time.time() total += (end-start) print(f"num_times ran: {list_length}, total: {total}, avg: {total/list_length}") # timing(100) # timing(1000) # timing(10000) # timing(100000) # timing(1000000) # timing(10000000)
9e2575781320fc63e65f8ccb9adaa9b7022eae5b
leticiassenna/POO2_trab1
/capoeira/model/cgt/Turma.py
391
3.53125
4
__author__ = 'Leticia' class Turma: def __int__(self): self.nome = "" self.turno = "" self.horario = "" self.dia_semana = "" self.rg_aluno = [] self.rg_professor = "" self.cadastro_reserva = list() self.cadastro_reserva.append(self.rg_aluno[len(self.cadastro_reserva)]) #o append insere o rg do aluno no final da lista!!
9543019bfff4ce6c96c5ccf5ecbe5c49f3665b08
jmstudyacc/python_practice
/fail_cakes.py
585
3.984375
4
dollars_cupcakes = int(input()) cents_cupcakes = int(input()) num_cupcakes = int(input()) dollar_sumcakes = dollars_cupcakes * num_cupcakes cents_cupcakes = cents_cupcakes * num_cupcakes monetary_cents = cents_cupcakes / 100 cents_to_dollars = monetary_cents // 1 remaining_cents = cents_cupcakes % 100 total_dollars = dollar_sumcakes + cents_to_dollars print(int(total_dollars), int(remaining_cents)) """ item_dollars = int(input()) item_cents = int(input()) n = int(input()) total_cents = (item_dollars * 100 + item_cents) * n print(total_cents // 100, total_cents % 100) """
0ec182b0b1390ce40dddc935fb147b93ca5b1e66
khanprog/Python-Stuff
/char_count.py
551
4.09375
4
""" Code for counting number of characters in a sentence. """ sentence = input("Enter a sentence here : ") sentence = sentence.lower() words = list(sentence) count_words = {} listCount = sentence.split(" ") print() print("Total Words: " + str(len(listCount))) print() for word in words: characters = list(word) for char in characters: if char in count_words: count_words[char] += 1 else: count_words[char] = 1 sorted_keys = sorted(count_words.keys()) for k in sorted_keys: v = count_words[k] print("Found : {0} : {1}".format(k,v))
5967427b6cc91d4d4c09ae7d66b5bf5f08ef89e9
funnyuser97/HT_1
/task8.py
299
4.1875
4
# 8. Write a script to replace last value of tuples in a list. mylist=[(1,2,3),(3,4,5),(6,7,8)] number=int(input('Input value for change :')) print('Input : ',mylist) for i in range(len(mylist)): tmp_list=list(mylist[i]) tmp_list[-1]=number mylist[i]=tuple(tmp_list) print('Output : ',mylist)
c8193691212960d3ceaf598eaca43ad2808bc201
wesenu/mit_6.00.1x
/Practice/collatz.py
1,238
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 21 10:52:44 2019 @author: dileepn Playing with the Collatz conjecture. """ import matplotlib.pyplot as plt def collatz(n, tries): """ This function implements the collatz conjecture. Start with a number, n. - If n is even, halve it - If n is odd, compute 3*n + 1 Continue this iteratively until we reach one. Inputs: n: A natural number to start with tries: Number of tries permitted. This is to terminate in case there is an infinite loop Outputs: string: 'Successful' or 'Unsuccessful' plot: Plot of the progress """ counter = 0 prog_list = [] while counter <= tries: prog_list.append(n) if (n == 1): print("Successful. Reached 1 in {} steps.".format(counter)) break if (n % 2 == 0): n = int(n/2) else: n = 3*n + 1 counter += 1 if counter > tries: print("Unsuccessful. Could not reach 1 in {} steps.".format(tries)) plt.plot(range(len(prog_list)), prog_list, 'r--') plt.grid(axis='both') plt.show()
37d51ccd6463150fd75376ea7be24e1be5eb0f10
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/hrnali002/question2.py
2,521
4.0625
4
#The 30 second food on floor program #Alison Hoernle #HRNALI002 #8 March 2014 print("Welcome to the 30 Second Rule Expert") print("------------------------------------") print("Answer the following questions by selecting from among the options.") see = input("Did anyone see you? (yes/no)\n") if (see == 'yes'): who = input("Was it a boss/lover/parent? (yes/no)\n") if (who == 'yes'): price = input("Was it expensive? (yes/no)\n") if (price == 'yes'): cut_off = input("Can you cut off the part that touched the floor? (yes/no)\n") if (cut_off == 'yes'): print("Decision: Eat it.") else: print("Decision: Your call.") else: chocolate = input("Is it chocolate? (yes/no)\n") if (chocolate == 'yes'): print("Decision: Eat it.") else: print("Decision: Don't eat it.") else: print("Decision: Eat it.") else: sticky = input("Was it sticky? (yes/no)\n") if (sticky == 'yes'): what = input("Is it a raw steak? (yes/no)\n") if (what == 'yes'): puma = input("Are you a puma? (yes/no)\n") if (puma == 'yes'): print("Decision: Eat it.") else: print("Decision: Don't eat it.") else: cat = input("Did the cat lick it? (yes/no)\n") if (cat == 'yes'): cat_healthy = input("Is your cat healthy? (yes/no)\n") if (cat_healthy == 'yes'): print("Decision: Eat it.") else: print("decision: Your call.") else: print("Decision: Eat it.") else: emausaurus = input("Is it an Emausaurus? (yes/no)\n") if (emausaurus == 'yes'): megalosaurus = input("Are you a Megalosaurus? (yes/no)\n") if (megalosaurus == 'yes'): print("Decision: Eat it.") else: print("Decision: Don't eat it.") else: cat = input("Did the cat lick it? (yes/no)\n") if (cat == 'yes'): cat_healthy = input("Is your cat healthy? (yes/no)\n") if (cat_healthy == 'yes'): print("Decision: Eat it.") else: print("Decision: Your call.") else: print("Decision: Eat it.")
c5d666108c8892968cd317c066294772c56abd33
amani021/python100d
/day_57.py
799
4.65625
5
#-------- DAY 57 "regular expressions (regEx)1" -------- import re #Built-in module for RegEx # You can by RegEx searching a specified pattern from a string & check if it exist or not print("Lesson 57: Regular Expressions (RegEx) 1") txt = "This lesson is so important to understand it" print(txt + "\n---------------------\nWe will do some checking for that statement:") test1 = re.search("^This.*it$", txt) if (test1): print(" YES! we have a match :)") print(' ', re.findall("s", txt)) #Return a list print(' ', re.findall("[e-m]", txt)) #Return a list contains a set of characters from e to m print(' ', re.split(" ", txt)) print(' ', re.sub("\s", " -> ", txt, 2)) #Replace first 2 white-spaces print(' ', re.findall(r"\bTh", txt)) else: print('SORRY :( no match')
ee9d46ed3be2c96249346e0413d2b2e6986d8746
Ahuang1158/TurtleArtDesign
/myShape.py
810
3.640625
4
def square( t, distance ): for times in range(4): t.forward(distance) t.left(90) def triangle( t, distance ): for times in range(3): t.forward(distance) t.left(120) def pentagon ( t, distance): angle=360/5 for times in range(5): t.forward(distance) t.left(angle) def polygon ( t, distance, side): angle=360/side t.begin_fill() for times in range(side): t.forward(distance) t.left(angle) t.end_fill() def move ( t, x, y): t.penup() t.goto(x, y) t.pendown() def petal (t,distance): t.begin_fill() for times in range(4): t.forward(distance) t.left(40) t.forward(distance) t.left(140) t.end_fill()
81df80f8a2c91279ad4c6d14069b07cf6246898f
mridulrb/Basic-Python-Examples-for-Beginners
/Programs/MyPythonXII/Unit2/PyChap02/empdisp.py
1,022
4.15625
4
# File name: ...\\MyPythonXII\Unit1\PyChap02\empdisp.py # Accessing employee information using class class Employee: # Class variables empcode = "" empname = "" empdesig = "" empbasic = 0 # Constructor called when creating an object of class type def __init__(self, ecode, ename, edesig, esal): self.empcode = ecode self.empname = ename self.empdesig = edesig self.empbasic = esal # A class method def Display(self): # Accessing attributes in class method print ("Here is the employee information....") print ("=" * 30) print("Employee code:", self.empcode) print("Employee name:", self.empname) print("Employee designation:", self.empdesig) print("Employee salary:", self.empbasic) # Creating a class object with three parameterized values Emp = Employee("E100", 'Mr. B Srinivasan', 'Sr. Programmer', 12600) # Calling the class method using instance object Emp.Display()
f86f63b127ed1f45defe3164b15512b560dadc11
jiajiabin/python_study
/day11-20/day17/06_协程.py
291
3.875
4
def function(n, s): for i in range(n): print(s) yield True yield False i1 = iter(function(5, "hello world!")) i2 = iter(function(6, "good morning!!")) ret1 = ret2 = True while ret1 or ret2: if ret1: ret1 = next(i1) if ret2: ret2 = next(i2)
dcc0c2437211e471c00fd73b2bb25ea3c5a25a32
evbeda/games2
/guess_number_game/test_guess_number_game.py
1,593
3.609375
4
import unittest from guess_number_game.guess_number_game import GuessNumberGame class TestGuessNumberGame(unittest.TestCase): def setUp(self): self.game = GuessNumberGame() self.game._guess_number = 50 def test_initial_status(self): self.assertTrue(self.game.is_playing) def test_play_lower(self): play_result = self.game.play(10) self.assertEqual(play_result, 'too low') self.assertTrue(self.game.is_playing) def test_play_higher(self): play_result = self.game.play(80) self.assertEqual(play_result, 'too high') self.assertTrue(self.game.is_playing) def test_play_equal(self): play_result = self.game.play(50) self.assertEqual(play_result, 'you win') self.assertFalse(self.game.is_playing) def test_initial_next_turn(self): self.assertEqual( self.game.next_turn(), 'Give me a number from 0 to 100', ) def test_next_turn_after_play(self): self.game.play(10) self.assertEqual( self.game.next_turn(), 'Give me a number from 0 to 100', ) def test_next_turn_after_win(self): self.game.play(50) self.assertEqual( self.game.next_turn(), 'Game Over', ) def test_get_board(self): self.assertEqual( self.game.board, '[]' ) self.game.play(10) self.assertEqual( self.game.board, '[10]' ) if __name__ == "__main__": unittest.main()
699593147f6382fa46ef364eaff01ad3a747ad41
LimaXII/CPD-Laboratorios
/Laboratório 1/lab1.py
8,240
3.515625
4
#Laboratorio 1 - CPD: #Nomes: Luccas da Silva Lima e Bruno Longo Farina #Turma: B #biblioteca necessaria para cronometrar o tempo. import time #vai criar uma lista onde vai ser posto o texto antes de ser escrito no arquivo textinho = [] #mesma ideia da outra variavel textinho2 = [] #funcao que define qual sequencia devera ser utilizada. def definir_seq(seq): if seq[2] == 4: return 'SHELL' elif seq[2] == 13: return 'KNUTH' else: return 'CIURA' #Funcao shell_sort. Recebe como parametro um vetor, o seu tamanho e uma sequencia. def shell_sort(array,n,seq): #Exercicio 1: #escreve no textinho o array intacto e qual sequencia está sendo utilizada (ver se n é melhor fazer isso dentro da main ao inves da função) textinho.append(str(array)) textinho.append('SEQ = ') textinho.append(definir_seq(seq)) textinho.append('\n') #inicia i valendo 0 e percorre o vetor da sequencia utilizada (shell, knuth ou ciura) i = 0 while i < 20: #caso ache um valor em seq[i+1] MAIOR que a posicao presente no meio do vetor, utiliza seq[i] if seq[i+1] >= n: #enquanto i, variavel que ira percorrer o vetor das sequencias, for maior ou igual a 0: while i >= 0: #com j comecando em seq[i] e indo ate o numero de elementos do vetor a ser ordenado for j in range(seq[i], n): #variavel auxiliar recebe o valor do vetor a ser ordenado na posicao j. array[j] aux = array[j] #contador_aux recebe o valor de j contador_aux = j while contador_aux >= seq[i] and array[contador_aux - seq[i]] > aux: #TROCA o numero na posicao contador_aux do vetor a ser ordenado, pelo conteudo na posicao array[x - incremento]. array[contador_aux] = array[contador_aux - seq[i]] #contador_aux recebe a posicao que foi utilizada acima: array[x - incremento] contador_aux = contador_aux - seq[i] #Troca o outro valor do vetor. array[contador_aux]: array[contador_aux] = aux #Como as 'trocas' sao realizadas utilizando variaveis auxiliares, cada uma delas deve ser feita separadamente. #printa o array, informando qual incremento foi utilizado. print(array, 'INCR =',seq[i]) #vai colocar numa lista essa string que acabou de ser disposta textinho.append(str(array)) textinho.append('INCR =') textinho.append(str(seq[i])) textinho.append('\n') #decrementa i, para retroceder uma posicao no vetor das sequencias. i = i - 1 #Caso o ordenamento tenha acontecido, i = 20 para interromper o loop no while. i = 20 #Caso seq[i+1] nao for >= n, incrementa i. else: i = i + 1 #Funcao shell_sort. Recebe como parametro um vetor, o seu tamanho e uma sequencia. def shell_sort2(array,n,seq): #Exercicio 2: inicio = time.time() #variavel que ira cronometrar o tempo de execucao. textinho2.append(definir_seq(seq)) textinho2.append(', ') textinho2.append(str(n)) textinho2.append(', ') #inicia i valendo 0 e percorre o vetor da sequencia utilizada (shell, knuth ou ciura) i = 0 while i < 20: #caso ache um valor em seq[i+1] MAIOR que a posicao presente no meio do vetor, utiliza seq[i] if seq[i+1] >= n: #enquanto i, variavel que ira percorrer o vetor das sequencias, for maior ou igual a 0: while i >= 0: #com j comecando em seq[i] e indo ate o numero de elementos do vetor a ser ordenado for j in range(seq[i], n): #variavel auxiliar recebe o valor do vetor a ser ordenado na posicao j. array[j] aux = array[j] #contador_aux recebe o valor de j contador_aux = j while contador_aux >= seq[i] and array[contador_aux - seq[i]] > aux: #TROCA o numero na posicao contador_aux do vetor a ser ordenado, pelo conteudo na posicao array[x - incremento]. array[contador_aux] = array[contador_aux - seq[i]] #contador_aux recebe a posicao que foi utilizada acima: array[x - incremento] contador_aux = contador_aux - seq[i] #Troca o outro valor do vetor. array[contador_aux]: array[contador_aux] = aux #Como as 'trocas' sao realizadas utilizando variaveis auxiliares, cada uma delas deve ser feita separadamente. #decrementa i, para retroceder uma posicao no vetor das sequencias. i = i - 1 #Caso o ordenamento tenha acontecido, i = 20 para interromper o loop no while. i = 20 #Calcula o tempo decorrido durante a execucao da funcao. fim = time.time() tempo = (fim - inicio) #Salva o tempo na string textinho2. textinho2.append(str(tempo)) textinho2.append('\n') #Caso seq[i+1] nao for >= n, incrementa i. else: i = i + 1 #Sequencias utilizadas: shell = [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576] knuth = [1,4,13,40,121,364,1093,3280,9841,29524,88573,265720,797161,2391484] ciura = [1,4,10,23,57,132,301,701,1577,3548,7983,17961,40412,90927,204585,460316,1035711] #Exercicio 1: #abre o arquivo para criar uma lista com os tamanhos de cada array with open('entrada1.txt','r') as f: tamanho = [int(r.split()[0]) for r in f] #Abre o arquivo novamente. f = open('entrada1.txt','r') #pra cada linha ele armazena os valores numa string for i in tamanho: data = f.readline() #converte a string em uma lista de inteiros res1 = [int(i) for i in data.split()] res2 = [int(i) for i in data.split()] res3 = [int(i) for i in data.split()] #remove o primeiro valor, que era o tamanho del res1[0] del res2[0] del res3[0] #e faz o shell sort dela shell_sort(res1,i,shell) shell_sort(res2,i,knuth) shell_sort(res3,i,ciura) #Cria o segundo arquivo de saida, contendo os resultados do exercicio 1. arquivo = open('saida1.txt', 'w') j = 0 for i in textinho: arquivo.write(textinho[j]) j=j+1 arquivo.close() f.close() #Exercicio 2: #Abre o arquivo entrada2.txt e armazenha na variavel tamanho, os tamanhos de todos os vetores presentes no arquivo. with open('entrada2.txt','r') as f: tamanho = [int(r.split()[0]) for r in f] #Abre o arquivo entrada2.txt e le os vetores presentes nele. f = open('entrada2.txt', 'r') for i in tamanho: data = f.readline() #converte a string em uma lista de inteiros res1 = [int(i) for i in data.split()] res2 = [int(i) for i in data.split()] res3 = [int(i) for i in data.split()] #remove o primeiro valor dos vetores (este valor informava o tamanho de cada vetor). del res1[0] del res2[0] del res3[0] #Faz o shell sort dela shell_sort2(res1,i,shell) shell_sort2(res2,i,knuth) shell_sort2(res3,i,ciura) #Cria o segundo arquivo de saida, contendo os resultados do exercicio 2. arquivo = open('saida2.txt', 'w') j = 0 for i in textinho2: arquivo.write(textinho2[j]) j=j+1 #Fecha o arquivo. arquivo.close() f.close()
e2cb553c1d23f2f3da65a1052ee290237dd6c1ce
fern17/algorithms_python
/sorting/bubble_sort.py
171
3.859375
4
def bubble_sort(v): for i in range(0, len(v)): for j in range(i+1, len(v)): if v[i] > v[j]: v[i], v[j] = v[j], v[i] return v
8d2377b49c58c975761d0fe014d8224fdd5ee8ee
aniket134/myCoding
/python/class_constructor.py
181
3.828125
4
class My_class(): def __init__(self, name): self.name = name print('inside My_class: ' + self.name) I1 = My_class('sall') I2 = My_class('bill') print(I1.name) print(I2.name)
e52e2085cccb9ac162fa3b8a22c8f4a6f3ef5f40
Sandoval-Angel/Learning-to-Code-Py
/Udemy: 100 Days of Code Challenge/Day 4.py
2,228
4.0625
4
from random import randint from time import sleep rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' rps_choices = [rock, paper, scissors] def initiate_game(): play_choice = input("\nEnter (S) to start a new game or (Q) to quit: ").lower() if play_choice == 's': rps_game() elif play_choice == 'q': print('\nThanks for playing! The game will now quit.') sleep(3) exit() else: print("\nERROR: Invalid entry! Only 'S' and 'Q' are recognized.") initiate_game() def rps_game(): cpu_choice = randint(0, 2) while True: try: choice_int = int(input('\nWhich do you pick? Enter 0 for Rock, 1 for Paper, or 2 for Scissors: ')) if choice_int < 0 or choice_int > 2: raise ValueError except ValueError: print('\nInvalid Entry: Entry not a number between 0 and 2.') else: break if choice_int == 0: print('\nYou picked:\n' + rps_choices[0] + '\nComputer picked:') if cpu_choice == 0: print(rps_choices[0] + '\nDraw!') elif cpu_choice == 1: print(rps_choices[1] + '\nYou lose!') else: print(rps_choices[2] + '\nYou win!') if choice_int == 1: print('\nYou picked:\n' + rps_choices[1] + '\nComputer picked:') if cpu_choice == 1: print(rps_choices[1] + '\nDraw!') elif cpu_choice == 2: print(rps_choices[2] + '\nYou lose!') else: print(rps_choices[0] + '\nYou win!') if choice_int == 2: print('\nYou picked:\n' + rps_choices[2] + '\nComputer picked:') if cpu_choice == 2: print(rps_choices[2] + '\nDraw!') elif cpu_choice == 0: print(rps_choices[0] + '\nYou lose!') else: print(rps_choices[1] + '\nYou win!') initiate_game() initiate_game()
b795a7eb1156a42996df907e8bf50f35ac504e07
nitishgupta/qdmr
/analysis/test_prog_lisp.py
5,795
3.515625
4
from typing import List from parse_dataset.parse import (qdmr_program_to_nested_expression, nested_expression_to_lisp, remove_args_from_nested_expression) def lisp_to_nested_expression(lisp_string: str) -> List: """ Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example, "(count (division first))" would get mapped to ['count', ['division', 'first']]. """ stack: List = [] current_expression: List = [] tokens = lisp_string.split() for token in tokens: while token[0] == "(": nested_expression: List = [] current_expression.append(nested_expression) stack.append(current_expression) current_expression = nested_expression token = token[1:] current_expression.append(token.replace(")", "")) while token[-1] == ")": current_expression = stack.pop() token = token[:-1] return current_expression[0] def print_sexp(exp): out = '' if type(exp) == type([]): out += '(' + ' '.join(print_sexp(x) for x in exp) + ')' elif type(exp) == type('') and re.search(r'[\s()]', exp): out += '"%s"' % repr(exp)[1:-1].replace('"', '\"') else: out += '%s' % exp return out def annotation_to_lisp_exp(annotation: str) -> str: # TODO: Remove this hard-coded fix annotation = annotation.replace('and\n', 'bool_and\n') annotation = annotation.replace('or\n', 'bool_or\n') expressions = annotation.split('\n') output_depth = 0 output = [] def count_depth(exp: str): """count the depth of this expression. Every dot in the prefix symbols a depth entry.""" return len(exp) - len(exp.lstrip('.')) def strip_attention(exp: str): """remove the [attention] part of the expression""" if '[' in exp: return exp[:exp.index('[')] else: return exp for i, exp in enumerate(expressions): depth = count_depth(exp) if i + 1 < len(expressions): next_expression_depth = count_depth(expressions[i+1]) else: next_expression_depth = 0 output.append('(') exp = strip_attention(exp) exp = exp.lstrip('.') output.append(exp) if next_expression_depth <= depth: # current clause should be closed output.append(')') while next_expression_depth < depth: # close until currently opened depth output.append(')') depth -= 1 output_depth = depth while 0 < output_depth: output.append(')') output_depth -= 1 # now make sure there's no one-expression in a parentheses (e.g. "(exist (find))" which should be "(exist find)") i = 0 new_output = [] while i < len(output): exp = output[i] if i + 2 >= len(output): new_output.append(exp) i += 1 continue exp1 = output[i+1] exp2 = output[i+2] if exp == '(' and exp1 not in ['(', ')'] and exp2 == ')': new_output.append(exp1) i += 2 else: new_output.append(exp) i += 1 output = ' '.join(new_output) output = output.replace('( ', '(') output = output.replace(' )', ')') return output def annotation_to_module_attention(annotation: str) -> List: """ retrieves the raw annotation string and extracts the word indices attention for each module """ lines = annotation.split('\n') attn_supervision = [] for line in lines: # We assume valid input, that is, each line either has no brackets at all, # or has '[' before ']', where there are numbers separated by commas between. if '[' in line: start_i = line.index('[') end_i = line.index(']') module = line[:start_i].strip('.') sentence_indices = line[start_i+1:end_i].split(',') sentence_indices = [ind.strip() for ind in sentence_indices] attn_supervision.append((module, sentence_indices)) return attn_supervision # input_program = \ # "equal\n"\ # ".count\n"\ # "..with_relation[3]\n"\ # "...find[1]\n"\ # "...project[5,6]\n"\ # "....find[8,9,10]\n"\ # ".1[0]\n" # # lisp_program = annotation_to_lisp_exp(input_program) # python_program = lisp_to_nested_expression(lisp_program) # attn_supervision = annotation_to_module_attention(input_program) # back_lisp = nested_expression_to_lisp(python_program) # print(back_lisp) # print(lisp_program) # print(python_program) # print(back_lisp) # print((back_lisp == lisp_program)) # print(attn_supervision) print("\n") x = "(COMPARISON (max (SELECT North__China West__India) (SELECT North__Middle)))" nested_python_program = lisp_to_nested_expression(x) back_lisp = nested_expression_to_lisp(nested_python_program) print(nested_python_program) print(back_lisp) print() # program = [ # "SELECT['when was Jabal Shammar being annexed']", # "SELECT['when was the preliminary attack on Taif']", # "COMPARISON['max', '#1', '#2']" # ] program = [ "SELECT['people killed According to official reports']", "AGGREGATE['count', '#1']", "SELECT['people wounded According to official reports']", "AGGREGATE['count', '#3']", "COMPARISON['max', '#2', '#4']" ] qdmr_nested_expression = qdmr_program_to_nested_expression(program) print(qdmr_nested_expression) print(nested_expression_to_lisp(qdmr_nested_expression)) print(lisp_to_nested_expression(nested_expression_to_lisp(qdmr_nested_expression))) print(remove_args_from_nested_expression(qdmr_nested_expression))
78516228051f3909522ff569d36a90ed05e837bb
lucy9215/leetcode-python
/88_mergeSortedArray.py
783
3.9375
4
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ while m>0 and n>0: if nums1[m-1]>nums2[n-1]: nums1[m+n-1] = nums1[m-1] m-=1 else : nums1[m+n-1] = nums2[n-1] n-=1 if n>0: nums1[:n]=nums2[:n] # return nums1 def main(): solution = Solution() nums2 = [1,2,3,4,5] nums1 = [2,9] m = len(nums1) n = len(nums2) nums1+=nums2 print ('Output:', solution.merge(nums1,m,nums2,n)) if __name__ == '__main__': main()
15352584fbdce193854661aacf3b73826e716db8
paweldunajski/python_basics
/12_If_Statements.py
462
4.25
4
is_male = True if is_male: print("You are a male") is_male = False is_tall = False if is_male or is_tall: print("You are male or tall or both") else: print("You are not a male nor tall ") if is_male and is_tall: print("You are male and tall") elif is_male and not is_tall: print("You are male but not tall") elif not is_male and is_tall: print("You are not a male but are not tall") else: print("you are not a male and not tall")
2f473f094f575d4176b1beda3503b96214780e2d
guywine/Python_course
/Exercises/09_tests/test_intadd.py
1,566
3.53125
4
import pytest from intadd import intadd def intadd(num1: int, num2: int) -> int: """Adds two numbers, assuming they're both positive integers. Parameters ---------- num1, num2 : int Positive integers Returns ------- int Resulting positive integer Raises ------ ValueError If either number is negative TypeError If either number isn't an integer """ if (not isinstance(num1, int)) or (not isinstance(num2, int)): raise TypeError(f"Received {num1, num2}; expected integers, not {type(num1), type(num2)}") if (num1 < 0) or (num2 < 0): raise ValueError(f"Received {num1, num2}; expected positive integers") return num1 + num2 standard_inputs = [(1, 2, 3), (100000, 200000, 100000 + 200000)] @pytest.mark.parametrize('inp1, inp2, result', standard_inputs) def test_valid_inputs(inp1, inp2, result): assert result == intadd(inp1, inp2) assert result == intadd(inp2, inp1) negative_valueerror_inputs = [(-1, 1), (1, -2), (-2, -3)] @pytest.mark.parametrize('inp1, inp2', negative_valueerror_inputs) def test_negative_input_raises_valueerror(inp1, inp2): with pytest.raises(ValueError): intadd(inp1, inp2) intadd(inp2, inp1) typeerror_inputs = [ ('s', 0), (None, 0), ([], 1), ((), 10), ({}, 2), ({1}, 20) ] @pytest.mark.parametrize("inp1, inp2", typeerror_inputs) def test_invalid_input_raises_typeerror(inp1, inp2): with pytest.raises(TypeError): intadd(inp1, inp2) intadd(inp2, inp1)
69e58218827f49d3ffdb68a7213b542eff5791c5
kotegit2020/Python-Practice
/strdict.py
156
3.765625
4
str1 = "koti" mydict = { } for x in str1: if x.lower() in mydict: mydict[x.lower()] += 1 else: mydict[x.lower()] = 1 print(mydict)
b2c0db85d44b8eab0c013975f22c4d6b34c98f5e
AlejoCasti/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
235
3.546875
4
#!/usr/bin/python3 """ Get number of lines """ def number_of_lines(filename=""): """ number of lines function """ with open(filename, 'r') as fil: idx = 0 for i in fil: idx += 1 return idx
7e8500189de257c5cc988d1b5cbcceed6a274582
pyskills/Python-Programming
/rock_paper_scissor/basic2.py
902
4.09375
4
import random prompt = 'Enter your choice:\nR or r for rock\nP or p for paper\nS or s for scissors\nQ or q to quit\n' out_template = 'you {} against the computer' while True: # infinite loop till break user = input(prompt).lower() # lower case users input if user == 'q': break result = 'lose' # default if not won comp = random.choice(['rock', 'paper', 'scissors']) print('Computer picked:', comp) if comp[0] == user: # moved tie out of main if result = 'tie' else: # test if win if user == 'r' and comp == 'scissors': result = 'win' if user == 'p' and comp == 'rock': result = 'win' if user == 's' and comp == 'paper': result = 'win' # NOTE: above three if's can become one boolean expressions, just or the if expressions together print(out_template.format(result))
abd002c718c2e42e2ede6668839d6db43f538f3d
linuxfranklin/benjamin
/Days_calculator.py
298
3.609375
4
days=365 weeks=52 months=12 life_span=65 age_now=int(input("Enter your age :")) left_years=life_span-age_now left_months=left_years*months left_weeks=left_months*weeks left_days=left_months*days print(f"months to live : {left_months}, weeks to live : {left_weeks}, days to live : {left_days}")
cf3f9026197fcb0abc7c8b0f8028671b3f7fa29f
ushodayak/ushodaya
/area of circle using math
106
4.125
4
import math r = float(input("Enter the radius of the circle: ")) area = math.pi* r * r print("%.2f" %area)
996d02a5c96343f9401e0fd88d00059bfa04e75f
aaronsellek/w3-pathfinder-aaronsellek
/w3-pathfinder-aaronsellek/pathfinder.py
2,969
3.875
4
from PIL import Image, ImageDraw class Map: #creating a class for the map itself def __init__(self, filename): self.elevations = [] #creating the empty list for elevations with open(filename) as file: for line in file: self.elevations.append([int(e) for e in line.split()]) #inputting the elevation altitudes into the empty list self.maximum_elevation = max([max(row) for row in self.elevations]) self.minimum_elevation = min([min(row) for row in self.elevations]) #finding the minimum and the maximum elevations def elevation(self, x, y): return self.elevations[y][x] #finding the x and y coordinates for the map def find_color(self, x, y): return int((self.elevation(x, y) - self.minimum_elevation) / (self.maximum_elevation - self.minimum_elevation) * 255) #finding the correct numerical value to assign them to colors class DrawMap: #creating a class for actually showing the colors and making the picture of the map def __init__(self, Map, point): self.Map = Map self.picture = Image.new('RGBA', (len(self.Map.elevations[0]), len(self.Map.elevations))) self.point = point #using "point" in order to find the starting point to create the line in map def draw(self): for x in range(len(self.Map.elevations[0])): for y in range(len(self.Map.elevations)): self.picture.putpixel((x, y), (self.Map.find_color(x, y), self.Map.find_color(x, y), self.Map.color(x, y))) self.picture.save('map.png') def print_path(self, point): for item_point in point: self.picture.putpixel(item_point, (156, 226, 227)) self.picture.save('aaronsmap.png') return self.picture class Pathfinder: def __init__(self, Map): self.Map = Map def pathfinder_finalized(self): self.point = [] cur_x = 0 cur_y = 50 while cur_x < len(self.Map.elevations[0]) - 1: possible_ys = [cur_y] if cur_y - 1 >= 0: possible_ys.append(cur_y - 1) if cur_y + 1 < len(self.Map.elevations): possible_ys.append(cur_y + 1) diffs = [ abs(self.Map.elevations[poss_y][cur_x + 1] - self.Map.elevations[cur_y][cur_x]) for poss_y in possible_ys ] min_diff = min(diffs) min_diff_index = diffs.index(min_diff) next_y = possible_ys[min_diff_index] cur_x += 1 cur_y = next_y self.point.append((cur_x, cur_y)) return self.point if __name__ == '__main__': elevation_map = Map('elevation_small.txt') point = Pathfinder(elevation_map) draw_elevation_map = DrawMap(elevation_map, point.pathfinder_finalized()) draw_elevation_map.draw() draw_elevation_map.print_path(point.pathfinder_finalized()) pathfinder = Pathfinder(elevation_map)
73e88332d5ab130a10286bd1da8430e7dc50d04b
Ann050/create
/2020-05-28 定义一个求平方和的函数.py
480
3.875
4
#------------------------------------------------------------------------------- # Name: 定义一个求平方和的函数 # Purpose: # # Author: chenw_000 # # Created: 28/05/2020 # Copyright: (c) chenw_000 2020 # Licence: <your licence> #------------------------------------------------------------------------------- def square_of_sum(l): sum = 0 for x in l: sum = sum + x * x return sum print(square_of_sum([2,3,4]))
a3ec2b0a3bd6f1d9741dbe019eb7111d65838d30
Amissan/prepaConcours
/td1/expr/expr.py
1,007
3.9375
4
from fractions import Fraction def calcul(expr): pile=[] val1=0.0 val2=0.0 for e in expr: if e!="+" and e!="-" and e!="*" and e!="/": pile.append(Fraction(e)) else: try: val1=pile.pop() val2=pile.pop() except: return "false" if(e=="/"): if(Fraction (val1)==0): return "false" else: pile.append(Fraction(val2/val1)) else: if(e=="+"): pile.append(Fraction(val2+val1)) if(e=="-"): pile.append(Fraction(val2-val1)) if(e=="*"): pile.append(Fraction(val2*val1)) res=pile.pop() try: err=pile.pop() return "false" except: return Fraction(res) expression1=input().split() expression2=input().split() print(calcul(expression1)==calcul(expression2))
786038f6e5eb25f5597be10b814ebbfdb49718ab
FranckCHAMBON/ClasseVirtuelle
/Term_NSI/devoirs/4-dm2/Corrigé/S5/E9.py
1,514
3.609375
4
""" Prologin: Entraînement 2003 Exercice: 9 - Puzzle https://prologin.org/train/2003/semifinal/puzzle """ nb_lignes_pièce = nb_colonnes_pièce = 4 nb_lignes_puzzle = nb_colonnes_puzzle = 10 pièce = [] puzzle = [] for ligne in range(nb_lignes_pièce): entrée = list(map(int, list(input()))) pièce.append(entrée) for ligne in range(nb_lignes_puzzle): entrée = list(map(int, list(input()))) puzzle.append(entrée) def est_dans_le_puzzle(x, y): """ Renvoie si les coordonnées `x` et `y` sont dans les limites de la puzlle """ return (0 <= x < nb_lignes_puzzle )and (0 <= y < nb_colonnes_puzzle) def recherche_puzzle_correct(x_départ, y_départ): """ Retourne un booléen si la pièce est compatible avec le puzzle à partir du coordonnées `x_départ` `y_départ` """ for delta_x in range(4): for delta_y in range(4): if not est_dans_le_puzzle(x_départ+delta_x, y_départ+delta_y): return False if puzzle[x_départ+delta_x][y_départ+delta_y] == 1 and 1 == pièce[delta_x][delta_y]: return False return True puzzle_correct = False for ligne in range(nb_lignes_puzzle): for colonne in range(nb_lignes_puzzle): if puzzle_correct: break if puzzle[ligne][colonne] != puzzle[0][0]: if recherche_puzzle_correct(ligne, colonne): puzzle_correct = True print(1 if puzzle_correct else 0)
c7636372d827a7b3c98b181ca92dc2add492c5c0
queryharada/lesson
/p238-07.py
161
3.734375
4
N = 10 Sum = 0 K = 0 while (K < N): K = K + 1 Sum = Sum + K print('loop invariant:N({0}) < K({1}) = {2}'.format(K, N, K < N)) print('Sum = ', Sum)
b8bf41baa2f06240a50372ebd36717678605dafe
pvargos17/python_practice
/week_02/labs/03_variables_statements_expressions/Exercise_08.py
475
4.375
4
''' Celsius to Fahrenheit: Write the necessary code to read a degree in Celsius from the console then convert it to fahrenheit and print it to the console. F = C * 1.8 + 32 Output should read like - "27.4 degrees celsius = 81.32 degrees fahrenheit" NOTE: if you get an error, look up what input() returns! ''' def converter(var): c = var F = c * 1.8 + 32 return f"{c} degrees in celsius = {F} degrees fahrenheit" temp = 27.4 print(converter(temp))
0f77f2f030c7e1e07ef38e2cb37e0fc211f19017
campbellmarianna/Tweet-Generator
/2ndOrderMarkovChain.py
1,944
3.53125
4
from dictogram import Dictogram # Inspired by Alexander Dejeu from pprint import pprint import random from sample import * text = "one fish two blue fish fish red fish blue red fish END" texts_list = text.split() def make_higher_order_markov_model(order, data): """Creates a histogram""" markov_model = dict() for i in range(0, len(data)-order): window = tuple(data[i: i+order]) # Create the window print(f"Window: {window}") if window in markov_model: # Add to the dictionary print(f"**********What is being added:{data[i+order]}") markov_model[window].add_count([data[i+order]]) # We have to just append to the existing Dictogram else: markov_model[window] = Dictogram([data[i+order]]) return markov_model def generate_random_start(model): print("IN FUNCTION") print('MODEL: {}'.format(model)) for k, v in model.items(): # pprint(f"Key: {k}") pprint(f"Value: {v}") for inner_key, inner_value in v.items(): if inner_key == 'END': seed_word = 'END' while seed_word == 'END': seed_word = non_uniform_sample(v) # break #seed_word = 'FOUND' return (k[1],seed_word) def generate_random_sentence(length, markov_model): current_word = generate_random_start(markov_model) print("I'm getting the current word") sentence = [current_word] for i in range(0, length): current_dictogram = markov_model[current_word] random_weighted_word = current_dictogram.return_weighted_random_word() current_word = random_weighted_word sentence.append(current_word) sentence[0] = sentence[0].capitalize() return ' '.join(sentence) + '.' return sentence model = make_higher_order_markov_model(2, texts_list) pprint(generate_random_start(model)) # pprint(generate_random_sentence(5, model))
e0c87b750ca3fe8871aa2512269da40bf2f6540c
Rnazx/Assignment-08
/Q1.py
3,956
3.796875
4
import library as rands import matplotlib.pyplot as plt import math figure, axes = plt.subplots(nrows=3, ncols=2)#define no. of rows and collumns RMS = [] Nroot = [] l = 100# no. of iterations N = 250# start from N=250 i=1 while (i<=5): print("************************************************************************************************************") print(" For Steps = "+str(N)+" and Number of walks = 5 ") print("************************************************************************************************************") X, Y, rms, avgx, avgy, radialdis = rands.randomwalk(l, N) print("The root mean square distance = ", rms) print("Average displacement in the x direction = ", avgx) print("Average displacement in the y direction = ", avgy) print("The Radial distance R = ", radialdis) RMS.append(rms) Nroot.append(math.sqrt(N)) k=u=0 if (i<3) : u=0 k=i-1 elif(i==3 or i==4) : u=1 k=i-3 else : u=2 k=0 for j in range(5): axes[u,k].set_xlabel('X') axes[u,k].set_ylabel('Y') axes[u,k].grid(True) axes[u,k].set_title("No. of steps = "+ str(N)) axes[u,k].plot(X[j],Y[j]) N +=250 i+=1 plt.figure() plt.title("RMS distance vs root of N plot for different number of steps starting from 250 ") plt.ylabel('RMS distance') plt.xlabel('squareroot of N') plt.plot(Nroot, RMS) plt.grid(True) plt.show() '''************************************************************************************************************ For Steps = 250 and Number of walks = 5 ************************************************************************************************************ The root mean square distance = 15.629352039696183 Average displacement in the x direction = 2.880434476082775 Average displacement in the y direction = -1.2758385256133062 The Radial distance R = 3.1503439041548127 ************************************************************************************************************ For Steps = 500 and Number of walks = 5 ************************************************************************************************************ The root mean square distance = 22.76072031959625 Average displacement in the x direction = 0.7067189887553609 Average displacement in the y direction = 2.151122020124929 The Radial distance R = 2.2642388731169145 ************************************************************************************************************ For Steps = 750 and Number of walks = 5 ************************************************************************************************************ The root mean square distance = 26.504581980149055 Average displacement in the x direction = 1.2664351771738056 Average displacement in the y direction = -0.349450693936544 The Radial distance R = 1.3137632379831536 ************************************************************************************************************ For Steps = 1000 and Number of walks = 5 ************************************************************************************************************ The root mean square distance = 32.50692594653746 Average displacement in the x direction = 4.3253278465174425 Average displacement in the y direction = -1.743836441343079 The Radial distance R = 4.663628041987837 ************************************************************************************************************ For Steps = 1250 and Number of walks = 5 ************************************************************************************************************ The root mean square distance = 33.981880998320044 Average displacement in the x direction = -0.4284515473756484 Average displacement in the y direction = 1.4508808279631595 The Radial distance R = 1.5128205132796326'''
a17d8f997943be292fab12a66b9a2994c997d000
ShruBal09/Python-Combat
/Extended_game.py
12,563
3.75
4
# coding: utf-8 # !/usr/bin/env python """ The Extended game program implements medics and expanded army, it generates a 2 Player/Commander game that allows the user to pick which player he wants to use first to build his army. An army can consist of a maximum of 10 units that can be purchased in the range of $1 to $3 per unit, a commander can chose how many units he wants to purchase (max 10). There are 5 types of units available, Archers ($1), Soldiers ($1), Knights ($1), Siege Equipment ($2) and Wizards ($3), where Archers are good against Soldiers but are terrible against Knights. Soldiers are good against Knights but can’t win against Archers. Knights beat Archers, but fall short against Soldiers. Siege Equipment win against everyone except Knights and Wizards. Wizard can beat anything, but they can’t dodge Archer arrows. If a unit comes up against a unit of the same type, both lose. After each round, the loser will be removed from the battle field and the fight continues with the winner of the previous round and the next in line of army of the losing commander of previous round. If the losing commander has enough balance after purchasing units (balance>0), then medic will be used to revive the lost army unit, at the cost of $1 for each revival, and the unit is added to the back of the army.The game continues until a commander is left with no army, the winner of the last round is declared the winner. If the last round ends in a tie, the commander having an army remaining is declared winner. If both commanders have no army left, the battle is declared draw.""" """The following module is used to provide color and bold formatting to the output printed on screen. Reference in documentation.""" from colorama import * init() ''' The matrix denotes who wins over the other, where 0 denotes Archer, 1 denotes Soldier, 2 denotes Knight, 3 denotes Siege Equipment, 4 denotes Wizard and 5 denotes a tie. Hence game_matrix[i][j] would denote who will win the match between i and j, ex: match between Archer(0) and Soldier(1) would be won by Archer(0)''' game_matrix = [[5, 0, 2, 3, 0], [0, 5, 1, 3, 4], [2, 1, 5, 2, 4], [3, 3, 2, 5, 4], [0, 4, 4, 4, 5]] ''' The class commander is used to define and store the army and cash balance for each player. The functions are used to add and remove units in the army and update the cash balance.''' class Commander: """ The init function initialises 3 variables, 1.To store the amount in $ available with the commander, 2.The army the commander has built, as a list, 3.A dictionary that holds the name of the unit corresponding to the number assigned to them, mostly used for screen display. """ def __init__(self): self.cash_balance = 10 self.army = [] self.units = {0: 'Archer', 1: 'Soldier', 2: 'Knight', 3: 'Siege Equipment', 4: 'Wizard'} ''' The purchase_units function adds units to the commanders army until the cash balance is available, i.e., it is greater than 0 or till the user wishes to add units, whichever is earlier. With each unit purchase, it reduces $1 from the commander's balance. In case the user enters a wrong input for a choice, it repeats the menu until they enter a valid input, after indicating an error message.''' def purchase_units(self): choice = 1 while choice == 1 and self.cash_balance > 0: print("") print("You may purchase one unit at a time, Archer, Soldier or Knight units cost $1," " Siege Equipment unit costs $2 and Wizard unit cost $3") print(Fore.RED + Style.BRIGHT + "Your Current balance is ", str(self.cash_balance) + Style.RESET_ALL) print("Units: \n 1.Archer\n 2.Soldier\n 3.Knight\n 4.Siege Equipment\n 5.Wizard") unit_chosen = input("Enter your choice (1/2/3/4/5): ") ''' Using if else conditions to ensure that the input from user is only numeric and either 1,2,3,4 or 5''' if unit_chosen.isnumeric(): unit_chosen = int(unit_chosen) if (unit_chosen >= 1) and (unit_chosen <= 3): self.cash_balance -= 1 elif unit_chosen == 4: self.cash_balance -= 2 elif unit_chosen == 5: self.cash_balance -= 3 else: print(Fore.RED + "Invalid choice!!" + Style.RESET_ALL) continue else: print(Fore.RED + "Invalid choice!!" + Style.RESET_ALL) continue self.army.append(unit_chosen - 1) print(Fore.RED + Style.BRIGHT + "Your Current balance is ", str(self.cash_balance) + Style.RESET_ALL) if self.cash_balance == 0: print("You can't purchase any further units") break else: ''' Using if else conditions to ensure that the input from user is only numeric and either 1 or 2''' while True: choice = input("Do you want to continue purchasing? 1.Yes 2.No (1/2):") if choice.isnumeric(): choice = int(choice) if choice == 1 or choice == 2: break else: print(Fore.RED + "Invalid Choice!!" + Style.RESET_ALL) else: print(Fore.RED + "Invalid Choice!!" + Style.RESET_ALL) ''' The function remove_unit is used to remove the unit in the front of the army if it has been defeated, if and only if there are any units to remove, i.e., the length of the army list is greater than 0. After removing/ popping the unit, it checks if the commander has enough balance to use the medic, if balance is more than 0, then the lost unit is revived and added to the back of his army at the cost of $1, i.e.,his balance reduces by 1. If balance is insufficient, no action is taken. After this process, it returns the length of the list, if it is greater than 0, or else it returns -1, to indicate that the list does not have elements to pop.''' def remove_unit(self, name): flag = 0 if len(self.army) > 0: removed_item = self.army.pop(0) if self.cash_balance > 0: print("Medic used to revive", self.units[removed_item]) self.army.append(removed_item) self.cash_balance -= 1 print(self.units[removed_item], " has been added to ", name, "army at the end") print(Fore.RED + Style.BRIGHT + "Available Balance is ", str(self.cash_balance) + Style.RESET_ALL) else: print("Not enough cash balance to revive") flag = 1 if flag: return len(self.army) else: return -1 ''' The combat function forms the main logic of the battle, it checks the front of the army for both the commanders with the game_matrix constructed above to see who wins, based on the unit that wins, the remove_unit function is called for the losing commander, to remove the unit at the front of his army, the result is printed on the screen and the battle continues to the next round, until there are no more units left in any one of the commander's army, correspondingly, the other commander is declared the winner of the game, who happens to be the winner of the last round as well. In case of a tie, in a battle round, units at the front of the army for both the commanders are removed, using remove_unit. If there is a tie in the last round, it is resolved by determining which commander has units left in his army, if both commanders are stranded, with empty armies, the game is declared a tie.''' def combat(): flag = 1 flag1 = 1 winner = None while flag and flag1: print("\n------------------------------------") print(Fore.CYAN + Style.BRIGHT + player1.units[player1.army[0]], " VS ", player2.units[player2.army[0]] + Style.RESET_ALL) if player1.army[0] == game_matrix[player1.army[0]][player2.army[0]]: winner = "Player1" print(Fore.YELLOW + Style.BRIGHT + "Round Winner: ", winner + Style.RESET_ALL) flag = player2.remove_unit("player2") elif player2.army[0] == game_matrix[player1.army[0]][player2.army[0]]: winner = "Player2" print(Fore.YELLOW + Style.BRIGHT + "Round Winner: ", winner + Style.RESET_ALL) flag = player1.remove_unit("player1") elif game_matrix[player1.army[0]][player2.army[0]]: winner = "No One" print(Fore.YELLOW + Style.BRIGHT + "Round Winner: ", winner, "\nIt's a Tie" + Style.RESET_ALL) flag = player1.remove_unit("player1") flag1 = player2.remove_unit("player2") if winner == "No One": if (flag > 0) and flag1 == 0: winner = "Player1" elif (flag1 > 0) and flag == 0: winner = "Player2" else: winner = "No One Its a tie" print("") print(Fore.YELLOW + Style.BRIGHT + "Winner of the Combat is :", winner + Style.RESET_ALL) return 0 # Create 2 objects for the class commander for the 2 players of the game player1 = Commander() player2 = Commander() '''Displays a menu for the 2 commanders to choose their armies. A choice is given to determine whether commander 1 wants to pick first or commander 2, Based on their choice, the commander's purchase_units function is called followed by the other commander. The menu repeats itself if the user entered any value other than 1 or 2, after displaying an error message. Once the units are picked the combat function is called and the game begins.''' print("Welcome to combat game!") while True: playerChoice = input("Choose Player:\n 1.Player1\n 2.Player2 \n (1/2): ") print("") ''' Using if else conditions to ensure that the input from user is only numeric and either 1 or 2''' # if user chose player 1 assign units for player1 if playerChoice.isnumeric(): playerChoice = int(playerChoice) if playerChoice == 1: print("Player", playerChoice, "Assign Units") player1.purchase_units() print("") print(Fore.CYAN + Style.BRIGHT + "Your army is " + Style.RESET_ALL) # print the army built using the units dictionary with its key as army elements for i in range(len(player1.army)): print(player1.units[player1.army[i]]) # Now let player 2 assign their units print("") print("Player", playerChoice + 1, "Assign Units") player2.purchase_units() print("") print(Fore.CYAN + Style.BRIGHT + "Your army is " + Style.RESET_ALL) # print the army built using the units dictionary with its key as army elements for i in range(len(player2.army)): print(player2.units[player2.army[i]]) break # if user chose player 2 assign units for player2 elif playerChoice == 2: print("Player", playerChoice, "Assign Units") player2.purchase_units() print("") print(Fore.CYAN + Style.BRIGHT + "Your army is " + Style.RESET_ALL) # print the army built using the units dictionary with its key as army elements for i in range(len(player2.army)): print(player2.units[player2.army[i]]) # Now let player 1 assign their units print("") print("Player", playerChoice - 1, "Assign Units") player1.purchase_units() print("") print(Fore.CYAN + Style.BRIGHT + "Your army is " + Style.RESET_ALL) # print the army built using the units dictionary with its key as army elements for i in range(len(player1.army)): print(player1.units[player1.army[i]]) break else: print(Fore.RED + "Invalid Player!!" + Style.RESET_ALL) else: print(Fore.RED + "Invalid Player!!" + Style.RESET_ALL) print("") print("Game Begins!") # call combat function combat() key = input("Press enter to exit!")
1484ac000332ca88c56a3c6775c846572a68ef1e
salonikalsekar/Python
/programs/compute.py
184
4.21875
4
# Problem Description # The program takes a number n and computes n+nn+nnn. # Problem Solution n = int(input("Enter the number: ")) print(n + n**2 + n**3) # time complexity -> O(1)
bc619189eb27000a6d84f9734b46947aa4a904db
arieldeveloper/Salary-Predictor
/salary_project.py
1,718
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 25 10:46:15 2018 @author: arielchouminov """ # Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('/Users/arielchouminov/Desktop/Machine-learning/Part 2 - Regression/Section 4 - Simple Linear Regression/Simple_linear_Regression/Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" #Linear regression model being applied to the sets of data we have from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) #Predicting the test set results y_pred = regressor.predict(X_test) #Visualizing the training set results plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train,regressor.predict(X_train), color = 'blue') plt.title('Salary based on Experience (training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() #Visualizing the Test set results plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train,regressor.predict(X_train), color = 'blue') plt.title('Salary based on Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
b112f6d620e7220e2ad38b90214f2d8fdfd81caa
roiei/algo
/leet_code/350. Intersection of Two Arrays II.py
1,359
3.5
4
import time from util.util_list import * from util.util_tree import * import copy import collections from typing import List class Solution: def intersect(self, nums1: [int], nums2: [int]) -> [int]: if len(nums1) > len(nums2): long = nums1 short = nums2 else: long = nums2 short = nums1 res = [] for i, num in enumerate(short): if num in long: res += long.pop(long.index(num)), return res def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: i = j = 0 if len(nums1) > len(nums2): long, short = nums1, nums2 else: long, short = nums2, nums1 res = [] while i < len(long) and j < len(short): print(long[i], short[j]) if long[i] == short[j]: res += long[i], j += 1 i += 1 return res stime = time.time() #print([1,2] == Solution().intersect([2,1], [1, 2])) print([4,9] == Solution().intersect([4,9,5], [9,4,9,8,4])) print([1] == Solution().intersect([2,1], [1,1])) #print([2,2] == Solution().intersect([1,2,2,1], [2,0,2])) print('elapse time: {} sec'.format(time.time() - stime))
1772822afb1897d64761a1ef1975bdb3269b7ec6
shouya/thinking-dumps
/discrete-optimization-2/week4-tsp/solver.py
1,515
3.6875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import math from collections import namedtuple Point = namedtuple("Point", ['x', 'y']) def length(point1, point2): return math.sqrt((point1.x - point2.x)**2 + (point1.y - point2.y)**2) def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount+1): line = lines[i] parts = line.split() points.append(Point(float(parts[0]), float(parts[1]))) # build a trivial solution # visit the nodes in the order they appear in the file solution = range(0, nodeCount) # calculate the length of the tour obj = length(points[solution[-1]], points[solution[0]]) for index in range(0, nodeCount-1): obj += length(points[solution[index]], points[solution[index+1]]) # prepare the solution in the specified output format output_data = '%.2f' % obj + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data import sys if __name__ == '__main__': import sys if len(sys.argv) > 1: file_location = sys.argv[1].strip() with open(file_location, 'r') as input_data_file: input_data = input_data_file.read() print(solve_it(input_data)) else: print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/tsp_51_1)')
6420dcdd387bae72fa29696f7949cc47c59c3468
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/ddnami001/question1.py
245
4.15625
4
#Amitha Doodnath #DDNAMI001 #24/03/2014 #Programme to print user defined rectangle height=eval(input("Enter the height of the rectangle:\n")) width=eval(input("Enter the width of the rectangle:\n")) for i in range(height): print("*"*width)
b8f704d33c73a16879e71f283fe019726bb6e5b0
fernandojsmelo/Python---Curso-Completo
/exercicio5_16.py
606
3.8125
4
valor = float(input("Digite o valor a pagar: ")) cedulas = 0 atual = 100 apagar = valor while True: if atual <= apagar: apagar -= atual cedulas += 1 else: print("%d cedula(s) de R$ %3.2f"%(cedulas,atual)) if apagar == 0: break if atual == 100: atual = 50 elif atual == 50: atual = 20 elif atual == 20: atual = 10 elif atual == 10: atual = 5 elif atual == 5: atual = 1 elif atual == 1: atual = 0.50 elif atual == 0.50: atual = 0.10 elif atual == 0.10: atual = 0.05 elif atual == 0.05: atual = 0.02 elif atual == 0.02: atual = 0.01 cedulas = 0
0bb1300aee1927315f6f9f555624d1e80e661ed8
josivantarcio/Desafios-em-Python
/Desafios/desafio041.py
398
3.703125
4
from datetime import date ano = int(input('Digite o ano de nascimento: ')) anoCorrente = date.today().year idade = anoCorrente - ano if(idade <= 9): print('Atleta \033[1;34mMirim') elif(idade <= 14): print('Atleta \033[1;34mInfantil') elif(idade <= 19): print('Atleta \033[1;34mJunior') elif(idade <= 25): print('Atleta \033[1;34mSênior') else: print('Atleta \033[1;34mMaster')
05096f0731e487efe6c54a5a943a06048d0b4f90
lalitzz/DS
/Sequence4/Algorithm-toolbox/Week4/binarysearch-1.py
1,291
3.71875
4
# Uses python3 import sys from random import randint def binary_search(a, x): left, right = 0, len(a) # write your code here while left < right: mid = (right + left) // 2 if a[mid] == x: return mid elif a[mid] > mid: right = mid - 1 else: left = mid + 1 return -1 def linear_search(a, x): for i in range(len(a)): if a[i] == x: return i return -1 def main(): count = 0 while True: a = [] b = [] for i in range(10): d1 = randint(1, 9) d2 = randint(1, 9) a.append(d1) b.append(d2) a = set(a) b = set(b) a = list(a) b = list(b) print(a) print(b) a_r = '' b_r = '' for x in b: a_r += str(binary_search(a, x)) for x in b: b_r += str(linear_search(a, x)) if a_r != b_r: print(a) print(b) print(a_r) print(b_r) break count += 1 if count == 100000: break if __name__ == '__main__': # input = sys.stdin.read() # data = list(map(int, input.split())) # n = data[0] # m = data[n + 1] # a = data[1 : n + 1] # for x in data[n + 2:]: # # replace with the call to binary_search when implemented # print(binary_search(a, x), end = ' ') main()
2a1095dbc8bdeae8559675f6740025c65b0bddd4
zilunzhang/Machine-Learning-and-Data-Mining
/a2/q2_0.py
963
3.84375
4
''' Question 2.0 Skeleton Code Here you should load the data and plot the means for each of the digit classes. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt def plot_means(train_data, train_labels): means = [] for i in range(0, 10): i_digits = data.get_digits_by_label(train_data, train_labels, i) # Compute mean of class i # print(i_digits.shape) mean_digit = np.mean(i_digits, 0) mean_digit = np.reshape(mean_digit,(8,8)) means.append(mean_digit) # Plot all means on same axis # print("mean's shape is: {}".format(np.reshape(means, (8,8,10)).shape)) all_concat = np.concatenate(means, 1) plt.imshow(all_concat, cmap='gray') plt.show() if __name__ == '__main__': train_data, train_labels, _, _ = data.load_all_data_from_zip('a2digits.zip', 'data') plot_means(train_data, train_labels)
e785c986a47fd71bafccc100aaf02555bb1ef1b1
RakeshRameshDS/Programming-Interview-Preparation
/Trees And Graph/02. List of Depths.py
1,178
3.765625
4
""" Given a binary tree, design an algorithm which creates linked list of all nodes at each depth """ class LLNode: def __init__(self, data): self.data = data self.link = None class TNode: def __init__(self, data): self.data = data self.left = None self.right = None root = TNode(2) L1 = TNode(3) L2 = TNode(4) L3 = TNode(5) L4 = TNode(6) L5 = TNode(7) root.left = L1 root.right = L2 L2.left = L3 L3.left = L4 L1.left = L5 """ Tree Structure 2 / \ 3 4 / / 7 5 / 6 """ def listOfDepths(root): Q = [] list_res = []; ll = [] Q.append(root) Q.append(None) while Q is not None: ele = Q.pop(0) if ele is not None: ll.append(ele.data) if ele.left is not None: Q.append(ele.left) if ele.right is not None: Q.append(ele.right) else: if len(ll) == 0: break list_res.append(ll) ll = [] Q.append(None) return list_res LL = listOfDepths(root) print(LL)
5ebdfbfc359e550d7a6c5425c836c077aadac7fd
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/8. Nested Loops/Таблица Улама.py
582
3.90625
4
# Ширина таблицы Улама n = int(input()) # Кол-во чисел,о которым строится таблица max_val = int(input()) counter = 1 while counter <= max_val: is_prime = True if 0 == counter % 2 and counter != 2: is_prime = False for y in range(3, int(counter / 2), 2): if 0 == counter % y or not is_prime: is_prime = False break if is_prime: print('#', end="\t") else: print(".", end="\t") counter += 1 if 0 == counter % n: print("")
54679cad23b57c9ae35480c7ae2d409cc3b8f7e2
Kornflex28/iqfit-solver
/iqfit/board.py
2,277
3.609375
4
from itertools import product from .piece import Piece class Board: def __init__(self, width=10, height=5): self.width = width self.height = height self.shape = width, height self.current_board = {(x, y): None for x, y in product( range(self.width), range(self.height))} self.coordinates = set(self.current_board.keys()) def __str__(self): rep = f"Board(width={self.width}, height={self.height})" for y in range(self.height): rep += "\n" for x in range(self.width): if self.current_board[(x, y)] is not None: rep += self.current_board[(x, y)][0] else: rep += "*" return rep def __repr__(self): return f"Board(width={self.width}, height={self.height})" def get_empty_coordinates(self): return {(x, y) for (x, y), p in self.current_board.items() if p is None} def put_piece_on_board(self, piece: Piece): if piece.get_2D_coordinates().issubset(self.get_empty_coordinates()): for x, y in piece.get_2D_coordinates(): self.current_board[(x, y)] = piece.name else: print(f"Piece {piece.name} can't fit on board.") return self.current_board def from_2D_put_piece_on_board(self, name, coords_2D): if coords_2D.issubset(self.get_empty_coordinates()): for x, y in coords_2D: self.current_board[(x, y)] = name else: print(f"Piece {name} can't fit on board.") return self.current_board def get_possible_coordinates(self, piece: Piece): piece_transfomartions = piece.get_transformations() possible_coordinates = [] for coords in piece_transfomartions: p = Piece(piece.name, coords) for dx in range(self.width-p.width+1): for dy in range(self.height-p.height+1): dp = p.translate_piece(dx, dy) dp_2D_coords = dp.get_2D_coordinates() if dp_2D_coords.issubset(self.get_empty_coordinates()) and dp not in possible_coordinates: possible_coordinates.append(dp) return possible_coordinates
8c031b625e027f4ec7b2567861f994f038d34921
NuclearAck/pythonLearning
/struture/palindromic_num.py
161
3.78125
4
import re def find_num_palindromic(): s = "ab" p = ".*c" res = re.findall(p,s) return True if not res else False print(find_num_palindromic())
a046567e8eb772648ea27eee2ea64a46f313e1ca
danlucss/Cursoemvideo
/Mundo3/ex104.py
818
4.15625
4
"""Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante ‘a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt(‘Digite um n: ‘)""" def leiaInt(msg): ''' Função para imprimir na tela um número inteiro; :param msg: Retorna a mensagem desejada. :return: Caso o número informado seja inteiro, ela retorna o número, senão, ela entra em loop, até um número inteiro valido ser selecionado. ''' while True: a = str(input(msg)) if a.isnumeric(): return int(a) else: print(f'\033[35mErro. Válido apenas números inteiros.\033[m') n = leiaInt('Digite um número inteiro: ') print(f'O número informado foi {n}.')
19b75a94f1a8c1717fbd7600d0504b5194420982
M45t3rJ4ck/Student
/Primes.py
1,036
4.59375
5
# Create a new Python file in this folder called “Optional_task.py” # Create a program to check if a number inputted by the user is prime. # A prime number is a positive integer greater than 1, whose only factors are 1 and the number itself. # Examples of prime numbers are: 2, 3, 5, 7, etc. # Ask the user to enter an integer. # First check if the number is greater than 1. # If it is greater than 1, check to see if it has any factors besides one and itself. # i.e if there are any numbers between 2 and the number itself that can divide the number without any remainders # If the number is a prime number, print out the number and ' is a prime number!' # If the number is not a prime number, print out the number and ' is not a prime number' U_prime = int(input("Please enter a number to check if it is prime: ")) primed = () for x in range(2, U_prime): if (x % 2) == 0: primed = str(U_prime) + " isn't a prime number." + "\n" else: primed = str(U_prime) + " is a prime number." + "\n" print(primed)
43cadbb9d4c4cdb3a317b275dff3db2da1164b86
jchunf/NLP_Model
/fastText/src/utils/huffman.py
6,383
4.09375
4
from queue import PriorityQueue from typing import Dict, List class _Node(object): """node of huffman tree """ def __init__(self, num: int, weight: int): self._num = num self._weight = weight self._left_child = None self._right_child = None def add_child(self, type: int, child): """add child for node Args: type: 0 if left child, 1 if right child child: node of child """ if type == 0: self._left_child = child else: self._right_child = child def num(self) -> int: return self._num def left_child(self): return self._left_child def right_child(self): return self._right_child def weight(self) -> int: return self._weight def __lt__(self, o): if self.weight() <= o.weight(): return True return False class HuffmanTree(object): """huffman tree left child of every node following with 0 right child of every node following with 1 tree must have at least one node """ def __init__(self, labels: Dict[int, int] = None): """initialize huffman tree Args: labels: maps from label to occurrence time """ self._cnt = 0 self._label2num: Dict[int, int] = {} self._num2label: Dict[int, int] = {} self._path: Dict[int, List[int]] = {} if labels is None: return nodes = PriorityQueue() for x in labels: self._label2num[x] = self._cnt self._num2label[self._cnt] = x nodes.put(_Node(self._cnt, labels[x])) self._cnt += 1 while nodes.qsize() >= 2: a = nodes.get() b = nodes.get() c = _Node(self._cnt, a.weight() + b.weight()) self._cnt += 1 c.add_child(0, a) c.add_child(1, b) nodes.put(c) self._root = nodes.get() self._DFS(-1, self._root) def _DFS(self, par: int, current: _Node): if current is None: return if par == -1: self._path[current.num()] = [current.num()] else: self._path[current.num()] = self._path[par] + [current.num()] self._DFS(current.num(), current.left_child()) self._DFS(current.num(), current.right_child()) def get(self, label: int) -> (List[int], List[int]): """get path of node in huffman tree Args: label: label of wanted node Returns: positive node in which node get left negative node in which node get right """ pos_nodes = [] neg_nodes = [] current = self._root for i in range(1, len(self._path[self._label2num[label]])): x = self._path[self._label2num[label]][i] if current.left_child().num() == x: pos_nodes.append(self._path[self._label2num[label]][i-1]) current = current.left_child() else: neg_nodes.append(self._path[self._label2num[label]][i-1]) current = current.right_child() return pos_nodes, neg_nodes def find(self, probability: List[float]) -> int: """get node following given path Args: probability: probability of getting left child on every node Returns: end label of path """ current: _Node = self._root while True: current_num = current.num() if probability[current_num] >= 0.5: child = current.left_child() else: child = current.right_child() if child is None: if current_num in self._num2label: return self._num2label[current_num] else: return -1 current = child def dump(self, path: str): """dump parameters of huffman tree Args: path: path to dump parameters """ with open(path, 'w') as f: f.write(str(self._root.num()) + '\n') f.write(str(self._cnt) + '\n') rec: List[str] = ["" for i in range(self._cnt)] stack: List[_Node] = [self._root] while len(stack) != 0: x = stack[-1] stack.pop() if x is None: continue left_child = x.left_child() right_child = x.right_child() if left_child is None: left_child = _Node(-1, 0) if right_child is None: right_child = _Node(-1, 0) rec[x.num()] = "%d %d %d" % ( x.weight(), left_child.num(), right_child.num()) stack.append(x.left_child()) stack.append(x.right_child()) for s in rec: f.write(s + '\n') for label in self._label2num: f.write("%s %d\n" % (label, self._label2num[label])) def load(self, path: str): """load parameters from given file Args: path: path of parameters """ nodes = {} nodes[-1] = None childs = [] with open(path, 'r') as f: line_count = 0 for line in f: current = line.strip() if line_count == 0: self._root = int(current) elif line_count == 1: self._cnt = int(current) elif line_count <= self._cnt + 1: param = current.split() cnt = line_count - 2 nodes[cnt] = _Node(cnt, int(param[0])) childs.append( [cnt, int(param[1]), int(param[2])]) else: param = current.split() self._label2num[int(param[0])] = int(param[1]) self._num2label[int(param[1])] = int(param[0]) line_count += 1 for p in childs: par = nodes[p[0]] par.add_child(0, nodes[p[1]]) par.add_child(1, nodes[p[2]]) self._root = nodes[self._root] def __len__(self): return self._cnt
871c62de1d66b8b10f477fa0dfd1ef15a174129a
Busiky/Tasks
/Triangle numbers and words/solution.py
476
3.828125
4
import string def triangle(item): abc = string.ascii_uppercase if item.isdigit(): number = int(item) else: number = sum([abc.index(letter) + 1 for letter in item.upper()]) count = 0 triangle_number = 0 while triangle_number < number: count += 1 triangle_number = count * (count + 1) // 2 if triangle_number == number: return count return False if __name__ == '__main__': print(triangle(input()))