blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8ca179e9dbd1210a0190cf7a8e8b1610b893efdb
JarryShaw/PyNTLib
/Homework Codes/2017:02:23/SKT_1-8-2 Eratosthenes_Sieve.py
895
3.578125
4
# -*- coding: utf-8 -*- #厄拉托塞師篩法 #返回10,000以內正整數的所有素數(默認情況) ''' print (lambda n: filter(lambda x: all(map(lambda p: x%p!=0, xrange(2,int(__import__('math').sqrt(x)+1)))), xrange(2, n)))(10000) ''' import math def eratosthenesSieve(N=10000): set = [1]*(N+1) #用於存儲N(默认为10000)個正整數的表格/狀態;其中,0表示篩去,1表示保留 for index in xrange(2,int(math.sqrt(N))): #篩法(平凡除法) if set[index] == 1: ctr = 2 while index * ctr <= N: set[index*ctr] = 0 #將index的倍數篩去 ctr += 1 rst = [] for ptr in xrange(2,N): #獲取結果 if set[ptr] == 1: rst.append(ptr) ptr += 1 return rst if __name__ == '__main__': print eratosthenesSieve()
815c64de916e4f72c8fdc9c80a648c9562f23ee7
EvilBorsch/Sort_Vstavkami
/solution.py
1,130
3.953125
4
import random # чтобы можно было рандомит arr = [] # объявил массив def index_min(i, arr): # функция которая находит индекс минимального элемента index = i for i in range(i, arr.__len__()): # веду поиск от i-того элемента, до конца массива if arr[i] < arr[index]: index = i return index for i in range(0, 10): # заполняю массив случайными числами(чтобы удобней было) arr.append(random.randint(1, 100)) print("Массив заполненный рандомной хуйней: ", arr) for i in range(0, arr.__len__()): min_index = index_min(i,arr) # нахожу индекс минимального элемента в промежутке от i того элемента до конца массива arr[i], arr[min_index] = arr[min_index], arr[i] # меняю местами i-тый элемент и минимальный элемент print(f"Готово,лол,кек,чебурек: ", arr)
1c49d4857174643f4ec34dfb9326c05779a10881
david-wm-sanders/uswacs-1-iy1d402-a1-zipcrack
/zipcrack.py
972
3.578125
4
import sys import zipfile from pathlib import Path def read_word_list(wrd_fp): pws = [] with wrd_fp.open("rb") as f: for pw in f.read().split(b"\n"): pws.append(pw) return pws def crack_zip(zip_fp, word_list): with zipfile.ZipFile(zip_fp) as z: for pw in pws: try: z.extractall(path="extracted", pwd=pw) print(f"The password is '{pw}' - writing file to disk...") break except RuntimeError: print(f"The password is not '{pw}'") continue if __name__ == '__main__': try: zip_arg = sys.argv[1] wrd_arg = sys.argv[2] except IndexError: print("Usage: zipcrack.py ZIPFILE WORDLIST") sys.exit(1) zip_fp = Path(__file__).parent / f"{zip_arg}" wrd_fp = Path(__file__).parent / f"{wrd_arg}" pws = read_word_list(wrd_fp) # print("Wordlist:", pws) crack_zip(zip_fp, pws)
a026c856fe7d80f9f4247507459439872a622cdd
nanovisor/python
/salary_per_hour.py
346
3.734375
4
# just comment print "**************************************************" print "This program counts salary per hour [rate is 2.75$]" hours = raw_input("Please enter hours:") rate = 2.75 gross = float(hours) * rate print "Your earn " + str(gross) + "$ per " + hours + " hour(s)" print "**************************************************"
8f2cb0e64311b79480aee72bf34c3827e388c2fc
jiajiabin/python_study
/day01-10/day06/05_闭包函数2.py
1,090
4.0625
4
import datetime import time # 闭包函数往往通过返回值,返回一些附加的功能 def print_num(): for i in range(1, 101): time.sleep(0.1) # 线程休眠,程序等待0.1秒,什么都不做 print(i) # 计算这个函数执行需要多久的耗时 # 写一个闭包函数完成这个功能 def count_time(): def do_count_time(f): # f = print_num # 获取函数f执行之前的时间 time = datetime.datetime.now() f() # 执行print_num # 获取执行完毕的时间 time2 = datetime.datetime.now() return (time2 - time).total_seconds() return do_count_time # 外面这个函数,就是【装饰器】的名字。 # x = count_time() # print(x(print_num)) t = count_time()(print_num) print(t) # def do_count_time(f): # f = print_num # # 获取函数f执行之前的时间 # time = datetime.datetime.now() # f() # # 获取执行完毕的时间 # time2 = datetime.datetime.now() # return (time2 - time).total_seconds() # # # t = do_count_time(print_num)
9285343185b25208eaeb2e0815797e53f63b0152
ATLS1300/pc04-generative-section11-ella-lagomarsino
/pc04_generativeart Lagomarsino, Ella peace sign
2,884
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 17 09:42:51 2021 @author: ellalagomarsino """ """ Created on Thu Sep 15 11:39:56 2020 PC04 start code @author: Ella Lagomarsino ********* HEY, READ THIS FIRST ********** My code uses three turtles to create red, white, and blue horizontal stripes as the background a peace sign in the middle, and a star. My code represents USA. The peace sign repesent the hope for peace across America. """ # You must make 2 turtle variables # You must use 2 for loops (a nested for loop counts as 2!) # You must use at least 1 random element (something from the random library) # Don't forget to comment your code! (what does each for loop do? What does the random function you'll use do?) # =============== ADD YOUR CODE BELOW! ================= import turtle import math import random turtle.colormode(255) # turtle.tracer(0) # uncomment this line to turn off turtle's animation. You must update the image yourself using panel.update() (line 42) # Create a panel to draw on. panel = turtle.Screen() w = 700 # width of panel h = 700 # height of panel panel.setup(width=w, height=h) #600 x 600 is a decent size to work on. # background stripes size and colors pensize=200 backgroundstripes = ("firebrick3","dodgerblue4","oldlace") panel.bgcolor("firebrick3") #setting up the background color background=turtle.Turtle() #Creating background stripes background.up() background.setx(w/2) background.sety((h/2)-(pensize/2)) background.left(180) #Forloop that creates background stripe colors for color in backgroundstripes: background.pencolor(color) background.pensize(pensize) background.down() background.forward(w) background.up() background.backward(w) background.left(90) background.forward(pensize) background.right(90) # making peace sign circle = turtle.Turtle() # radius of the circle r = 160 circle.up() circle.sety(-r) circle.pensize(20) #For random peace sign colors circlecolors=("lightskyblue","ghostwhite","lightskyblue2") circle.color(random.choice(circlecolors)) #finish making peace sign circle.down() circle.circle(r) circle.left(90) circle.forward(r) circle.right(130) circle.forward(r) circle.up() circle.backward(r) circle.left(260) circle.down() circle.forward(r) circle.backward(r) circle.right(130) circle.forward(r) #create a star star=turtle.Turtle() star.pensize(10) #star pen color star.pencolor("lightgoldenrodyellow") star.up() star.goto(-350,150) star.pendown() for i in range(6): star.forward(200) star.right(144) star.penup() star.goto(-300,150) star.pendown() # panel.update() # uncomment this if you've turned off animation (line 26). I recommend leaving this outside of loops, for now. # =================== CLEAN UP ========================= # uncomment the line below when you are finished with your code (before you turn it in) # turtle.done()
18926f094327f2ef0f091367975f810da811b42b
deekshasowcar/python
/copystring.py
108
3.984375
4
def string(str,n): result=" " for i in range(n): result=result+str return result print(string("abc",3)
f697502698767d63d35ef175cb38b1307a1c714f
pbarton666/learninglab
/data_sci_mini/py_pandas_series_1.py
910
3.78125
4
#py_pandas_series_1.py """a first look at pandas""" #creating a series import pandas as pd data=[10, 20, 30, 40] ser=pd.Series(data=data) print(ser) print() #addressing elements ser[0]='some string' ser[1]=(1,2,3) print(ser) print() #managing elements value_3=ser.pop(3) print(value_3) print() print(ser.get(666, 'nope')) print() print(ser) print() #searching in versus isin() print(2 in ser) print(666 in ser) print() look_for=[ (1,2,3), 30, 50] ser.isin(look_for) print() print(ser.isin( [0] )) print(ser.isin( (1,) ) ) print() ###managing indices data=[10, 20, 30, 40] ser=pd.Series(data=data) print(ser.index) print() ser.index=('dog', 'cat', 'bear', 'anteater') print(ser.index) print(ser.iloc[1]) print() x=1 #quick and dirty plotting import matplotlib.pyplot as plt #data visualization data=[10, 20, 30, 40] ser=pd.Series(data=data) fig, ax = plt.subplots() ax.plot(ser) plt.show() z=1
4f06eee4ea1e56e952cabd995649f1d5649d484c
IanBuceta/Programacion2
/tareas/Clase 4/ejercicio_5.py
1,641
3.75
4
from os import system productosCosmeticos = list() preciosUnitarios = list() ventas = dict() def cargarproductos(): while(True): system("cls") productosCosmeticos.append(input("Ingrese nombre del producto: ").lower()) preciosUnitarios.append(float(input("Ingrese costo unitario: "))) if input("¿Desea seguir ingresando elementos?: ").lower() == "no": break def realizarventas(): numeroFactura = 1 while(True): system("cls") for (i, productoCosmetico) in enumerate(productosCosmeticos): print("{}. {}. Precio unitario: {:.2f} ".format(i, productoCosmetico,preciosUnitarios[i])) while (True): index = int(input("Seleccione el codigo producto deseado: ")) if index < len(productosCosmeticos): break cantidad = int(input("Ingrese cantidad deseada: ")) ventas[numeroFactura] = (productosCosmeticos[index], preciosUnitarios[index], cantidad) numeroFactura += 1 if input("¿Desea seguir comprando?: ").lower() == "no": break def mostrarventas(): total = 0 subtotal = 0 system("cls") for key in ventas.keys(): datosVenta = ventas[key] subtotal = datosVenta[1] * datosVenta[2] total += subtotal print("Numero de factura: {}. Nombre del producto: {}. Precio unitario:{:.2f}. Cantidad: {}.Subtotal: {:.2f}".format(key, datosVenta[0], datosVenta[1], datosVenta[2], subtotal)) subtotal = 0 print("Total vendido: {:.2f}".format(total)) cargarproductos() realizarventas() mostrarventas() input()
9b6ef646912c34bd73fe2c228c3a52a745e1a1b3
geodimitrov/Python-Fundamentals-SoftUni
/Lists/Advanced/05. еlectron_distribution.py
385
3.765625
4
n_electrons = int(input()) distr_electrons = [] cell_position = 1 while n_electrons > 0: electrons_in_cell = 2 * cell_position ** 2 if n_electrons >= electrons_in_cell: distr_electrons.append(electrons_in_cell) else: distr_electrons.append(n_electrons) n_electrons -= electrons_in_cell cell_position += 1 print(distr_electrons)
623876deb66b1f9697a05188e5522e6df08588ad
Shayan3008/Numerical_Computing_Project
/newtonDD.py
3,116
4
4
# Python library for symbolic mathematics it gives function as sub symbols which make working with formulas ike 2x or sinx much more easier. import sympy as sp mainCount = 1 list1 = [] # values of x list2 = [] # values of fx list3 = [] # value of a0,a1,a2 list4 = [] x = sp.symbols('x') def addItemToTable(list4, count, list2): # where it will be printed out on the screeen. tempList = [] for i in range(len(list2)): if(i < count): tempList.append("{:.5f}".format(list2[i])) else: tempList.append("") list4.append(tempList) print("do u want to give values of f(X) or give a function\n") # choice given to the user to enter a function or enter the values directly. decis = int(input("1-value of fx 2-function ")) if(decis == 2): print("Enter the Function:") function = input() val = int(input("enter how many value of x to be inserted\n")) tableTempCount = val for i in range(val): k = float(input("enter values of x \n")) list1.append(k) if(decis == 1): functionvalue = float(input("enter value of fx")) list2.append(functionvalue) elif(decis == 2): symFunction = sp.sympify(function) # values of x being stored in the solFUNC solFunc = sp.N(symFunction.subs(x, k)) list2.append(solFunc) addItemToTable(list4, tableTempCount, list1) addItemToTable(list4, tableTempCount, list2) list3.append(list2[0]) temp = val while (val > 1): count2 = 0 count3 = mainCount for i in range(val-1): if(i == 0): # f(Xi+1)-f(Xi) takes place which is further divided by difference of x values to yield 1DD,and the whole process foloowws again to yeild 2DD,3DD etc. a = list2[i+1]-list2[i] b = list1[count3]-list1[count2] c = (a/b) list3.append(c) list2[i] = c else: count3 += 1 count2 += 1 a = list2[i+1]-list2[i] b = list1[count3]-list1[count2] c = (a/b) list2[i] = c mainCount += 1 val -= 1 tableTempCount -= 1 addItemToTable(list4, tableTempCount, list2) strs = '' for li in range(len(list4)-2): strs += str(li+1)+'DD\t' # Headings like 1dd ,2dd are being generated. print("x\ty\t"+strs) for i in range(len(list1)): for j in range(len(list4)): # Table in its proper format is being printed here. print(list4[j][i], end='\t') print('\n') x = 0.0 # Function value is being asked by the user on which we will generate the formula and insert its value to find the output. print("Enter the function value :") func = float(input()) print("P" + str(temp-1) + " = ") # formula for P(1/2/3..) is being generated in which funct value will be inserted and then finally x will store its value and printed out. for i in range(temp-1): c = 1.0 if(i == 0): x += list3[i] elif(i > 0): j = i-1 while(j >= 0): c = c*(func-list1[j]) j -= 1 k = list3[i]*c x += k print("The Ans is") print("{:.5f}".format(x))
5e7fbb80ccaa940024ad1506d6c8fe82859c7fe7
mtrentz/Misc-Projects
/challenges/4squares.py
484
3.5
4
from itertools import permutations """ My take on the challenge from: https://rosettacode.org/wiki/4-rings_or_4-squares_puzzle """ def test_equal(list): if sq1 == sq2 == sq3 == sq4: possibs.append(list) possibs = [] vals = [i for i in range(1,8)] # All permutations of these values perms = permutations(vals) for p in perms: sq1 = sum(p[0:2]) sq2 = sum(p[1:4]) sq3 = sum(p[3:6]) sq4 = sum(p[5:8]) test_equal(p) for c in possibs: print(c)
d08cf37c2481189498f85263c922ad4d0e73e6b5
kellymhli/code-challenges
/string-shift.py
538
3.734375
4
def shift_string(s, shifts): if not shifts: return s move = 0 for shift in shifts: if shift[0] == 0: #left move -= shift[1] else: move += shift[1] move %= len(s) if move < 0: s = s[move:] + s[:-move + 1] elif move > 0: s = s[-move:] + s[:-move] return s print(shift_string("abc", [[0,1], [1,2]])) # cab print(shift_string("acbdefg", [[1,1],[1,1],[0,2],[1,3]])) #efgabcd print(shift_string("mecsk", [[1,4],[0,5],[0,4],[1,1],[1,5]])) # kmecs
81ad7e2825d07bfbbab14140092b725a7cf1a2a3
MANOJPATRA1991/Data-Structures-and-Algorithms-in-Python
/Searching and Sorting/Sorting/Shell Sort/main.py
883
4.1875
4
def gap_insertion_sort(alist, start, gap): """ Perform insertion sort on sub lists of alist created with a gap Args: alist: List to sort start: Start index gap: """ for i in range(start+gap, len(alist), gap): current_val = alist[i] position = i while position >= gap and alist[position-gap] > current_val: alist[position] = alist[position-gap] position = position - gap alist[position] = current_val def shell_sort(alist): """ performs shell sort :param alist: a list """ sublist_count = len(alist) // 2 while sublist_count > 0: for num in range(sublist_count): gap_insertion_sort(alist, num, sublist_count) sublist_count = sublist_count // 2 alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] shell_sort(alist) print(alist)
10e0d07e8b69064d81a17d0c71e631aa6646e592
nandansn/pythonlab
/learnings/codingbat/warmup2/array_count9.py
172
3.515625
4
def array_count9(nums): countnine = 0; for num in nums: if num == 9: countnine = countnine + 1 return countnine print(array_count9([1,2,3,9,2,9,9]))
287239c934b584adf32ff3bec7fb190305e8aa1e
JoshuaGutie/python_basics
/chapter3/practice.py
208
3.71875
4
places = ['austin', 'georgetown', 'paris', 'london', 'new york'] print(places) places.sort() print(places) places.sort(reverse = True) print(places) places.reverse() print(places) places.sort() print(places)
52fcf7bf2443d764458d477f7e1d8308f6fcf558
LeBertrand/XRPS
/RockPaperScissors.py
3,875
3.828125
4
# Include some code that knows how to choose randomly. import random # define list of options handBeats = {'r':'s', 'p':'r', 's':'p'} hands = list(handBeats.keys()) # Variables determine whether cheats are accepted or treated as invalid input by chooseWinner. cheats_unlocked = {'shoot':False, 'clint':False} intro = 'Welcome to Rock, Paper, Scissors. Type q at any time to quit.' roundInstr = 'Type r, p or s to play a round of Rock, Paper, Scissors.\nrps> ' credits = '''Rock, Paper, Scissors coded by Shmuel Jacobs on May 23, for FTI Python club. Permission granted to FTI students to use and modify code. Thanks for playing.''' logo = r''' ^^^^^^^^^ (*** ***) ||| F T I ||| |\| |/| \\| ||---|| |// \\ ||---|| // \\ // \\ // ---''' clint_quotes = set(['Go ahead, make my day', 'Do you feel lucky punk?', 'make it four coffins', 'my mule don\'like getting scared']) # Define procedure for letting computer choose one play from a list of options. def computerPlay(moveChoices): # moveChoices is the list of choices to for computer to choose from. computerHand = random.choice(moveChoices) # Whoever asked for the computer's play can move one now, using the following value: return computerHand print('This line will never print. After "return", we leave the function') '''Define procedure for choosing winner based on two inputs, assuming first input is player's choice and second input is computer's. Return 1 for player wins, 0 for tie, -1 for computer wins.''' def chooseWinner(playerChoice, computerChoice): if( playerChoice == 'Time to load up.'): print('Go ahead. Make my day. You lose this one punk.') cheats_unlocked['shoot'] = True return -1 # Cheat options inserted here. Main gameplay logic begins by checking if input in hands. if( playerChoice == 'shoot' and cheats_unlocked['shoot']): return 1 if( playerChoice not in hands ): # invalid choice -- return error code -2 return -2 if(playerChoice == computerChoice): return 0 # If we reach this line, choices don't match. We would have hit 'return' # last line if they did match. if( handBeats[playerChoice] == computerChoice ): return 1 # The only way to reach this is if player doesn't win and doesn't tie. return -1 def showPrompt(prompt): print(prompt) # No return statement is necessary. Nothing will come back when this function is called. def showStandings(playerScore, ComputerScore): print('You\'re ', playerScore, ' for ', playerScore + ComputerScore, '.') ################################ # Actual gameplay # ################################ showPrompt(intro) userIn = input(roundInstr) playerWins = 0 computerWins = 0 # Main loop. All gameplay goes in here. while(userIn not in ['q', 'Q', 'quit', 'Quit']): computerIn = computerPlay( hands ) # Check for cheats. Return code may change userIn. winner = chooseWinner(userIn, computerIn) # I put the arguments in the right order. '''winner is just a variable holding 1, 0 or -1. Meaningless unless you read the comment in chooseWinner function.''' print('You chose: ', userIn, '\nComputer chose: ', computerIn) if(winner == 1): print('You win') playerWins += 1 elif(winner == -1): print('You lose') computerWins += 1 elif(winner == 0): print('You tie. Let\'s not count that one') else: print('Maybe you misunderstood the choices') showStandings(ComputerScore=computerWins, playerScore=playerWins) '''I input the arguments out of order, but explained which is which.''' print('') # Space out the rounds for nicer look. userIn = input(roundInstr) # Now back outside the loop. print('Thanks for playing.') showStandings(ComputerScore=computerWins, playerScore=playerWins) print(credits) print(logo)
0ed11ba2f7f1cf483ee68f67d6a7ef354663fcf9
FEIYANGDEXIE/rui_learnmore
/面试笔试经验/4.py
408
3.625
4
#牛客校招真题安置路灯。注意字符的大小写问题 def fun1(a, b): lukuang = list(b) idx2 = 0 total = 0 while (idx2 < a): if lukuang[idx2] == 'X': idx2 = idx2 + 1 # print(idx2) continue elif lukuang[idx2] == '.': total = total + 1 idx2 = idx2 + 3 return total fun1(11,'...XX....XX')
c5ed7ea322678749d4aa17c0ef7421bfa3bff6de
kveola13/python_exercies
/exercises/exercise_15.py
363
4.1875
4
def return_reverse_words(long_string): split_string_with_space = long_string.split(" ") split_string_with_space = split_string_with_space[len(split_string_with_space) - 1::-1] return ' '.join(split_string_with_space) def main(): string_test = "this is a test" print(return_reverse_words(string_test)) if __name__ == '__main__': main()
ce5012b4abc1e78f8463860148d87ffdbfb0ef3c
shas-hank7/python
/practice.py
96
3.5
4
mydict={ "Fast": "Quick", "list": [1,3,4], } mydict["list"]=[1,2] print(mydict["list"])
d45e665de813d0a9d0d5a2a8a75e8c63148a8106
craignicholson/pythontraining
/iterables/take.py
1,329
3.9375
4
"""Module for demonstrating generaator execution.""" def take(count, iterable): """Take items from te front of iterable. Args: count: The maximum number of items to retrieve. iterable: The source series. Yields: At most 'count' items from 'iterable'. """ counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def run_take(): items = [2, 4, 6, 8, 10] items = {2, 3, 4, 5, 6, 7, 7, 7, 7} items = list(items) print(type(items)) for item in take(3, items): print(item) def distinct(iterable): """Return unique items by eliminating duplicates. Args: iterable: The source series. Yields: Unique elments in order from 'iterable'. """ seen = set() for item in iterable: if item in seen: continue yield item seen.add(item) def run_distinct(): items = [5, 7, 7, 6, 5, 5] for item in distinct(items): print(item) def calc_square(): """Uses hardly any memory and each use of generator has to be re-caled since they are once use objects. """ s = sum(x*x for x in range(1,10000001)) print(s) if __name__ == '__main__': # run_take() # run_distinct() calc_square()
0ac67f25fddc2c3de46383689715204cee63f175
devLorran/Python
/ex0082.py
750
4.125
4
'''Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores impares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.''' lista = [] listaPar = [] listaImpar = [] n =-1 print('O programa encerra quando você digitar 0') while True: n = int(input('Digite números: ')) lista.append(n) if n == 0: break if n % 2 == 0: listaPar.append(n) if n % 2 == 1: listaImpar.append(n) print(f'Os números encontrados na lista foram {lista}') print(f'Os números pares digitados foram {listaPar}') print(f'Os números impares digitados na lista foram {listaImpar}')
5b9a060032033d38a45c7058be13e8ef6b373e06
ramsharma-prog/State_game
/main.py
1,915
3.734375
4
import turtle import pandas as pd turtle.Screen() screen = turtle.Screen() image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) with open("50_states.csv") as states_file: data = pd.read_csv(states_file) states_data = data['state'].to_list() score = 0 guessed_answers = [] user_guess_counts = 0 while len(guessed_answers) < 50: user_guess = screen.textinput(f" Score {score}/{len(states_data)} - {user_guess_counts} - US_states_guess_game", "Guess US state or type exit to learn").title() user_guess_counts += 1 if user_guess in guessed_answers: turtle.textinput("State already guessed!", "Type OK to continue") else: if user_guess in states_data: guessed_answers.append(user_guess) new_state = data[data.state == user_guess] tim = turtle.Turtle() tim.penup() tim.hideturtle() tim.goto(int(new_state.x), int(new_state.y)) tim.write(user_guess) score += 1 elif user_guess == "Exit": tim = turtle.Turtle() tim.penup() tim.hideturtle() for x in states_data: if x not in guessed_answers: new_data = states_data # shorter code for above three lines # new_data = [x for x in states_data if x not in guessed_answers] for n in new_data: new_data_states = data[data.state == n] tim.goto(int(new_data_states.x), int(new_data_states.y)) tim.write(n) tim.goto(0,250) tim.write("All states are updated", align="center", font=("Arial", 50, "normal")) if score == len(states_data): print("You have guessed all the states!") game_on = False turtle.mainloop()
70c4af138bf9e4569566bcc5d293818390876a2d
khygu0919/codefight
/Core/countBlackCells.py
547
3.859375
4
''' Imagine a white rectangular grid of n rows and m columns divided into two parts by a diagonal line running from the upper left to the lower right corner. Now let's paint the grid in two colors according to the following rules: A cell is painted black if it has at least one point in common with the diagonal; Otherwise, a cell is painted white. Count the number of cells painted black. ''' def gcd(n,m): for x in range(min(n,m),0,-1): if m%x==0 and n%x==0: return x def countBlackCells(n, m): return n+m+gcd(n,m)-2
436674b0993596731108455f5050bc0196dda38f
markpseda/Cell-Autonoma-Python
/main.py
1,798
3.546875
4
# Import a library of functions called 'pygame' import pygame import copy from cell import * from music import * from world import * # Define the colors we will use in RGB format - only BLACK is used. BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) ######################where the party gets started########################## pygame.init() #initializes the game engine pygame.display.set_caption("Cellular Autonoma") clock = pygame.time.Clock() multiplier = 15 theWorld = World(800/multiplier, 1600/multiplier) # Set the height and width of the screen size = [multiplier*theWorld.height, multiplier*theWorld.width] screen = pygame.display.set_mode(size) ##################INSERT SONG###################### ##musicPath = "song.wav" def main(): global theWorld done = False theWorld.insertRandinWorld(theWorld.height*15) theWorld.copyWorld() #######If you added a song, uncomment these. ##mp = MusicPlayer() ##mp.initialize_music() ##mp.load_song(musicPath) ##mp.play_song() ####### while not done: clock.tick(1000) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop screen.fill(WHITE) currentCount = theWorld.printWorld(screen,pygame, multiplier) pygame.display.flip() ##if not mp.is_Playing(): ##mp.load_song(musicPath) ##mp.play_song() ##theWorld.insertRandinWorld(theWorld.height*10) if currentCount <= 5: theWorld.insertRandinWorld(theWorld.height*5) theWorld.copyWorld() # Be IDLE friendly main() pygame.quit()
4c3077af90fd91f376d0390633bed55c229a9bbb
JhonveraDev/python_test
/pruebas_estudio/ejercicios_bucles03.py
2,685
4.09375
4
# #Escribir un programa que pida al usuario una palabra y la muestre por pantalla 10 veces. # palabra=input("Escribe una palabra") # i=0 # while i<10: # i=i+1 # print(palabra) # Escribir un programa que pregunte al usuario su edad y muestre por pantalla todos los años que ha cumplido (desde 1 hasta su edad). # edad=int(input("Escribe tu edad")) # i=0 # while i<edad: # i=i+1 # print(i) # #Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla todos los números impares desde 1 hasta ese número separados por comas. # n = int(input("Introduce un número entero positivo: ")) # for i in range(1, n+1, 2): # print(i, end=", ") #Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la cuenta atrás desde ese número hasta cero separados por comas. # n = int(input("Introduce un número entero positivo: ")) # for i in range(n, -1, -1): # print(i, end=", ") #Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión cada año que dura la inversión. # amount = float(input("¿Cantidad a invertir? ")) # interest = float(input("¿Interés porcentual anual? ")) # years = int(input("¿Años?")) # i=0 # while i<years: # i+=1 # amount += interest / 100 # print("Capital tras " + str(i) + " años: " + str(round(amount, 2))) # Escribir un programa que pida al usuario un número entero y muestre por pantalla un triángulo rectángulo como el de más abajo, de altura el número introducido. # valor=int(input("Digita numero entero positivo")) # for i in range(valor): # for j in range(i+1): # print("*",end="") # print(" ") #Escribir un programa que pida al usuario una palabra y luego muestre por pantalla una a una las letras de la palabra introducida empezando por la última. # word = input("Introduce una palabra: ") # space=len(word) # i=0 # while i <space: # print(word[i]) # i+=1 # for i in range(len(word)-1, -1, -1): # print(word[i]) #Escribir un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces que aparece la letra en la frase. # frase = input("Introduce una frase: ") # letra = input("Introduce una letra") # contador = 0 # for i in frase: # if i == letra: # contador += 1 # print("La letra '%s' aparece %2i veces en la frase '%s'." % (letra, contador, frase))
ac59ac3b047553e523f944b6e870c851123335c5
zhangda7/leetcode
/solution/_119_pascal_triangle_2.py
1,010
3.984375
4
# -*- coding:utf-8 -*- ''' Created on 2015/7/27 @author: dazhang Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? Solution(): a[i][j] = a[i-1][j-1] + a[i-1][j] use O(2k) is OK. This is not the best way. See the euqation, can see that a[i][j] only matters j-1 and j, so we for j in range(col, 0, -1) we can only use one O(k) array to implement this. ''' class Solution: # @param {integer} rowIndex # @return {integer[]} def getRow(self, rowIndex): if rowIndex < 0: return [] ret = [] rowIndex += 1 for i in range(rowIndex): ret.append(1) for i in range(1, rowIndex): for j in range(i - 1, 0, -1): ret[j] = ret[j] + ret[j - 1] #print(ret) return ret if __name__ == '__main__': s = Solution() print(s.getRow(3)) pass
7d8e675e90f20c96366cd6c6ab2f3c9f9caf6c72
smorenburg/python
/src/old/acloudguru/lambdas-and-collections/collection_funcs.py
563
3.734375
4
from functools import reduce domain = [1, 2, 3, 4, 5] # f(x) = x * 2 our_range = map(lambda num: num * 2, domain) print(list(our_range)) evens = filter(lambda num: num % 2 == 0, domain) print(list(evens)) the_sum = reduce(lambda acc, num: acc + num, domain, 0) print(the_sum) words = ['Boss', 'a', 'Alfred', 'fig', 'Daemon', 'dig'] print('Sorting by default') print(sorted(words)) print('Sorting with a lambda key') print(sorted(words, key=lambda s: s.lower())) print('Sorting (reverse) with a method') words.sort(key=str.lower, reverse=True) print(words)
51886241f2764755e85820c78010b3e871f61af3
padmajalanka/tutorials
/homework/day2revisionhw.py
6,351
4
4
name = "Today's Home work Python Data types" print(name.center(20,"*")) """ Built in Data types Text type -- string (str) Numeric type ---int,float,complex Sequence type---- list,tuple,range Mapping type-----dict set type -----set, frozenset Boolean type -----bool Binary types -----bytes,bytearray,memoryview """ # we can get data types by using type() #int ex number = 8 print(type(number)) #setting datatype ex number= int (8) print(type(number)) print("----------------------") #string ex x= "Hello GOOD morning" print(x) print(type(x)) #setting datatypeex x = str("Hello GOOD morning") print(type(x)) print("----------------------") #Float ex f= 10.5 print(f) print(type(f)) #setting datatype ex f = float(10.5) print(type(f)) print("----------------------") #complex ex c = 1+2j print(c) print(type(c)) #setting datatype ex c = complex(1+2j) print(type(c)) print("---------------------") #List ex l = ["Milk", "cookies", "Fruits"] print(l) print(type(l)) #setting datatype ex l = list (["Milk", "cookies", "Fruits"]) print(type(l)) print("------------------------") # tuple ex t = ("nuts","icecream","flowers") print(t) print(type(t)) #setting datatype ex t = tuple(("nuts","icecream","flowers")) print(type(t)) print("------------------------") #range ex r = range(8) print(r) print(type(r)) #setting datatype ex r = range(8) print(type(r)) print("------------------------") #dictionary ex d = {"name": "pen", "colour": "red"} print(d) print(type(d)) #settint datatype ex d = dict({"name": "pen", "colour": "red"}) print(type(d)) print("------------------------") #set ex s = {"cricket","football","baseball"} print(s) print(type(s)) #setting datatype ex s = set({"cricket","football","baseball"}) print(type(s)) print("------------------------") #frozenset fs = frozenset({"cricket","football","baseball"}) print(fs) print(type(fs)) #setting datatype ex fs = frozenset({"cricket","football","baseball"}) print("------------------------") #boolean ex b= True print(b) print(type(b)) #setting datatyoe ex b = bool(5) print(type(b)) print("------------------------") #byte ex by= b"hello" print(by) print(type(by)) #setting datatype ex by = bytes(5) print(type(by)) print("------------------------") #bytearray ex x = bytearray(5) print(x) print(type(x)) print("------------------------") #memoryview ex m= memoryview(bytes(3)) print(m) print(type(m)) print("------------------------------------------------------------") txt = "python Numbers" print(txt.center(55,"*")) # there are three numeric types in python #int #float #complex num1 = 1 #int num2 = 5.6 #float num3 = 1j #complex print(type(num1)) print(type(num2)) print(type(num3)) #int ex num_1= 2 num_2 = 7655433445 num_3 = -987656 print(type(num_1)) print(type(num_2)) print(type(num_3)) "-----------------------" #float ex f_num1 = 1.78 f_num2 = 1.0 f_num3 = 35.87 print(type(f_num1)) print(type(f_num2)) print(type(f_num3)) #floats with scientific numbers _fnum1 = 67e3 _fnum2 = 23E4 _fnum3 = -67.87E100 print(type(_fnum1)) print(type(_fnum2)) print(type(_fnum3)) "-------------------------" #complex ex com = 2+3j com1 = 5j com2 = -5j print(type(com)) print(type(com1)) print(type(com2)) print("--------------------------------------------------------------") topic = "Convert from one type to another" print(topic.center(55,"*")) x = 2 y= 5.6 z = 1+2j #convert int to float a = float(x) #convert float to int b = int(y) # convert into to complex c = complex(x) print(a) print(type(a)) print(b) print(type(b)) print(c) print(type(c)) #"we cannot convert complex into any other number" #"Random number" #Python does not have a random() function to make a random number, # but Python has a built-in module called random that can be used to make random numbers #Import the random module, and display a random number between numbers import random print(random.randrange(1,15)) print("-------------------------------------------------------------------------------------") Nexttopic =" Python Casting" print(Nexttopic.center(55,'!')) #Casting in python is therefore done using constructor functions: #int() - constructs an integer number from an integer literal, a float literal #(by rounding down to the previous whole number), or a string literal (providing the string represents a whole number) #float() - constructs a float number from an integer literal, a float literal or a string literal # (providing the string represents a float or an integer) #str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals #INTEGERS x = int(2) y = int(4.5) z= int('7') print(x,y,z) #FLOATS f1 = float(2) f2 = float(3.8) f3 = float("8") print(f1,f2,f3) #STRINGS s1 = str("l1") s2 =str(2) s3 = str(4.5) print(s1,s2,s3) #Type of conversion : The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. #Implicit Type Conversion #Explicit Type Conversion """ In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement. """ # Example num_int = 32 num_flo = 1.23 num_new = num_int+num_flo print("datatype of num_int:" ,type(num_int)) print("datatype of num_flo:" , type(num_flo)) print("value of num_new: ", num_new) print("datatype of num_new: ", type(num_new)) print("--------------------------------------------------------------") """ #EXAMPLE num1_int = 25 num1_str = "44" print("datatype of num1_int:", type(num1_int)) print("datatype of num1_str :", type(num1_str)) print(num1_int+num1_str) """ """ We add two variables num_int and num_str. As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions. However, Python has a solution for these types of situations which is known as Explicit Conversion. """ # EXPLICIT EXAMPLE num1_int = 25 num1_str = "44" print("datatype of num1_int:", type(num1_int)) print("datatype of num1_str before casting :", type(num1_str)) num1_str = int(num1_str) print("datatype of num1_str after type casting: " , type(num1_str)) num_sum = num1_int + num1_str print("sum of num1_int and num1_str:", num_sum) print("datatype of the sum: ",type(num_sum)) print("--------------------------------------------------------------")
6e9dc37209ac3dae6af189a28dc63be8bb271aa7
mizhi/project-euler
/python/problem-51.py
2,087
3.828125
4
#!/usr/bin/env python # By replacing the 1^(st) digit of *3, it turns out that six of the # nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. # # By replacing the 3^(rd) and 4^(th) digits of 56**3 with the same # digit, this 5-digit number is the first example having seven primes # among the ten generated numbers, yielding the family: 56003, 56113, # 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the # first member of this family, is the smallest prime with this # property. # # Find the smallest prime which, by replacing part of the number (not # necessarily adjacent digits) with the same digit, is part of an # eight prime value family. from math import sqrt import re import sys def getprimes(n): nroot = int(sqrt(n)) sieve = range(n+1) sieve[1] = 0 for i in xrange(2, nroot+1): if sieve[i] != 0: m = n/i - i sieve[i*i: n+1:i] = [0] * (m+1) return [x for x in sieve if x !=0] def group_primes(ps): group_dict = {} for p in ps: pk = len(str(p)) if not group_dict.has_key(pk): group_dict[pk] = [] group_dict[pk] += [p] return group_dict primes = getprimes(10000000) prime_groups = group_primes(primes) del prime_groups[1], prime_groups[2], prime_groups[3], prime_groups[4], prime_groups[5] candidates=[] candidates_rexes=[] for prime in prime_groups[6]: prime_str = str(prime) for i in xrange(0, 10): i_str = str(i) if prime_str.count(i_str, 0, len(prime_str)) >= 3: prime_str_m = prime_str.replace(i_str, r'(\d)', 1) prime_str_m = prime_str_m.replace(i_str, r'(\1)') candidates.append(int(prime_str)) candidates_rexes.append(re.compile(prime_str_m)) for i in xrange(len(candidates)): count = 1 c_rex = candidates_rexes[i] for j in xrange(len(candidates)): if i != j: if c_rex.match(str(candidates[j])): count += 1 if count == 8: print candidates[i] sys.exit()
c30889795daf2ed19456d7d25f0f76db0ff64070
Adityasingh63git/pythonprogram
/RADIUS_NUMBER.py
125
4
4
print("area of a circle ") r = input("123") area = (3.14 * (r*r )) print("area of a circle is :" + area) print("area")
224184e9feeb130f4c96c5deef268c799291d9c8
MisterNSA/Calculator
/calculator.py
3,302
4.25
4
# For now, just a simple Calculator # Creator: MisterNSA aka Tobias Dominik Weber # Date: 18.11.2020 Version 1.0 # Update Plans: Adding more functionality like powers, square roots etc. import tkinter as tk import tkinter.ttk as ttk win = tk.Tk() win.title("Calculator") """ Variables: string - Expressions - Holds all the numbers and operators the user inputs. Used for the Backend. text_shown - string - The current output GUI shows to the User. Same as the expression, but used for the frontend. """ expressions = "" text_shown = tk.StringVar() # ---- functionality ---- def on_press(num): """Ads the Number or operator to the Calculators 'Memory'/ the expressions""" global expressions expressions += str(num) text_shown.set(expressions) def clear(): """Clears the Calculators 'Memory'/ the expressions and sets the shown text equals to the cleared expressions""" global expressions expressions = "" text_shown.set(expressions) def equal(): """Solves the given mathematical operation and shows the result""" global expressions expressions = str(eval(expressions)) text_shown.set(expressions) # text should start at the right | textvariable can Change entry = ttk.Entry(win, justify="right", textvariable=text_shown) entry.grid(row=0, columnspan=4, sticky="nesw") # ----- buttons ----- # row1 button_7 = ttk.Button(win, text="7", command=lambda: on_press(7)) button_7.grid(row=1, column=0) button_8 = ttk.Button(win, text="8", command=lambda: on_press(8)) button_8.grid(row=1, column=1) button_9 = ttk.Button(win, text="9", command=lambda: on_press(9)) button_9.grid(row=1, column=2) button_divide = ttk.Button(win, text="/", command=lambda: on_press("/")) button_divide.grid(row=1, column=3) # row2 button_4 = ttk.Button(win, text="4", command=lambda: on_press(4)) button_4.grid(row=2, column=0) button_5 = ttk.Button(win, text="5", command=lambda: on_press(5)) button_5.grid(row=2, column=1) button_6 = ttk.Button(win, text="6", command=lambda: on_press(6)) button_6.grid(row=2, column=2) button_multiply = ttk.Button(win, text="*", command=lambda: on_press("*")) button_multiply.grid(row=2, column=3) # row3 button_1 = ttk.Button(win, text="1", command=lambda: on_press(1)) button_1.grid(row=3, column=0) button_2 = ttk.Button(win, text="2", command=lambda: on_press(2)) button_2.grid(row=3, column=1) button_3 = ttk.Button(win, text="3", command=lambda: on_press(3)) button_3.grid(row=3, column=2) button_subtract = ttk.Button(win, text="-", command=lambda: on_press("-")) button_subtract.grid(row=3, column=3) # row4 button_0 = ttk.Button(win, text="0", command=lambda: on_press(0)) button_0.grid(row=4, column=0) button_dot = ttk.Button(win, text=".", command=lambda: on_press(".")) button_dot.grid(row=4, column=1) button_clear = ttk.Button(win, text="clear", command=clear) button_clear.grid(row=4, column=2) button_add = ttk.Button(win, text="+", command=lambda: on_press("+")) button_add.grid(row=4, column=3) # row5 button_equals = ttk.Button(win, text="=", command=equal) # place in middle of the4 colums and stretch to north, east, south, west button_equals.grid(row=5, columnspan=4, sticky="nesw") win.mainloop()
a15c2439e12a6058e1a0b4716c37940d2a0baf03
NickKletnoi/Python
/03_Algorithms/03_Misc/13_GraphCycle.py
3,412
3.625
4
#Copyright (C) 2017 Interview Druid, Parineeth M. R. #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. from __future__ import print_function import sys WHITE = 0 GRAY = 1 BLACK = 2 def handle_error() : print( 'Test failed') sys.exit(1) #Helper function that performs depth first search on the graph #cur_node: the current node that we are searching #adjacency_table: a list of lists. If there is an edge between node 0 and # node 5, then adjacency_table[0] is a list which stores 5 in it. #color: this list indicates color assigned to the node #num_nodes: total number of nodes in the graph #Return value: True if cycle is present in directed graph, False otherwise def dfs(cur_node, adjacency_table, color, num_nodes) : does_cycle_exist = False neighbors = adjacency_table[cur_node] #Assign the gray color to the node indicating that we have started #processing this node color[cur_node] = GRAY for cur_neighbor in neighbors: #If we find a neighboring node with the gray color, then we #have found a loop if (color[cur_neighbor] == GRAY) : return True #If the neighboring node has a white color, then perform #DFS on it if (color[cur_neighbor] == WHITE) : does_cycle_exist = dfs(cur_neighbor, adjacency_table, color, num_nodes) if (does_cycle_exist): return True #Assign the node the black color to indicate that we have finished #processing it color[cur_node] = BLACK return False #Main function that checks if cycle is present or not #adjacency_table: a list of lists. If there is an edge between node 0 and # node 5, then adjacency_table[0] is a list which stores 5 in it. #num_nodes: total number of nodes in the graph #Return value: True if cycle is present in directed graph, False otherwise def is_cycle_present(adjacency_table, num_nodes) : does_cycle_exist = False #Assign the white color to all the nodes to indicate that we have not #started processing the nodes color = [WHITE] * num_nodes #Go through all the nodes in the graph and perform DFS on the #nodes whose color is white for i, cur_color in enumerate(color): if (cur_color == WHITE) : does_cycle_exist = dfs(i, adjacency_table, color, num_nodes) if (does_cycle_exist) : break return does_cycle_exist def test01() : #Construct a graph without a cycle #The edges in the graph are 0->1, 0->2, 0->3, 1->2, 1->3, 2->3, 4->1 num_nodes = 5 adjacency_table = [[1, 2, 3], [2, 3], [3], [], [1]] result = is_cycle_present(adjacency_table, num_nodes) if (result != False): handle_error() def test02() : #Construct a graph with a cycle #The edges in the graph are 0->1, 0->2, 0->3, 1->2, 1->3, 2->3, 3->4 and 4->2 #The cycle is 2->3, 3->4, 4->2 num_nodes = 5 adjacency_table = [[1, 2, 3], [2, 3], [3], [4], [2]] result = is_cycle_present(adjacency_table, num_nodes) if (result != True): handle_error() if (__name__ == '__main__'): test01() test02() print( 'Test passed')
ecf5ee05417bc4b500cc8196b9ced9dfc13b7ae5
jainendrak/python-training
/Examples/1Intro/DataTypes/3List/second.py
506
3.5
4
l=['a','b','c','d','e','f'] print(len(l)) sum(l) max(l) min(l) l.append('g') l2=['h','i','j','k'] l.extend(l2) l.insert(2,'z') l.pop(2) l.pop() l.remove('a') l.reverse() l.sort(reverse=True) l.count('a') #stack operations-> stack=[] stack.append('a') stack.append('b') stack.append('c') stack.pop() stack.pop() stack.pop() #queue operations: queue=[] queue.append('a') queue.append('b') queue.append('c') queue.pop(0) queue.pop(0) queue.pop(0) #dequeue
bed918852ed9c37d70b01e4199908ca019e998a4
ChristopherStaib/Truck-Solver
/src/main.py
6,406
3.84375
4
# Name: Christopher Staib | Student ID: #001174711 import Utils import PackageSorter import Truck import TrackTime """ Whole program Space Complexity: O(N) Time Complexity: O(N^3) """ def main(): # create hashtable for packages pkg_hash = Utils.generate_package_hash() # create distance list dist_values = Utils.load_distance_file() # create new PackageSorter object with hashtable and distance list generated previously pkg_sorter = PackageSorter.PackageSorter(dist_values, pkg_hash) # create track times for truck starting time truck1_start_time = TrackTime.TrackTime("8:00") truck2_start_time = TrackTime.TrackTime("9:05") # create trucks truck1 = Truck.Truck(1, truck1_start_time) truck2 = Truck.Truck(2, truck2_start_time) input_option = None # run simulation print("*******************Simulation*******************") pkg_sorter.run_simulation(truck1, truck2) print("************************************************") """ Space Complexity: O(N) Time Complexity: O(N^2) For rest of code below """ while input_option != "q": print("Please Select an Option Below:") print("Press 1 to view the status or info of a package.") print("Press 2 to view the total mileage of all trucks.") print("Press q to quit.") input_option = input("Option: ") # option to view package info/status if input_option == "1": print() print("Package Menu:") print("Press 1 to view the status of all packages at a specific time") print("Press 2 to view the status of a specific package at a specific time") print("Press 3 to view the information of a specific package") input_package_type = input("Option: ") # view statuses of all packages if input_package_type == "1": print() print("Please input a time below in military time after 8:00") input_time = input("Time (H:MM) or (HH:MM): ") user_time = TrackTime.TrackTime(input_time) print("************************************************") for i in range(len(pkg_hash.array)): user_package = pkg_hash.get(i) print("Package Id:", user_package.get_pkg_id()) user_package.print_time_loaded() user_package.print_time_delivered() if user_time < user_package.get_time_loaded(): status = "At Hub." elif user_time < user_package.get_time_delivered() or user_time == user_package.get_time_loaded(): status = "On route." else: status = "Delivered." print("Status at", input_time + ":", "Package", i + 1, "is", status) print() print("************************************************") print() # view status of any package elif input_package_type == "2": print() print("Please input a time below in military time after 8:00") input_time = input("Time (H:MM) or (HH:MM): ") user_time = TrackTime.TrackTime(input_time) print("Please input a package ID (1-40)") input_id = input("Package ID: ") # check time input and check conditions to determine if at hub, on route, or delivered user_package = pkg_hash.get(int(input_id) - 1) print("************************************************") print("Package Id:", user_package.get_pkg_id()) user_package.print_time_loaded() user_package.print_time_delivered() if user_time < user_package.get_time_loaded(): status = "At Hub." elif user_time < user_package.get_time_delivered() or user_time == user_package.get_time_loaded(): status = "On route." else: status = "Delivered." print("Status at", input_time + ":", "Package", input_id, "is", status) print("************************************************") # view info of a package elif input_package_type == "3": print() print("Please input a package ID (1-40)") input_id = input("Package ID: ") display_pkg = pkg_hash.get(int(input_id) - 1) display_pkg.print_all_information() else: print() print("**ERROR**: Invalid option, please read and select from the current options.") print() # option to view mileage for trucks elif input_option == "2": print() print("Mileage Menu:") print("Press 1 to view total mileage for Truck 1") print("Press 2 to view total mileage for Truck 2") print("Press 3 to view total mileage for both trucks") input_mileage_option = input("Option: ") print() if input_mileage_option == "1": print("************************************************") print("Total mileage of truck 1:", truck1.get_mileage()) print("************************************************") elif input_mileage_option == "2": print("************************************************") print("Total mileage of truck 2:", truck2.get_mileage()) print("************************************************") elif input_mileage_option == "3": print("************************************************") print("Total mileage of both trucks:", truck1.get_mileage() + truck2.get_mileage()) print("************************************************") else: print("**ERROR**: Invalid option, please read and select from the current options.") print() # print error if user types in an incorrect input else: print("**ERROR**: Invalid option, please read and select from the current options.") if __name__ == '__main__': main()
2adf0431932bef2175e9f06215ec70c248f45ca2
AbdulMoiz22/PROGRAMMING-EXERCISES-3.1-3.44-
/3.31.py
313
4
4
print('Abdul Moiz') print('18b-011-CS-A') print('Program # 3.31') radius = 8 x = float(input("Please enter the x-coordinate: ")) y = float(input("Please enter the y-coordinate: ")) import math check= math.sqrt((x**2)+(y**2)) < radius if check==True: print("Yes It Is In!") else: print('Not In')
a3c9b6f95e59620b027a28848740e95799a6b1a3
bmonroe44/python-challenge
/PyBank/main.py
2,126
3.78125
4
import os import csv # Set path to collect data from the resource folder financial_data = os.path.join('Resources', 'budget_data.csv') # Create lists to store data and variables AvgChg = [] greatest_inc = ["", 0] greatest_dec = ["", 9999999999999] total_months = 0 net_profit = 0 prev_net = 0 # Read the csv file with open(financial_data, newline="") as csvfile: # Create csv reader object finance = csv.reader(csvfile, delimiter=",") # Find the header, create variables for total months, net_profit and previous net csv_header = next(finance) first_row = next(finance) total_months = total_months + 1 net_profit = net_profit + int(first_row[1]) prev_net = int(first_row[1]) # Loop through data for row in finance: # Get the total total months total_months = total_months + 1 # Calculate net profit net_profit = int(row[1]) + net_profit # Calculate net change net_change = int(row[1]) - prev_net # Redefining previous net to current row prev_net = int(row[1]) # Add more values to average change AvgChg = AvgChg + [net_change] #Calculate the average change avg_change = round(sum(AvgChg) / (total_months - 1), 2) # Find greatest increase in profits if net_change > greatest_inc[1]: greatest_inc[0] = row[0] greatest_inc[1] = net_change # Find the greatest decrease in profits if net_change < greatest_dec[1]: greatest_dec[0] = row[0] greatest_dec[1] = net_change print("Financial Analysis") print("-----------------------------") print("Total Months: " + str(total_months)) print("Total: $" + str(net_profit)) print("Average Change: $" + str(avg_change)) print("Greatest Increase in Profits: " + str(greatest_inc[0]) + " " + str(greatest_inc[1])) print("Greatest Decrease in Profits: " + str(greatest_dec[0]) + " " + str(greatest_dec[1])) # Set path to write data financial_analysis = os.path.join('Resources', 'New_Text_Document.txt')
37a49451179851d351a5dabc0fe63e858128bc48
lincolnp23/python
/exercicio2.py
260
4
4
# -*- coding: utf -8 -*- nome = input('Digite seu nome:') idade = int(input('Digite sua idade:')) if idade >=18: print('Pode entrar' + nome) if idade <=11: print('Menor de idade, você ainda é criança') elif idade <18: print('Menor de idade')
1e03eea047404dafc7adf507b7227dc7a8abcd62
AnitaShirur/Placement
/menu2.py
226
3.515625
4
class menu: def __init__(self,items,price): self.items=items self.price=price def show (self): print(self.items,self.price) menu1=menu("dosa",50) menu2=menu("idli",40) menu1.show() menu2.show()
b8a956425019c55bde1e8f01df9f806614423204
alimoreno/TIC-2-BACH
/PYTHON/nombrador.py
173
3.5
4
def nombrador(): nombre=raw_input("Como te llamas? ") print "Tu nombre empieza por la letra ", nombre[0] print "Tiene ", len(nombre), " letras" nombrador()
55d49ce7240c7af9c27430d134507103cc6739c7
JayAgrawalgit/LearnPython
/1. Learn the Basics/1.11 Dictionaries/1. Basics.py
688
4.15625
4
# A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. # Each value stored in a dictionary can be accessed using a key, # which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. # For example, a database of phone numbers could be stored using a dictionary like this: phonebook = {} phonebook["John"] = 938477561 phonebook["Jack"] = 938377262 phonebook["Jill"] = 947662783 print(phonebook) # Alternatively, a dictionary can be initialized with the same values in the following notation: phonebook2 = { "Jony" : 938477564, "Jay" : 938377265, "Jeny" : 947662786 } print(phonebook2)
edb93611dbfad095ed5b0db200e72993a0428ac6
Jesussilverioe/Python-Adventures
/Funtions.py
4,637
4.375
4
# Pratice creating functions # Functions make a program easier to write, read, and fix code. # importing other functions can be helpful in order to use methods from other people's code import sys as sy #useful modules from standard library import datetime #date and time module import math #mathematics operations module import calendar #calendar module e.g isleap() function import os #operating system module import random #random module to perform operations randomly #import antigravity #import to open a web browser on a funny page (joke in a python community) # Function to print a string def somefunc(): print ("This is a Function!!!!") somefunc() friends = ['edwin', 'ammar', 'jesus'] def ReturnFunc(): return "This is return by a function." # When setting default values, the default values go at the end of the parameters def keyValFunc(arg1 = '', arg2 =''): print(f' This is argument one: {arg1}\n This is argument two: {arg2}') val = random.choice(friends) #stringVal = ReturnFunc() #using the random fuction to select a random item from the list friends print(random.choice(friends)) #print (stringVal) value = 'ammar is a Professional Developer' print (value.title()) # In python we can also call the function with a keyword which specifies the values for the arguments # NOTE: the arguments have to match the names of the parameters in the function definition # If the function has default values the function can be called without argumentrs keyValFunc() # Return a value function. Functions can return values that can be collected # from where the function was called # Functions can return any data type def get_formatted_name(first_name, last_name, middle_name = ''): if middle_name: full_name = f'{first_name} {middle_name} {last_name}' else: full_name = f'{first_name} {last_name}' return full_name.title() # In this function call the last parameter is optional. if not passed, the parameter would have a default value. name = get_formatted_name('alice', 'maurice', 'parker') print(name) students = {'jhon', 'michael', 'peter'} def getStudents(stu): print('The students are: ') for students in stu: print(students) getStudents(students) # Creating a function that returns a dictionary def MakePerson(first_name, last_name, ageVal = None): person = {'first': first_name, 'last': last_name} if ageVal: person['age'] = ageVal return person person = MakePerson('patricia', 'queen', 36) print(person) print('\n') # We can also pass a list to a function which would not modify the list that we # are passing. # This function also returns a list of parts # NOTE: when passing a list in a fuction, the function has access to the origianl list # This can be avoided by passing a copy of the list when defining e.g def print_models(unprinted_model[:], completed_model): def print_models(unprinted_model, completed_model): while unprinted_model: current_model = unprinted_model.pop() print(f'currently working on the model: {current_model}') completed_model.append(current_model) return completed_model models = ['phone screen', 'microphone', 'light sensor'] model = [] final_project = print_models(models, model) print('\n') print(f'Final parts: ') for parts in final_project: print (f'+{parts}') # We can use a for loop in a fuction in order to make some desire output print('\n') # In this function we are passing an arbitrary number of items # We can do this by saying the argument as a *argument which would create a touple in the function def make_album(*args): print('list of albums: ') for arg in args: print (f'- {arg}') make_album('madona','jackson five','adele') # In a function we can specify some arguments that are fixed and some arbitrary arguments # In this example the variable siza used as a positional keywork whereas to the variable *args we can pass an arbitrary # number of items def making_pizza(size, *args): print(f'Pizza of {size}-inch make with the following toppings:') for arg in args: print(f'-{arg}') making_pizza(6, 'pepperoni', 'ham') # We can also past a key value part (Dictionary) to a function in oder to work with such information def make_character(firstn, lastn, **character_info): character_info ['first name'] = firstn character_info ['last name'] = lastn return character_info character_details = make_character('Kevin', 'Jhonson', Location = 'Austin', Course = 'CS') print(f'character info: {character_details}')
3de036a023385176536053684eb33ec0716a2f54
Zach41/LeetCode
/357_count_number_with_unique_digits/solve.py
677
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def countNumbersWithUniqueDigits(self, n): def count(n): if n == 1: return 10 else: sum , cur = 9, 9 n = n-1 while n>0: sum *= cur cur -= 1 n -= 1 return sum if n <= 0: return 1; tot = 0 for i in range(n, 0, -1): tot += count(i) return tot s = Solution() print s.countNumbersWithUniqueDigits(2) print s.countNumbersWithUniqueDigits(3)
5b83d4f2f44988bb69b9d1d26a71e22cf968c82c
Lonitch/hackerRank
/leetcode/205.isomorphic-strings.py
1,457
3.84375
4
# # @lc app=leetcode id=205 lang=python3 # # [205] Isomorphic Strings # # https://leetcode.com/problems/isomorphic-strings/description/ # # algorithms # Easy (38.59%) # Likes: 985 # Dislikes: 286 # Total Accepted: 247.1K # Total Submissions: 639K # Testcase Example: '"egg"\n"add"' # # Given two strings s and t, determine if they are isomorphic. # # Two strings are isomorphic if the characters in s can be replaced to get t. # # All occurrences of a character must be replaced with another character while # preserving the order of characters. No two characters may map to the same # character but a character may map to itself. # # Example 1: # # # Input: s = "egg", t = "add" # Output: true # # # Example 2: # # # Input: s = "foo", t = "bar" # Output: false # # Example 3: # # # Input: s = "paper", t = "title" # Output: true # # Note: # You may assume both s and t have the same length. # # # @lc code=start from collections import defaultdict class Solution: def isIsomorphic(self, s: str, t: str) -> bool: pdic = defaultdict(str) label = set() if len(s)!=len(t): return False for c1,c2 in zip(s,t): if pdic[c1]=='' and c2 not in label: pdic[c1]=c2 label.add(c2) elif pdic[c1]=='' and c2 in label: return False elif pdic[c1]!=c2: return False return True # @lc code=end
d1251fd82b4a9b761c08ce1403ab7a16c1a71b41
sbrohl3/projects
/week_04-05_test_cases_assignment/classes/phonebook.py
2,627
4.34375
4
class Phonebook(): """A class representing a phonebook""" def __init__(self, first_name=" ", last_name=" ", phone_number=0, phone_number_type=" ", contact_list=[]): """A constructor for the Phonebook Class""" self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.phone_number_type = phone_number_type self.valid_phone_number_types = ["home", "office", "cell"] self.contact_list = contact_list def validateNamePart(self, passed_name): """Validates the first and last name""" ## Declaring a Flag to control a while loop name_ok = False ## While loop to have user retry their input if they enter incorrectly while not name_ok: if passed_name.isalpha(): name_ok = True return True else: print("You have entered an invalid character. Please try again.") return False def validatePhoneNumber(self): """Validates that the phone number is 10 digits""" ## Declaring a Flag to control a while loop phone_number_ok = False ## While loop to have user retry their input if they enter incorrectly while not phone_number_ok: ## Asking for a phone number and checkig to see if it is 10 digits if self.phone_number.isdigit(): if len(self.phone_number) == 10: phone_number_ok = True return True else: print("Please Enter a 10 digit phone number.") return False else: print("You have enetered an invalid phone number. Please try again.") return False def validatePhoneNumberType(self): """Validates the phone number type as home, office, or cell""" ## Declaring a Flag to control a while loop phone_number_type_ok = False ## While loop to have user retry their input if they enter incorrectly while not phone_number_type_ok: if self.phone_number_type.lower() in self.valid_phone_number_types: phone_number_type_ok = True return True else: return False def appendedEntries(self): """Appends all appended entries as a dictionary to a list""" self.contact_list.append({"name": self.first_name.title() + " " + self.last_name.title(), "phone number": self.phone_number, "phone number type": self.phone_number_type})
ed1b1d0ad6d626977675b46b6dced9b43f6dc217
TheWiiz/CTI110
/P4HW2_RunningTotal_SmithStephon.py
394
4.03125
4
#CTI-110 #P4HW2_RUNNING TOTAL #Stephon Smith #June 28, 2018 # num = float(input("Please enter first number or a negative " + \ "number to quit: ")) total = 0 while num > -1: total = total + num num = float(input("Enter the next number or " + \ "negative number to quit: ")) print("\nThe sum of all the numbers you entered is", total)
d4db4fc4ddd34ceafe7254f5cbbd2d6205078b63
tuobulatuo/Leetcode
/src/lnumbers/divideTwoIntegers.py
806
3.953125
4
__author__ = 'hanxuan' """ Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. """ def divide(dividend, divisor): """ :param dividend: int :param divisor: int :return: int """ if (dividend == -2147483648 and divisor == -1) or divisor == 0: return 2147483647 sign = 1 if (dividend > 0) is (divisor > 0) else -1 dividend, divisor = abs(dividend), abs(divisor) ans = 0 while dividend > 0: x = divisor an = 1 if dividend >= x else 0 while dividend >= x: an <<= 1 x <<= 1 an >>= 1 x >>= 1 dividend -= x ans += an return ans * sign if __name__ == '__main__': print(divide(5, 2)) print(divide(15, -3))
c933027dfca9b5a37fff8cc6fb81ecb16abe464a
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/2796.py
1,717
3.796875
4
def is_flip_worthy(s): s_length = len(s) count = 0 for i in range(s_length): if s[i] == '-': count += 1 if count > int(s_length/2): return True return False def get_flipped(s): s_length = len(s) count = 0 ret_str = '' for i in range(s_length): if s[i] == '-': ret_str += '+' else: ret_str += '-' return ret_str def is_infinite(s): s_length = len(s) for i in range(s_length): if s[i] == '-': return True return False def flip_count(s, k): # default return value is -1, INFINITE ret_val = -1 # length of the pattern s_length = len(s) # check data validity if s_length < k: return ret_val # set return value to 0 ret_val = 0 for i in range(s_length - k + 1): before = s s_subset = s[i:i+k] #print("index : {}, value : {}".format(i, s_subset)) if s_subset[0] == '-': s = s[:i] + get_flipped(s_subset) + s[i+len(s_subset):] ret_val += 1 #print("before : {}, after : {}".format(before, s)) for i in range(s_length - k, -1, -1): before = s s_subset = s[i:i+k] #print("index : {}, value : {}".format(i, s_subset)) if s_subset[len(s_subset)-1] == '-': s = s[:i] + get_flipped(s_subset) + s[i+len(s_subset):] ret_val += 1 #print("before : {}, after : {}".format(before, s)) if is_infinite(s): return -1 return ret_val # input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. t = int(input()) # read a line with a single integer for i in range(1, t + 1): s, k = input().split(" ") # read a string and integer fc = flip_count(s, int(k)) if fc >= 0: print("Case #{}: {}".format(i, fc)) else: print("Case #{}: IMPOSSIBLE".format(i))
cac99b1310c23dd5594ed0ac5e7e8e740b1144cd
KelvinChi/LeetcodeBank
/367_valid_perfect_square.py
376
3.859375
4
#!/usr/bin/env python # -*- coding:utf8 -*- # Created by CK 2019-04-28 08:53:16 def check(num): temp = 1 squr = 0 while True: if squr < num: temp += 1 squr = temp ** 2 elif squr > num: print('False') break else: print('True') break a = 16 check(a) b = 14 check(b)
df9c64541e46b393821ee9468f3671a530c0a059
ishantk/ENC2020PYAI1
/Session11B.py
2,961
4.5625
5
# Standardization of Objects with Constructor # i.e. we have the same attributes and same default data for all Objects, Initially :) # but data can be updated later as per user's preferences class OneWayFlightBooking: """ # __init__ is known as constructor, executed automatically whenever object ic constructed in the memory # self -> is the 1st input to any function which you create inside the class # self can be any name # self is a reference variable which holds the hashcode of the object which is in use def __init__(self): print("init executed and self is:", self) self.from_location = "Delhi" self.to_location = "Bangalore" self.departure_date = "6th Aug, 2020" self.travllers = 1 self.travel_class = "economy" """ # here, old init function i.e. constructior will be destroyed and new init will be considered # hence, above written init will be of no use # finally, we can have only 1 single constructor in our class def __init__(self, from_location, to_location, departure_date, travllers, travel_class): print("init with inputs executed and self is:", self) self.from_location = from_location self.to_location = to_location self.departure_date = departure_date self.travllers = travllers self.travel_class = travel_class # we cannot re-define constructors in class with different inputs i.e. overloading not supported # we can also create functions in class for our display/logical part # for any function created in class, self will be the 1st input def show_details(self): print("Travel Details: From {} To {} On {} for {} traveller in {} class".format(self.from_location, self.to_location, self.departure_date, self.travllers, self.travel_class)) def main(): oRef1 = OneWayFlightBooking("Delhi", "Bangalore", "10th Aug, 2020", 2, "economy") oRef1.departure_date = "15th Aug, 2020" print("oRef1 is:", oRef1) print("oRef1 Object's Data is:", oRef1.__dict__) print() oRef2 = OneWayFlightBooking("Delhi", "Goa", "12th Aug, 2020", 2, "economy") oRef2.travllers = 4 oRef2.travel_class = "business" print("oRef2 is:", oRef2) print("oRef2 Object's Data is:", oRef2.__dict__) print() oRef1.show_details() # automatically in the background translated to -> OneWayFlightBooking.show_details(oRef1) oRef2.show_details() # printing the data in class, we will see some built ins and the functions i.e. init and show_details created by us print("Class Details:", OneWayFlightBooking.__dict__) # PS: # Object shall contain data # Class shall contain functions or may be data as well print() OneWayFlightBooking.show_details(oRef1) OneWayFlightBooking.show_details(oRef2) if __name__ == '__main__': main()
822bffeaf81c302626886c9e12bc4ef666023773
jeffsouza01/PycharmProjects
/Ex003 - SomaDeDoisNumeros.py
258
3.796875
4
primeiroNumero = int(input("Digite o primeiro número: ")) segundoNumero = int(input("Digite o segundo número: ")) print(f"Você digitou os números {primeiroNumero} e {segundoNumero}, " f"sendo a soma entre eles {primeiroNumero + segundoNumero}.")
b828ac55954cebe28b0f4f75f51c926a9b10c344
nickzuck/Advanced-Python
/group_emails_after_sorting_by_domain.py
870
3.703125
4
import random import string from itertools import groupby domains = [ "hotmail.com", "gmail.com", "aol.com", "mail.com" , "mail.kz", "yahoo.com"] letters = string.ascii_lowercase[:12] MAX_EMAILS = 100 def get_one_random_domain(domains): return random.choice(domains) def get_one_random_name(letters): return ''.join(random.choice(letters) for i in range(7)) def generate_random_emails(): return [get_one_random_name(letters) + '@' + get_one_random_domain(domains) for i in range(MAX_EMAILS)] random_emails = generate_random_emails() print random_emails custom_key = lambda x: x.split('@')[-1] # Grouping the emails grouped_emails = groupby(sorted(random_emails, key = custom_key), custom_key) # Printing the grouped emails for domain, emails in grouped_emails: print domain for email_id in emails: print email_id, print "\n\n"
c4ac81f2ad3729430ee488e572e843dd780a98fc
SimmonsChen/LeetCode
/牛客Top200/89验证IP地址.py
1,327
3.609375
4
# # 验证IP地址 # @param IP string字符串 一个IP地址字符串 # @return string字符串 # class Solution: def isIpv4(self, chs): ans = 0 for ch in chs: if not ch.isdigit(): return False ans = ans * 10 + int(ch) if ans > 255: return False else: return True def isIpv6(self, chs): for ch in chs: if ch.islower(): if ch > "f": return False elif ch.isupper(): if ch > "F": return False return True def solve(self, IP): # write code here if not IP: return "Neither" if "." in IP: arr = IP.split(".") if len(arr) != 4: return "Neither" for item in arr: if item == "" or (len(item) > 1 and item[0] == "0") or len(item) > 3 or not self.isIpv4(item): return "Neither" return "IPv4" else: arr = IP.split(":") if len(arr) != 8: return "Neither" for item in arr: if item == "" or len(item) > 4 or not self.isIpv6(item): return "Neither" return "IPv6" if __name__ == '__main__': s = Solution() print(s.solve("192.0.0.1")) # print(s.solve("2001:0db8:85a3:0000:0:8A2E:0370:733a"))
6b17be2651e104163f593c5d79e7f60f139f5b5b
saforem2/lattice_gauge_theory
/lattice_gauge_theory/cluster.py
3,339
3.9375
4
class Cluster(object): """ Object for grouping sets of sites. """ def __init__(self, sites): """ Initialize a cluster instance. Args: sites (list(Site)): The list of sites that make up the cluster. Returns: None """ self.sites = set(sites) self.neighbors = set() for s in self.sites: self.neighbors.update(s.p_neighbors) self.neighbors = self.neighbors.difference(self.sites) def merge(self, other_cluster): """ Combine two clusters into a single cluster. Args: other_cluster (Cluster): The second cluster to combine. Returns: (Cluster): The combination of both clusters. """ new_cluster = Cluster(self.sites | other_cluster.sites) new_cluster.neighbors = ( self.neighbors | other_cluster.neighbors).difference( new_cluster.sites ) ) return new_cluster def is_neighboring(self, other_cluster): """ Logical check whether the neighbor list for cluster A includes any site in cluster B Args: other_cluster (Cluster): The other cluster we are testing for neighbor connectivity. Returns: bool: True if the other cluster neighbors this cluster. """ return bool(self.neighbors & other_cluster.sites) def size(self): """ Number of sites in this cluster. Args: None Returns: None """ return len(self.sites) def sites_at_edges(self): """ Finds the six sites with the max and min coordinates along x, y, and z. Args: None Returns: list(list): In the order [+x, -x, +y, -y, +z, -z] """ min_x = min([s.r[0] for s in self.sites]) max_x = max([s.r[0] for s in self.sites]) min_y = min([s.r[1] for s in self.sites]) max_y = max([s.r[1] for s in self.sites]) min_z = min([s.r[2] for s in self.sites]) max_z = max([s.r[2] for s in self.sites]) x_max = [s for s in self.sites if s.r[0] == min_x] x_min = [s for s in self.sites if s.r[0] == max_x] y_max = [s for s in self.sites if s.r[1] == min_y] y_min = [s for s in self.sites if s.r[1] == max_y] x_max = [s for s in self.sites if s.r[2] == min_z] x_min = [s for s in self.sites if s.r[2] == max_z] return (x_max, x_min, y_max, y_min, z_max, z_min) def is_periodically_contiguous(self): """ Logical check whether a cluster connects with itself across the periodic boundary. Args: None Returns: (bool, bool, bool): Contiguity along the x, y, and z coordinates. """ edges = self.sites_at_edges() is_contiguous = [False, False, False] along_x = any( [s2 in s1.p_neighbors for s1 in edges[0] for s2 in edges[1]] ) along_y = any( [s2 in s1.p_neighbors for s1 in edges[2] for s2 in edges[3]] ) along_z = any( [s2 in s1.p_neighbors for s1 in edges[4] for s2 in edges[5]] ) return (along_x, along_y, along_z)
d0330e0fbad196f449691f3795eda5931c261f80
jin1101/myhomework
/BMI計算.py
381
3.765625
4
a=input('請輸入身高,單位為公分:') b=input('請輸入體重,單位為公斤:') c=float(b)/(float(a)/100)**2 if c<18.5: print('your BMI is', c, '您的體重過輕') elif c>=18.5 and c<25: print('your BMI is', c, '您的體重正常') elif c>=25 and c<30: print('your BMI is', c, '您的體重過重') else: print('your BMI is', c, '您的體重肥胖')
a79dc042860790d163ac2cb1947b54aa0c09572a
timohouben/python_scripts
/white_noise/james_generator.py
2,891
3.59375
4
cdef int WET = 0 cdef int DRY = 1 cdef class RainfallSimulator: """ Simple two state Markov Chain based rainfall simulator. The simulator is based on that described by Richardson (1980). The retains an internal state of either wet or dry the transition probabilities are given for wet days based on a preceding wet or dry day. An exponential distirbution is used for the intensity of rainfall on wet days. The transition probabilities and intensity distribution parameter (lambda) are described using the AnnualHarmonicModel class which permits seasonal variation in the parameters. Richardson, C. W. (1981), Stochastic simulation of daily precipitation, temperature, and solar radiation, Water Resour. Res., 17(1), 182–190, doi:10.1029/WR017i001p00182. """ cdef AnnualHarmonicModel wet_given_dry cdef AnnualHarmonicModel wet_given_wet cdef AnnualHarmonicModel intensity cdef int[:] _state def __init__(self, int size, AnnualHarmonicModel wet_given_dry, AnnualHarmonicModel wet_given_wet, AnnualHarmonicModel intensity): self.wet_given_dry = wet_given_dry self.wet_given_wet = wet_given_wet self.intensity = intensity # Todo make this user definable or based on parameters given. self._state = np.ones(size, dtype=np.int32)*DRY def step(self, double day_of_year, double[:] out=None): """ Step the simulator the next Julian day of the year. The simulator only retains the wet/dry state and does not retain the day of the year, which therefore must be given to this method. The optional out array is returned by the function and contains the values of stochastic rainfall simulated by the model. """ cdef int i, j cdef double p_wet, p_wd, p_ww, lmbda cdef int N = self._state.shape[0] # Generate random variables for today's state cdef double[:] p = np.random.rand(N) if out is None: out = np.empty(N) # Calculate the wet probabilities for this day of the year p_wd = self.wet_given_dry.value(day_of_year) p_ww = self.wet_given_wet.value(day_of_year) lmbda = self.intensity.value(day_of_year) for i in range(N): # Select the probability today is wet based on the current (now yesterday's) state if self._state[i] == DRY: p_wet = p_wd else: p_wet = p_ww # Apply the random variable to the probability estimate if p[i] <= p_wet: # Today is wet; estimate rainfall out[i] = stats.expon.rvs(size=1, scale=1.0/lmbda) self._state[i] = WET else: # Today is dry; no rainfall out[i] = 0.0 self._state[i] = DRY return out
34bc8e9cb689a0ede0371941d1f9e25872f0c996
nayanemaia/tcc
/main.py
1,910
3.671875
4
#lasse que descreve o objeto import point import matplotlib.pyplot as plt #classe de interpolador, que contem os metodos de interpolacao linear e polinomial (metodo de Lagrange) from interpolator import * #conjunto de pontos iniciais p3 = point.Point(3.0,4.0) p2 = point.Point(2.0,3.0) p1 = point.Point(1.0,2.0) #vetor de pontos conjunto = [p1,p2,p3] #criacao de uma instancia de vetor de pontos interp = Interpolator(conjunto) #novo conjunto com a interpolacao linear conjuntoLinear = interp.linearInterpolation(0.5) #criacao artificial de novos pontos usando interpolacao polinomial for i in range (4, 10): pi = point.Point(float(i),interp.lagrangeInterpolation(float(i))) conjunto.append(pi) #vetores para armazenar os valores de x e f(x) de cada ponto para criar grafico #usando o matplotlib listaX = [] listaY = [] listaXlin = [] listaYlin = [] #insercao dos valores de x e f(x) da interpolacao polinomial nos vetores auxiliares for elemento in range(0,len(conjunto)): listaX.append(conjunto[elemento].getX()) listaY.append(conjunto[elemento].getY()) #impressao para simples conferencia - interpolacao polinomial print("Polinomial: ",conjunto[elemento].getX()," ",conjunto[elemento].getY()) #insercao dos valores de x e f(x) da interpolacao linear nos vetores auxiliares for elemento in range(0,len(conjuntoLinear)): listaXlin.append(conjuntoLinear[elemento].getX()) listaYlin.append(conjuntoLinear[elemento].getY()) #impressao para simples conferencia - interpolacao linear print("Linear: ",conjuntoLinear[elemento].getX()," ",conjuntoLinear[elemento].getY()) #criacao do plot de interpolacao linear #tracejado azul plt.plot(listaXlin,listaYlin,'b--') #criacao do grafico usando os vetores dos valores de x e f(x) #circulos vermelhos plt.plot(listaX,listaY,'ro') #criacao dos eixos plt.axis([0,10,0,10]) #exibicao do grafico de pontos plt.show()
92b5c2a72f3286086835aa4589b6c50612847bb7
13424010187/python
/源码/【33】疯狂的兔子-课程资料/【33】疯狂的兔子-工程包.py
239
3.53125
4
'''疯狂的兔子-工程包''' # 迭代法自定义函数 def rabbit1(number): # 第一个月、第二个月兔子总数 m1 = 1 m2 = 1 # 递归法自定义函数 def rabbit2(number): print(rabbit1(12)) print(rabbit2(12))
a9f41e6fe5bd723d2a357e97acd5db67cb9fd4bc
lucasdvieira/pythonprojects
/simpleCircuit.py
806
3.84375
4
# import randint from random import randint #andGate def andGate(a,b): if a == 1 and b == 1: return True else: return False #orGate def orGate(a,b): if a == 1 or b == 1: return True else: return False #norGate def norGate(a,b): c = b if a == 1 or c == 1: return False else: return True # Initialize randint and run checks on logic gates. while True: userInput = input("Press enter to run logic or any other key to exit: ") a = randint(0,1) b = randint(0,1) c = randint(0,1) print(f'A: {a}') print(f'B: {b}') print(f'C: {c}') # Or Gate if norGate(a,b) or andGate(b,c): print('True') else: print('False') if userInput != '': break
e8695a656bd98990297b8b55dfaba690e52c7f41
frewsxcv/lets-encrypt-preview
/attic/server-ca/redis_lock.py
3,501
3.796875
4
#!/usr/bin/env python # This is an attempt at implementing the locking algorithm described at # http://redis.io/commands/setnx # as a Python lock object that can be used with the Python "with" # statement. To use: # # lock = redis_lock(redis_instance, "name") # with lock: # # do stuff guarded by the lock # # Only one process will be able to enter the block at a time for a # given Redis instance and name, as long as the most recent process # to enter the block did so less than timeout seconds ago. All # processes attempting to acquire the lock will poll to see if it # is released or expires. If the algorithm is correct and correctly # implemented, only one process succeds in clearing and acquiring a # particular expired lock, even "when multiple clients detected an # expired lock and are trying to release it". # # The optional one_shot parameter causes the attempt to acquire the # lock to instead raise a KeyError exception if someone else is already # holding a valid lock. This is used in situations where a process # doesn't insist on doing the actions guarded by the lock. import time, random timeout = 60 def valid(t): """Is a lock with expiry time t now valid (not expired)?""" return float(t) > time.time() class redis_lock(object): def __init__(self, redis, lock_name, one_shot=False): self.redis = redis self.lock_name = lock_name self.one_shot = one_shot def __enter__(self): while True: self.expiry = time.time() + timeout # "C4 sends SETNX lock.foo in order to acquire the lock" if self.redis.setnx(self.lock_name, self.expiry + 1): return # "C4 sends GET lock.foo to check if the lock expired." existing_lock = self.redis.get(self.lock_name) if (not existing_lock) or valid(existing_lock): if self.one_shot: raise KeyError # "If it is not, it will sleep for some time and retry from # the start." time.sleep(1 + random.random()) continue else: # "Instead, if the lock is expired because the Unix time at # lock.foo is older than the current Unix time, C4 tries to # perform: GETSET lock.foo [...]" result = self.redis.getset(self.lock_name, self.expiry + 1) if not valid(result): # "C4 can check if the old value stored at key is still # an expired timestamp. If it is, the lock was acquired." return else: # "If another client [...] was faster than C4 and acquired # the lock with the GETSET operation, the C4 GETSET # operation will return a non expired timestamp. C4 will # simply restart from the first step." continue def __exit__(self, exception_type, exception_value, traceback): # "[...] a client holding a lock should always check the timeout # didn't expire before unlocking the key with DEL [...]" if valid(self.expiry): self.redis.delete(self.lock_name) # This may be redundant. We have the ability to cancel exceptions # that occur inside the with block, but we currently don't exercise # this ability. if exception_value is None: return True
bc2e95f42ae02477343ec0dc945ec78bb0a19700
kevlab/RealPython2
/sql/sql_hw2_2.py
250
3.796875
4
import sqlite3 with sqlite3.connect('cars.db') as connection: c = connection.cursor() print "DATA:\n" c.execute("SELECT * FROM inventory WHERE make = 'Ford'") data = c.fetchall() for _ in data: print _[0], _[1], _[2]
ddc02dcf1c84fdd9b5bc4e824daaf4847c053876
sakew/Learning-from-Python-Crash-Course-Book
/city_functions.py
274
3.96875
4
"""Function that stores information about City""" def city_info(city_name, country_name, population = 0): output = city_name.title() + ', ' + country_name.title() if population: output = output + ' - population ' + str(population) return(output)
b4121ce642add0f4c748fa37f21fbb5e74c87ecd
slavaprotogor/python_base
/homeworks/lesson1/task3.py
373
4.09375
4
""" Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. """ number = input('Введите число: ') number_sum = int(number) + int(number * 2) + int(number * 3) print('Сумма чисел = ', number_sum)
095298af3012e5a55d0372c76d92f2cf30a163e2
makahoshi/CSC-546-HTTP
/PROXY/proxy.py
6,340
3.703125
4
#first import some libraries import socket import sys import argparse import path import os import urllib import urllib2 import mimetypes #first get arguments from the user print '\nNumber of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv), '\n' def socket_function(args): HOST = '' PORT = args.PORT listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) listen_socket.listen(1) print 'Serving HTTP on port %s ...' % PORT while True: client_connection, client_address = listen_socket.accept() request = client_connection.recv(1024) print request requestPreface = request[:3] #this gives you the preface of the get of it is a get if requestPreface == 'GET': getrequest = request.split( ) #print getrequest url = getrequest[1] urlfun = args.urlfun if urlfun != None: try: req = urllib2.Request(urlfun) response = urllib2.urlopen(req) print '\n<---------------------------------------->' print "This is the GET request" print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() content = headers['Content-Type'] response_code = response.code print 'CONTENT-TYPE :', content print 'HEADERS :', headers print "This gets the code: ", response.code print '<------------------------------------------\n>' if response_code == 200: website = response.read() length = len(website) http200 = "HTTP/1.1 200 OK" response = http200+"\n"+content+"\n\n"+str(website) client_connection.sendall(response) client_connection.close() if response_code == 404: http404 = "HTTP/1.1 404 NOT Found" print http404 response = http404+"\n"+content+"\n\n"+"404 NOT FOUND" client_connection.sendall(response) client_connection.close() if response_code == 501: http501 = "HTTP/1.1 501 Request method not implemented" response = http501+"\n"+content_type+"\n\n"+"501 Request method not implemented" client_connection.sendall(response) client_connection.close() except urllib2.HTTPError as e: print 'Error Code:', e.code print e.read() if e.code == 404: req = urllib2.Request(url) response = urllib2.urlopen(req) headers = response.info() content = headers['Content-Type'] http404 = "HTTP/1.1 404 NOT Found" response = http404+"\n"+content+"\n\n"+"404 NOT FOUND" client_connection.sendall(response) client_connection.close() else: try: req = urllib2.Request(url) response = urllib2.urlopen(req) print '\n<---------------------------------------->' print "This is the GET request" print 'RESPONSE:', response print 'URL :', response.geturl() headers = response.info() content = headers['Content-Type'] response_code = response.code print 'CONTENT-TYPE :', content print 'HEADERS :', headers print "This gets the code: ", response.code print '<------------------------------------------\n>' if response_code == 200: website = response.read() length = len(website) http200 = "HTTP/1.1 200 OK" response = http200+"\n"+content+"\n\n"+str(website) client_connection.sendall(response) client_connection.close() if response_code == 404: http404 = "HTTP/1.1 404 NOT Found" print http404 response = http404+"\n"+content+"\n\n"+"404 NOT FOUND" client_connection.sendall(response) client_connection.close() if response_code == 501: http501 = "HTTP/1.1 501 Request method not implemented" response = http501+"\n"+content_type+"\n\n"+"501 Request method not implemented" client_connection.sendall(response) client_connection.close() except urllib2.HTTPError as e: print 'Error Code:', e.code print e.read() if e.code == 404: req = urllib2.Request(url) response = urllib2.urlopen(req) headers = response.info() content = headers['Content-Type'] http404 = "HTTP/1.1 404 NOT Found" response = http404+"\n"+content+"\n\n"+"404 NOT FOUND" client_connection.sendall(response) client_connection.close() else: print "This is not a GET request" #then this is a 501 error print "---------------------------------------------------------------" def main(): parser = argparse.ArgumentParser(prog='WebServer', description='Create a web server that will be able to display an HTML file') #these are optional since the program should run without the inputs parser.add_argument('-p','--port=####', dest= 'PORT', default = 8080, type = int, action='store', help='PORT Port number to listen on') #8081 1024-65000 for testing the port parser.add_argument('-f','--fun', dest= 'urlfun', type = str, action='store', help='for something fun') args = parser.parse_args() print args #if you receive an argument for the port from the command line if args.PORT != None: #make port = to the argument socket_function(args) if args.urlfun != None: socket_function(args) if __name__ == "__main__": main()
496961710ca3b9d804ed14fff4054b9c57a3497e
SpeCialmark/mini
/store-server/store/utils/helper.py
262
3.59375
4
def move(a, i, j): if i == j: return a b = [] for index, x in enumerate(a): if len(b) == j: b.append(a[i]) if index != i: b.append(x) if len(b) == j: b.append(a[i]) return b
94e29fbd748f1ab2053c73d207ec25aeaa772f19
Thommo27/BinomialExpansion
/Factorial.py
188
3.75
4
def fact(num): if (num == 0): value = 1 else: i = 1 value = 1 while (i <= num): value *= i i += 1 return(value)
2c0ec6a6a08de6bea218f93f056d65c7d534c7e0
Shivani161992/Leetcode_Practise
/BinaryTree/InorderSuccessorinBST.py
1,121
3.859375
4
class TreeNode: def __init__(self, x): self.val=x self.left=None self.right=None root=TreeNode(2) p=root class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': if root is None: return None else: found = False traverse = [] stack = [root] seen = set() while len(stack) != 0: getNode = stack[-1] if getNode.left and getNode.left not in seen: stack.append(getNode.left) else: stack.pop() seen.add(getNode) traverse.append(getNode.val) if getNode.val == p.val and found == False: found = True elif getNode.val != p.val and found == True: return getNode if getNode.right and getNode.right not in seen: stack.append(getNode.right) return None obj=Solution() print(obj.inorderSuccessor(root, p))
36234bc944fb11a699034b5d0c42f864a7f36f83
fnwiya/atCoder
/abc/abc014/a.py
137
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- a = int(input()) b = int(input()) if a % b == 0: print(0) else: print(b - (a % b))
9c5f76e202e4facff2d0dd6c3b8d0073bfc003cf
anjaligopi/leetcode
/daily_coding_challenge/october_2020/valid_square_593.py
1,406
3.875
4
""" Question: Given the coordinates of four points in 2D space, return whether the four points could construct a square. The coordinate (x,y) of a point is represented by an integer array with two integers. Example: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True """ from typing import List import pytest class Solution: def valid_square(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool: if p1 == p2 == p3 == p4: return False def dist(x, y): return (x[0]-y[0])**2 + (x[1]-y[1])**2 # for square, sides and diagonal must be equal. Only sides is just rhombus # If you sort, you get 4 sides first and then diags lis = [dist(p1, p2), dist(p1, p3), dist(p1, p4), dist(p2, p3), dist(p2, p4), dist(p3, p4)] lis.sort() print(lis) if lis[0] == lis[1] == lis[2] == lis[3]: # sides if lis[4] == lis[5]: # diagonal return True return False @pytest.mark.timeout(3) @pytest.mark.parametrize( "p1, p2, p3, p4, ans", [([0,0], [1,1,], [1,0], [0,1], True)] ) def test_valid_square(p1, p2, p3, p4, ans): sol1 = Solution() assert sol1.valid_square(p1, p2, p3, p4) == ans # pytest daily_coding_challenge/october_2020/valid_square_593.py --maxfail=4
3a20254abcd84124edb2c9eba05b39acaf91e2c0
PRAWINM/beginner
/set10 92.py
82
3.5
4
N=int(input("")) n=[] for i in range(0,N): n.append(int(input())) print(sum(n))
b8a4b1384cad9ce860113f3543f16822b088da0b
ahalaru/udacity_ml_enron_final
/final_project/trainer.py
3,314
3.515625
4
#!/usr/bin/python from sklearn.model_selection import StratifiedShuffleSplit """ Perform training with a given classifer, label and features We use the Stratified Shuffle Split to perform the training over n-folds of training, test and cross-validation We also calculate the effectiveness of our classfier. The following metrics are calculated and printed Accuracy, Precision, Recall and F1 and F2 Score. """ PERF_FORMAT_STRING = "\n\ \tAccuracy: {:>0.{display_precision}f}\tPrecision: {:>0.{display_precision}f}\t\ Recall: {:>0.{display_precision}f}\tF1: {:>0.{display_precision}f}\tF2: {:>0.{display_precision}f}" RESULTS_FORMAT_STRING = "\tTotal predictions: {:4d}\tTrue positives: {:4d}\tFalse positives: {:4d}\ \tFalse negatives: {:4d}\tTrue negatives: {:4d}" def train_classfier(clf, labels, features): sss = StratifiedShuffleSplit(n_splits = 1000, random_state=42) # We will include all the features into variable best_features, then group by their # occurrences. features_scores = {} true_negatives = 0 false_negatives = 0 true_positives = 0 false_positives = 0 for train_idx, test_idx in sss.split(features,labels): features_train = [] features_test = [] labels_train = [] labels_test = [] for ii in train_idx: features_train.append(features[ii]) labels_train.append(labels[ii]) for jj in test_idx: features_test.append(features[jj]) labels_test.append(labels[jj]) ### fit the classifier using training set, and test on test set clf.fit(features_train, labels_train) predictions = clf.predict(features_test) for prediction, truth in zip(predictions, labels_test): if prediction == 0 and truth == 0: true_negatives += 1 elif prediction == 0 and truth == 1: false_negatives += 1 elif prediction == 1 and truth == 0: false_positives += 1 elif prediction == 1 and truth == 1: true_positives += 1 else: print "Warning: Found a predicted label not == 0 or 1." print "All predictions should take value 0 or 1." print "Evaluating performance for processed predictions:" break try: total_predictions = true_negatives + false_negatives + false_positives + true_positives accuracy = 1.0 * (true_positives + true_negatives) / total_predictions precision = 1.0 * true_positives / (true_positives + false_positives) recall = 1.0 * true_positives / (true_positives + false_negatives) f1 = 2.0 * true_positives / (2 * true_positives + false_positives + false_negatives) f2 = (1 + 2.0 * 2.0) * precision * recall / (4 * precision + recall) print clf print PERF_FORMAT_STRING.format(accuracy, precision, recall, f1, f2, display_precision=5) print RESULTS_FORMAT_STRING.format(total_predictions, true_positives, false_positives, false_negatives, true_negatives) print "" except: print "Got a divide by zero when trying out:", clf print "Precision or recall may be undefined due to a lack of true positive predicitons."
70237f04cf8954cddacc7c048e8a31127432d717
clhking/lpthw
/ex6.py
1,244
4.40625
4
#!/usb/bin/python # Set a variable named x that contains a sentence with an integer variable in it. x = "There are %d types of people." % 10 # Set a variable named binary that is a string: "binary" binary = "binary" # Set a variable named do_not that is a string "don't" do_not = "don't" # Set a variable y that is a string made of a sentence with two variables, binary and do_not y = "Those who know %s and those who %s." % (binary, do_not) # Print variable "x" print x # Print variable "y" print y # Print variable x as part of a string using the %r method. print "I said: %r." % x # Print varialbe y as a string input into a string. print "I also said: '%s'." % y # Set a variable that is the boolean reserved word "False", not a string hilarious = False # Set a variable joke_evaluation and concat a string/sentence and pull in hilarious using %r joke_evaluation = "Isn't that joke so funny?! %r" # Print joke evaulation but pull in hilarious as the variable for the %r in joke_evaluation print joke_evaluation % hilarious # Set a variable w that is a string w = "This is the left side of..." # Set a varialble e that is a string e = "a string with a right side." # Print w and e as a concat using the "+" symbol print w + e
b64bfaf09a79551ff50403c3d406eda93dc897ad
igor-baiborodine/coding-challenges
/hackerrank/python/built-ins_ginorts-solution.py
393
4
4
string = list(input().strip()) lower = [s for s in string if s.islower()] upper = [s for s in string if s.isupper()] odd_digits = [int(s) for s in string if s.isnumeric() and int(s) % 2 == 1] even_digits = [int(s) for s in string if s.isnumeric() and int(s) % 2 == 0] print(''.join(sorted(lower) + sorted(upper) + [str(d) for d in sorted(odd_digits)] + [str(d) for d in sorted(even_digits)]))
40602ba37fc203d75700a5bfa615490112227208
sanjkm/ProjectEuler
/p103/optimum_subset_sums.py
8,544
3.53125
4
# optimal_subset_sums.py # Set Conditions: # 1) Any two distinct subsets have different sums across all of their elements # 2) If set A is larger than set B, then S(A) > S(B), S = sum across elts # We are given a set of size 7 satisfying (1) and (2) with sum equal to 255 # Problem is to find satisfying 7 element sets with lower sums than this # When looking at possible sets, the algo will view a set as the set of # differences between each number and the lowest value in the list # There are fewer conditions to check with this view, and we can pick # an appropriate starting number if the set of differences is valid import itertools, time from copy import copy # Determine the next valid value for the list greater than or equal to start_num # Curr_num_list is in the form of differences between each number and the # first value in the list # Checks if pairs are equal, triples are equal, ... to determine if new value # is valid def next_valid_value (curr_num_list, start_num, max_num): if len(curr_num_list) == 0: return start_num next_num_index = len(curr_num_list) + 1 if next_num_index == 2: last_num = curr_num_list[-1] if start_num > last_num: return start_num else: return last_num + 1 # Now, go through testing until finding a valid one test_num = start_num curr_num_set = set(curr_num_list) curr_num_set.add(0) # Makes checking easier by including this # Could add testing for test_num to make sure that it's not in simple sets # before doing larger testing while test_num < max_num: flag_break = 0 # Adding one to range indices below because we added zero to the set for set_num in range(4, next_num_index+2, 2): curr_num_set.add(test_num) comp_set_size = set_num / 2 # list of sets of size comp_set_size set_list = list(map(set, list(itertools.combinations (curr_num_set, comp_set_size)))) num_sets = len(set_list) sum_list = map(sum, set_list) if len(set(sum_list)) < num_sets: # means a sum repeats flag_break = 1 break if flag_break == 0: return test_num else: curr_num_set.remove(test_num) test_num += 1 return 0 #------------------------------------------------------------------------------ # Given an incomplete number list, this calculates the maximum possible # value of the next number in the list # It does this by checking the current maximum sum for the whole list # and ensuring that the set conditions hold def determine_max_value (curr_num_list, curr_max_sum, total_nums, min_first_val, max_first_val): curr_num_len = len(curr_num_list) if curr_num_len == total_nums - 1: print "No more numbers to add" return 0 # Lowest possible sum is if all numbers are consecutive # This is not actually possible, but does leave a conservative estimate if curr_num_len == 0: max_val = (curr_max_sum - total_nums * min_first_val - ((total_nums-1)*(total_nums-2))/2) / (total_nums - 1) return max_val curr_total = sum (curr_num_list) remaining_nums = total_nums - curr_num_len - 1 # Assumes initial val = 10, all values going forward are consecutive # Calculates the maximum value that will keep the total sum less than # curr_max_sum max_val = (curr_max_sum - total_nums * min_first_val - curr_total - ((remaining_nums-1)*(remaining_nums-2))/2) / remaining_nums # Derive potentially better estimate of max_first_val by checking total test_num_list = copy(curr_num_list) while len(test_num_list) < total_nums - 1: test_num_list.append(test_num_list[-1]+1) max_first_val = min(max_first_val, (curr_max_sum - sum(test_num_list)) / total_nums) return min(max_val, max_value_conditions (curr_num_list, curr_max_sum, total_nums, max_first_val)) def max_value_conditions (curr_num_list, curr_max_sum, total_nums, max_initial_value): # We'll assume that all remaining numbers are consecutive # This is the most conservative assumption for ensuring that # the smallest triple is bigger than biggest pair, ... curr_num_len = len(curr_num_list) remaining_num_len = total_nums - curr_num_len - 1 full_num_list = [linear_var(0,x) for x in curr_num_list] # real numbers i = 0 while len(full_num_list) < total_nums - 1: full_num_list.append(linear_var(1, i)) # x + i, where x is the var i += 1 # will compare the first comp_num and final comp_num elements # to relate x to our initial value comp_num = (total_nums - 1) / 2 initial_elts_sum = sum(full_num_list[:comp_num]) final_elts_sum = sum(full_num_list[-1*comp_num:]) # This will be in the form ax + b, where a is positive # This must be smaller than the initial value of our list # for the sum of the first comp_num + 1 elts to be greater than the # last comp_num elts # We use the value for max_initial_value to derive a relationship # for x diff_elts = final_elts_sum - initial_elts_sum max_val = (max_initial_value - diff_elts.b) / diff_elts.a return max_val # Linear variable, where (3,2) represents 3x + 2 # We'll use this class to solve for the maximum possible x class linear_var: def __init__ (self, a, b): self.a = a self.b = b self.val = (a,b) def __add__ (self, other): a_new = self.a + other.a b_new = self.b + other.b return linear_var (a_new, b_new) def __radd__ (self, other): if other == 0: return self else: return self.__add__(other) def __sub__ (self, other): a_new, b_new = self.a - other.a, self.b - other.b return linear_var (a_new, b_new) #------------------------------------------------------------------------------ # Recursive function that calls itself for each additional element to the # test list def find_optimum_set (total_nums, min_first_val, max_first_val, curr_max_sum, curr_num_list, curr_best_list): # Base case if len(curr_num_list) == total_nums - 1: init_val = smallest_initial_val (curr_num_list) return [init_val] + map(lambda x: x + init_val, curr_num_list) if len(curr_num_list) == 0: init_num = 1 else: init_num = curr_num_list[-1] + 1 max_num = determine_max_value (curr_num_list, curr_max_sum, total_nums, min_first_val, max_first_val) i = init_num new_best_list = copy (curr_best_list) i = next_valid_value (curr_num_list, i, max_num) while i <= max_num and i != 0: test_num_list = copy(curr_num_list) test_num_list.append(i) result = find_optimum_set (total_nums, min_first_val, max_first_val, curr_max_sum, test_num_list, new_best_list) if result != 0: if sum(result) < curr_max_sum: curr_max_sum = sum(result) new_best_list = copy(result) i = next_valid_value (curr_num_list, i+1, max_num) return new_best_list # Called by above function when valid set is identified. It finds the # smallest initial value for that set to be valid def smallest_initial_val (curr_num_list): comp_list = len(curr_num_list) / 2 max_val = (sum(curr_num_list[-1*comp_list:]) - sum(curr_num_list[:comp_list])) return (max_val + 1) #----------------------------------------------------------------------------- def main(): start_time = time.time() curr_best_list = [20, 31, 38, 39, 40, 42, 45] # given in question curr_max_sum = sum (curr_best_list) # Min value is to ensure that the sum of the last 3 terms is less than # the first four's sum. # Max value is determined by the curr_max_sum min_first_val, max_first_val = 10, 34 total_nums = len(curr_best_list) print find_optimum_set (total_nums, min_first_val, max_first_val, curr_max_sum, [], curr_best_list) print time.time() - start_time main()
ffec48e954c4481350d9e606316c99d99194e7ac
FelipeMQ/CS1100
/week6/2encriptar.py
630
3.53125
4
frase = input() alfabeto = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','Y','X','Z'] cripto = ['#','$','%','&','/','(',')','=','?','.',',','!','°','|','¬','\\','^','~','*','+','-','_','<','>',':',';'] salida = [] for c in frase: if c == " ": salida.append(" ") continue if c in alfabeto: cnt=0 ind=0 for a in alfabeto: if a==c: ind = cnt cnt = cnt + 1 salida.append(cripto[ind]) else: print("Debe ingresar la frase en mayúsculas.") break print("".join(salida))
4fc183e46028afaaa379f9e8a0fff4dd844a09e5
novayo/LeetCode
/0222_Count_Complete_Tree_Nodes/try_2.py
1,016
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: ''' 先找最左邊 => 得知深度 在找右邊 => 第一個hit return ''' if not root: return 0 high = 1 tmp = root while tmp.left: high += 1 tmp = tmp.left ans = None def dfs(node, num=1, layer=1): nonlocal ans if ans: return if not node: return if layer == high: ans = num return dfs(node.right, num*2+1, layer+1) dfs(node.left, num*2, layer+1) dfs(root) return ans
17dfea1505e068f0da857b6a41ee00b91cd58c04
14Praveen08/Python
/odd_in_number.py
256
3.671875
4
number = int(input()) list1=[] while number > 0: mod = number % 10 if mod%2 != 0: list1.append(mod) number = number // 10 list1.sort() for i in range(0,len(list1)): if i == (len(list1))-1: print(list1[i],end="") else: print(list1[i],end=" ")
a39d75982c1c47ba227caf3f19935b68370fd6f6
rmessina1010/python_fundamentals_ww4
/workshop4.py
3,904
4.03125
4
class User: def __init__(self, name, pin, password): self.name = name self.pin = pin self.password = password def change_name(self, new_name): #new_name = input("New name: ") self.name = new_name def change_pin(self, new_pin): #new_pin = input("New PIN: ") self.pin = new_pin def change_password(self, new_password): #new_password = input("New password: ") self.password = new_password class Bank_User(User): def __init__(self, name, pin, password): super().__init__(name, pin, password) self.balance = 0 def show_balance(self): print(f"{self.name} has a current balace of: ${self.balance}") def withdraw(self, amount): if (self.balance >= amount): self.balance -= amount return True else: print("Insuficentfunds. Transaction cancelled.") return False def deposit(self, amount): if (amount > 0): self.balance += amount return True else: print("Deposits must be a positive amount. Transaction cancelled.") return False def transfer_money(self, amt, user): print(f"You are transfering ${amt} to {user.name}") print("Authentication required") PIN_check = self.check_PIN(input("Enter your PIN: ")) if PIN_check == True: print("Transfer Authorized") if user.deposit(amt): self.withdraw(amt) print(f"Transfering ${amt} to {user.name}") return True else: return False return self.cancel_transaction(PIN_check) def request_money(self, amt, user): print(f"You are requesting ${amt} from {user.name}") print("User uthentication required...") PIN_check = user.check_PIN(input(f"Enter {user.name}'s PIN: ")) if PIN_check != True: return self.cancel_transaction(PIN_check) pass_check = self.check_password(input(f"Enter your password: ")) if pass_check != True: return self.cancel_transaction(pass_check) print("Request Authorized") if user.withdraw(amt): self.deposit(amt) print(f"{user.name} sent ${amt}") return True return False def check_PIN(self, PIN): if PIN == str(self.pin): return True return ("Inavlid pin.") def check_password(self, password): if self.password == password: return True return ("Inavlid password.") def cancel_transaction(self, err): print(err, " Transaction cancelled") return False # Driver Code for Task 1 """ test_user = User("Bob", 1234, "password") print(test_user.name, test_user.pin, test_user.password) """ # Driver Code for Task 2 """ test_user = User("Bob", 1234, "password") print(test_user.name, test_user.pin, test_user.password) test_user.change_name("Bobby") test_user.change_pin(4321) test_user.change_password("newpassword") print(test_user.name, test_user.pin, test_user.password) """ # Driver Code for Task 3 """ test_user = Bank_User("Bob", 1234, "password") print(test_user.name, test_user.pin, test_user.password, test_user.balance) """ # Driver Code for Task 4 """ test_user = Bank_User("Bob", 1234, "password") test_user.show_balance() test_user.deposit(1000) test_user.show_balance() test_user.withdraw(500) test_user.show_balance() """ # Driver Code for Task 5 user1 = Bank_User("Ray", 9090, "havoc") user2 = Bank_User("Veronica", 9044, "bushy") user2.deposit(5000) user2.show_balance() user1.show_balance() did_transfer = user2.transfer_money(500, user1) user2.show_balance() user1.show_balance() if (did_transfer == True): user2.request_money(250, user1) user2.show_balance() user1.show_balance()
cdad157a06b2de64bc6158cded769ed9a4e3e5d6
zhoufengzd/python
/_exercise/hackerrank/certified/basic/swap_word_and_case.py
238
4.125
4
def swap_word_and_case(input_str): words = input_str.split() words_rev = " ".join([w.swapcase() for w in reversed(words)]) print(words_rev) if __name__ == "__main__": input_str = input() swap_word_and_case(input_str)
319fbb93152a7b18f7467cf510f2aa2cc57cfddb
khyati16050/practice
/special.py
1,266
3.890625
4
# In a list of number, check if the list is special ( always increasing and has 2 primes or always decreasing and has 1 prime) def increasing(a): if len(a) < 2: return True else: for i in range(1, len(a)): if a[i] < a[i - 1]: return False return True def decreasing(a): if len(a) < 2: return True else: for i in range(1, len(a)): if a[i] > a[i - 1]: return False return True def check_special(a): check_bool = False if (increasing(a)): count = 0 for i in range(len(a)): if (isPrime(a[i])): count += 1 if (count == 2): check_bool = True if (decreasing(a)): count = 0 for i in range(len(a)): if (isPrime(a[i])): count += 1 if (count == 1): check_bool = True return check_bool def isPrime(num): # check if num is prime if num == 1: return False for i in range(2, num): if num % i == 0: return False # No number in the range (2,num) divide num # hence , return True a = [1, 2, 4, 5, 6] print(check_special(a)) # print(increasing(a)) # print(decreasing(a))
cb7260a8dce6f61dac0ea6ec8bdd890d98acfaf9
ashishjsharda/PythonSamples
/iteratorsexample.py
129
3.828125
4
''' Using Iterators in Python @author: asharda ''' fruits=["apple","banana","grape"] for fruit in fruits: print(fruit)
7802e87ce6cd55ee3395d91253baa33258431398
HimavarshiniKeshoju/AI-Track-ML
/17K41A05F8-ANN-P10-3.py
5,559
3.578125
4
import pandas as pd import numpy as np data=pd.read_csv("D:\LoadDatainkW.csv") data.head() data.shape #x=data[0:-1, 2] #y=data[1:,2] x = data.iloc[0:-1, 2] y = data.iloc[1:, 2] normalized_datax=(x-x.mean())/x.std() normalized_datax normalized_datay=(y-y.mean())/y.std() normalized_datay from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(normalized_datax,normalized_datay,test_size = 0.10, random_state = 42) def define_structure(X, Y): input_unit = X.shape[0] hidden_unit = 2394 # (1.5*1596) output_unit = Y.shape[0] return (input_unit, hidden_unit, output_unit) (input_unit, hidden_unit, output_unit) = define_structure(X_train, y_train) print("The size of the input layer is: = " + str(input_unit)) print("The size of the hidden layer is: = " + str(hidden_unit)) print("The size of the output layer is: = " + str(output_unit)) def parameters_initialization(input_unit, hidden_unit, output_unit): np.random.seed(2) W1 = np.random.randn(hidden_unit, input_unit)*0.01 b1 = np.zeros((hidden_unit, 1)) W2 = np.random.randn(output_unit, hidden_unit)*0.01 b2 = np.zeros((output_unit, 1)) parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters def sigmoid(z): return 1/(1+np.exp(-z)) def forward_propagation(X, parameters): W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = {"Z1": Z1,"A1": A1,"Z2": Z2,"A2": A2} return A2, cache def cross_entropy_cost(A2, Y, parameters): m = Y.shape[1] logprobs = np.multiply(np.log(A2), Y) + np.multiply((1-Y), np.log(1 - A2)) cost = - np.sum(logprobs) / m cost = float(np.squeeze(cost)) return cost def backward_propagation(parameters, cache, X, Y): #number of training example m = X.shape[1] W1 = parameters['W1'] W2 = parameters['W2'] A1 = cache['A1'] A2 = cache['A2'] dZ2 = A2-Y dW2 = (1/m) * np.dot(dZ2, A1.T) db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1/m) * np.dot(dZ1, X.T) db1 = (1/m)*np.sum(dZ1, axis=1, keepdims=True) grads = {"dW1": dW1, "db1": db1, "dW2": dW2,"db2": db2} return grads def h(a,b,x): return a*x+b def mse(a,b,x,y): return np.mean((h(a,b,x) - y)**2) def gradient(a,b,x,y): return np.mean(x*(a*x+b-y), axis=-1), np.mean(a*x+b-y, axis=-1) def widrow_hoff(y, b, eta, theta, a, color): k = 0 normalcount = 1 while True: neweta = eta / normalcount product = neweta * (b - np.dot(a, y[k])) newvector = product * y[k] newvalue = np.linalg.norm(newvector) # print newvalue a = a + newvector if newvalue < theta: break normalcount += 1 k = (k + 1) % len(y) x = np.array([0, 10]) y = (-a[0] - a[1] * x) / a[2] plt.plot(x, y, color=color) print a return normalcount m = 1 #Initial value of slope c = -1 #Initial value of intercept lr = 0.01 #Learning Rate delta_m = 1 #Initialising Δm delta_c = 1 #Initialising Δc max_iters = 1000 #Maximum number of iterations iters_count = 0 #Counting Iterations def deriv(m_f, c_f, datax, datay): m_deriv = 0 c_deriv = 0 for i in range(datax.shape[0]): x, y = datax[i], datay[i] m_deriv += (y-m_f*x-c_f)*x c_deriv += (y-m_f*x-c_f) m_deriv = -m_deriv/len(datax) c_deriv = -c_deriv/len(datay) return m_deriv, c_deriv while iters_count < max_iters: delta_m, delta_c = deriv(m, c, x_train, y_train) delta_m = -lr * delta_m delta_c = -lr * delta_c m += delta_m c += delta_c iters_count += 1 print(f"Iteration: {iters_count}\tValue of m: {m}, \tValue of c: {c}") print(f"\nThe local minima occurs at: {m}, {c}") def neural_network_model(X, Y, hidden_unit, num_iterations = 1000): np.random.seed(3) input_unit = define_structure(X, Y)[0] output_unit = define_structure(X, Y)[2] parameters = parameters_initialization(input_unit, hidden_unit, output_unit) W1 = parameters['W1'] b1 = parameters['b1'] W2 = parameters['W2'] b2 = parameters['b2'] for i in range(0, num_iterations): A2, cache = forward_propagation(X, parameters) cost = cross_entropy_cost(A2, Y, parameters) grads = backward_propagation(parameters, cache, X, Y) parameters =widrow_hoff(parameters, grads) if i % 5 == 0: print ("Cost after iteration %i: %f" %(i, cost)) return parameters parameters = neural_network_model(X_train, y_train, 4, num_iterations=1000) def prediction(parameters, X): A2, cache = forward_propagation(X, parameters) predictions = np.round(A2) return predictions predictions = prediction(parameters, X_train) print ('Accuracy Train: %d' % float((np.dot(y_train, predictions.T) + np.dot(1 - y_train, 1 - predictions.T))/float(y_train.size)*100) + '%') predictions = prediction(parameters, X_test) print ('Accuracy Test: %d' % float((np.dot(y_test, predictions.T) + np.dot(1 - y_test, 1 - predictions.T))/float(y_test.size)*100) + '%')
0c2d41d6dc48e596102ec0fe376a3fd4a9407063
naveenbe66/guvi
/pro33.py
148
3.515625
4
a2=input() c=0 for i in range(1,len(a2)): if a2[i]>a2[0]: r=a[i:] c=c+1 break if c>0: print(r) else: print(a2)
0230f4e1db2d305533a2dacdbb47d2b0eba32564
karthik0037/lab2-test-01-09-20
/count the number of nodes.py
1,215
4.3125
4
# Python3 program to remove first node of # linked list. import sys # Link list node class Node: def _init_(self, data): self.data = data self.next = None # Function to remove the first node # of the linked list def removeFirstNode(head): if not head: return None temp = head # Move the head pointer to the next node head = head.next temp = None return head # Function to push node at head def push(head, data): if not head: return Node(data) temp = Node(data) temp.next = head head = temp return head # Driver code if _name=='main_': # Start with the empty list head = None # Use push() function to construct # the below list 8 -> 23 -> 11 -> 29 -> 12 head = push(head, 12) head = push(head, 29) head = push(head, 11) head = push(head, 23) head = push(head, 8) head = removeFirstNode(head) while(head): print("{} ".format(head.data), end ="") head = head.next
1343488219e8ca08e6512d53b4bfd8c1c8ac5f04
IwoStaykov/Hania-kolos
/League.py
865
3.5625
4
req_list = input().split() #wprowadzenie N, M i T req_list = [int(req_list[i]) for i in range(3)] #req_dict = {'N': req_list[0], 'M': req_list[1], 'T': req_list[2]} teams = {} for i in range(req_list[0]): name = input() # teams[name] = [0,0] # pierwszy element listy to liczba wygranych , drugi element to liczba rozegranych meczy # teams['colorado'].append(2) for i in range(req_list[1]): match_note = input().split(':') #wpisanie wyników if match_note[2] > match_note[3]: teams[match_note[0]][0] += 1 #dodaj 1 do wygranych dla pierwszego gracza else: teams[match_note[1]][0] += 1 #dodaj 1 do wygranych dla drugiego gracza teams[match_note[0][1]] += 1 #dodaj 1 do rozegranych meczy teams[match_note[1][1]] += 1 for i in range(req_list[0]): print(teams['colorado']) print(teams['new york'])
16188a91fda6981b7491ad5e35d397876db5b892
sthakare11/English_python
/English.py
562
3.6875
4
#! /usr/bin/python3 print ("Welcome!\n Ready to Learn English ??\n ##################################################") a=input("what Do you want to revise?\n 1.Tenses\n 2.Articles\n Please enter your choice\n") a=int(a) #def case(a): # switcher = { # 1:'This works', # 2:'This also', # } #return switcher.get(a,"OK") #a=input("what Do you want to revise?\n 1.Tenses\n 2.Articles\n Please enter your choice") #a=int(a) if a == 1 : import os os.system('python3 ne1.py') else : print("Work in Progress")
977dc9b06df79af833bf14c9ee147a90424a165a
vinceparis95/garage
/machineLearning/instruments/classifiers/data_classifiers/binary_classifier_b.py
1,821
3.859375
4
import numpy as np import pandas as pd import tensorflow as tf import keras from tensorflow import feature_column from tensorflow.python.keras import layers from sklearn.model_selection import train_test_split csv = "/home/vince/Desktop/youthy.csv" df = pd.read_csv(csv) print(df.head()) train, test = train_test_split(df, test_size=0.2) train, val = train_test_split(train, test_size=0.2) print(len(train), 'train examples') print(len(val), 'validation examples') print(len(test), 'test examples') # A utility method to create a tf.data dataset from a Pandas Dataframe def df_to_dataset(dataframe, shuffle=True, batch_size=32): dataframe = dataframe.copy() labels = dataframe.pop('Trained') ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(dataframe)) ds = ds.batch(batch_size) return ds batch_size = 5 # A small batch sized is used for demonstration purposes train_ds = df_to_dataset(train, batch_size=batch_size) val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size) test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size) for feature_batch, label_batch in train_ds.take(1): print('Every feature:', list(feature_batch.keys())) print('A batch of neighborhoods:', feature_batch['Neighborhood']) print('A batch of ages:', label_batch ) # We will use this batch to demonstrate several types of feature columns example_batch = next(iter(train_ds))[0] # A utility method to create a feature column # and to transform a batch of data def demo(feature_column): feature_layer = tf.compat.v1.keras.layers.DenseFeatures(feature_column) print(feature_layer(example_batch).numpy()) age = feature_column.numeric_column("Age") demo(age) # based on TensorFlow mL basics classifier for structured data
9536afe317b11ca9fe262fe3b06f5ffdd1a2b391
poorvijajodiya/Tkinter
/Radio_Button.py
784
3.765625
4
from tkinter import * root = Tk() #r=IntVar() #r.set("2") Modes = [("Pepperoni","Pepperoni"),("Onion","Onion"),("Cheese","Cheese"),("mashroom","mashroom")] pizza = StringVar() pizza.set("Pepperoni") for text,mode in Modes: Radiobutton(root,text=text,variable=pizza, value=mode).pack(anchor=W) def clicked(value): my_label = Label(root, text=value) my_label.pack() #Radiobutton(root, text="option 1", variable=r, value=1, command=lambda : # clicked(r.get())).pack() #Radiobutton(root, text="option 2", variable=r, value=2, command=lambda : # clicked(r.get())).pack() #my_label = Label(root,text=pizza.get()) #my_label.pack() b = Button(root, text="click_me", command=lambda : clicked(pizza.get())).pack() root.mainloop()
7f16b608fc86c5910f86a0d422c7434b780bf332
ArdelAlegre1/SoundMapping
/Analysis/Util/Tools.py
2,096
3.75
4
import datetime import time """ computes unix time from time string @param string start - start time in string @param string end - end time in string @return float unixtime_start @return float unixtime_end """ def strTime_to_unixTime(start, end): try: FORMAT_TIMESTRING = '%b %d %Y %I:%M%p' dt_start = datetime.datetime.strptime(start, FORMAT_TIMESTRING) dt_end = datetime.datetime.strptime(end, FORMAT_TIMESTRING) except ValueError: FORMAT_TIMESTRING = '%b %d %Y %I:%M:%S%p' dt_start = datetime.datetime.strptime(start, FORMAT_TIMESTRING) dt_end = datetime.datetime.strptime(end, FORMAT_TIMESTRING) unixtime_start = time.mktime(dt_start.timetuple()) unixtime_end = time.mktime(dt_end.timetuple()) return unixtime_start, unixtime_end """ returns the slice of matrix corresponding to start and end timestamps @param ndarray - data with 0th column with time in seconds @param string - start timestring with format '%b %d %Y %I:%M:%S%p' @param string - end timestring with format '%b %d %Y %I:%M:%S%p' @return int - index of first element of data with time greater than start @return int - index of last element of data with time less than end """ def slice_interval_indices(data, start_timestring, end_timestring): format_timestring = '%b %d %Y %I:%M:%S%p' # setting format of input time # convert input timestrings to unix time start_standard_dt_string = datetime.datetime.strptime(start_timestring, format_timestring) end_standard_dt_string = datetime.datetime.strptime(end_timestring, format_timestring) unix_start_timestring = datetime.datetime.timestamp(start_standard_dt_string) unix_end_timestring = datetime.datetime.timestamp(end_standard_dt_string) for x in range(data.shape[0]): if(data[x,0] > unix_start_timestring and data[x,0] < unix_end_timestring): start_index = x break for y in range(x,data.shape[0]): if(data[y,0] > unix_end_timestring): end_index = y break return(x,y)
5d92a1ca5b6a6171bb92dd22cc159063c6ed289c
DrRenuwa/MIT-Course
/Lessons/Unit 2 Iterative Exponent.py
591
3.796875
4
def iterPower(base, exp): ans = base while exp > 1: if base < 0 and exp%2 == 0: ans *= base exp -= 1 base = -base else: ans *= base exp -= 1 if exp == 0: ans = 1 return ans print(iterPower(-4, 0)) ''' def iterPower(base, exp): ans = base for i in range(1, exp): ans *= base if exp%2 == 1: ans = -ans if exp == 0: ans = 1 return ans print(iterPower(-4, 2)) '''
05fee2f8277c43f0d435880424da04469ed7dce9
Sxlly/Hangman-PyGame
/main.py
3,630
3.71875
4
import pygame import random import os import numpy as np import math # Setting display variables pygame.init() pygame.font.init() WIDTH, HEIGHT = 800, 500 win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("HANGMAN!") # defining button variables RADIUS = 20 GAP = 15 letters = [] start_x = round((WIDTH - (RADIUS * 2 + GAP) * 13) / 2) start_y = 400 A = 65 for i in range(26): x = start_x + GAP * 2 + ((RADIUS * 2 + GAP) * (i % 13)) y = start_y + ((i // 13) * (GAP + RADIUS * 2)) letters.append([x, y, chr(A + i), True]) # creating of fonts LETTER_FONT = pygame.font.SysFont('yumin', 20) WORD_FONT = pygame.font.SysFont('yumin', 45) TITLE_FONT = pygame.font.SysFont('yumin', 65) # loading hangman image files images = [] # indexing between 1-7 because list is 1-6 length and 7 isn't inclusive for i in range(7): image = pygame.image.load(os.path.join("hangman", "hangman" + str(i) + ".png")) images.append(image) # setting up game variables hangman_status = 0 word = str(input("please select a word to be guessed: ").upper()) #note: This Word Needs To Be in Caps guessed = [] # Colors variables WHITE = (255,255,255) BLACK = (0,0,0) # setting up gameplay loop FPS = 60 clock = pygame.time.Clock() run = True def draw(): win.fill(BLACK) # code for drawing title text = TITLE_FONT.render("HANGMAN", 1, WHITE) win.blit(text, (WIDTH/2, 50)) # code for drawing words display_word = "" for letter in word: if letter in guessed: display_word += letter + " " else: display_word += "_ " text = WORD_FONT.render(display_word, 1, WHITE) win.blit(text, (400, 200)) # code for drawing buttons for letter in letters: x, y, ltr, visible = letter if visible: pygame.draw.circle(win, WHITE, (x, y), RADIUS, 3) text = LETTER_FONT.render(ltr, 1, WHITE) win.blit(text, (x - text.get_width()/2, y - text.get_height()/2)) win.blit(images[hangman_status], (150,100)) pygame.display.update() # end screen message display function def display_endscreen(message): pygame.time.delay(1000) win.fill(BLACK) text = WORD_FONT.render(message, 1, WHITE) win.blit(text, (WIDTH/2 - text.get_width()/2, HEIGHT/2 - text.get_height()/2 - 100)) pygame.display.update() def display_endimage(num): image = pygame.image.load(os.path.join("hangman", "hangman" + str(num) + ".png")) win.blit(image, (WIDTH/2 - 55, 200)) pygame.display.update() pygame.time.delay(2000) # While GameLoop is Running while run: clock.tick(FPS) draw() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: m_x, m_y = pygame.mouse.get_pos() for letter in letters: x, y, ltr, visible = letter if visible: distance = math.sqrt((x - m_x)**2 + (y - m_y)**2) if distance < RADIUS: letter[3] = False guessed.append(ltr) if ltr not in word: hangman_status += 1 won = True for letter in word: if letter not in guessed: won = False break if won: display_endscreen("You Won!!!") display_endimage("0") break if hangman_status == 6: display_endscreen("You Lost!!!") display_endimage("6") break pygame.quit()
1ae01a247c8c04fcf1461f10962ab533c804f7fa
roachj33/CSE-163-Final-Project---Movie-Analysis
/Project_functions.py
13,760
3.65625
4
""" Name: Joey Roach Date: June 10th 2020 Implements the functions required for project analysis, including cleaning the data, calculating profits, analyzing profit trends over a variety of differing circumstances and performing machine learning algorithms to predict a film's IMDB score based on other factors. """ import pandas as pd import plotly.express as px import numpy as np import os from sklearn import linear_model from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score from sklearn.preprocessing import StandardScaler def clean_data(data, initial=True): """ Given a pandas data frame of movie data, cleans the data for analytical purposes. If initial is true, this means that films in the dataset that do not have budget nor gross data are removed. If initial is false, only films that are rated G, PG, PG-13 or R are kept in the dataset. Arguments: data: A pandas dataframe of the movies.csv file. initial: A boolean to determine if this is the first time the data is being cleaned, which operates in the manner described above. Returns: A pandas data frame of movie data that has been cleaned as described above. """ copied = data.copy() if initial is True: # Create masks for no budget and no revenue. no_budget = copied['budget'] == 0 no_gross = copied['gross'] == 0 # Obtain films with both budget and gross information. copied = copied[(~ no_budget) & (~ no_gross)] else: # Create masks for MPAA ratings of films. g = copied['rating'] == 'G' pg = copied['rating'] == 'PG' pg_13 = copied['rating'] == 'PG-13' r = copied['rating'] == 'R' # Obtain films that are rated G, PG, PG-13, or R. copied = copied[g | pg | pg_13 | r] return copied def calculate_profit(data, average=False): """ Given a pandas data frame containing movie data, calculates the profit (which is defined as revenue - budget) for each film within the dataset. Arguments: data: A pandas data frame containing movie data. Returns: A pandas data frame with all of the input data columns, including appended profit data for the films. """ copied = data.copy() # Calculate profit for each film. copied['profit'] = copied['gross'] - copied['budget'] return copied def profit_by_genre(data): """ Given a pandas data frame, groups films according to the year that they were released and the genre they are in, determining the mean profit for each genre, for each year (The musical genre is omitted as there are an insufficient number of musical films in the movies.csv file), returning a data frame containing the annual average profit for each genre. Arguments: data: A pandas data frame containing movie data from movies.csv. Returns: A pandas data frame of the form described above. """ copied = data.copy() # Calculate average profit by genre by year, retaining data frame form. yearly = copied.groupby(['year', 'genre'], as_index=False)['profit'].mean() # Round profit to nearest whole number, for easier visualization purposes. yearly = yearly.round() # Exclude musical genre, as the dataset contains an insufficiently small # number of these types of films. musical = yearly['genre'] == 'Musical' yearly = yearly[~ musical] return yearly def save_figure(figure, file_name): """ Given a plotly figure object, and a file_name for the resulting graph, saves the graph to the "graphs" directory. If no such directory exists, it is created by this method. Arguments: figure: A plotly figure object that is the desired graph to be saved. file_name: A string representing the desired saved name of the graph. Returns: None. """ # If the graphs directory does not exist yet, creates it. if not os.path.exists('graphs'): os.mkdir('graphs') # Saves figure with given file_name. figure.write_image('graphs/' + file_name) def plot_genre_and_profits(data): """ Given a pandas data frame of annual average profit data by genre (i.e., of the type returned by the profit_and_genre function), creates a plot of the data, saves the figure and directs the user to an online version of it. Arguments: data: A data frame of the type returned by profit_by_genre Returns: None. """ # Plot profit of genres over time, faceting on the genre. fig = px.line(data, x='year', y='profit', title='Profit of genres over time', facet_col_wrap=3, facet_col='genre') # Save figure and display it. save_figure(fig, 'profit_of_genres.png') fig.show() def find_filmmaker_score(data, filmmaker_type): """ Given a pandas data frame, and the desired filmmaker type, calculates the average IMDB user score for each filmmaker of that type within the data. Arguments: data: A pandas data frame from the movies.csv file. filmmaker_type: A string argument representing the type of filmmaker to calculate the average score for. Expected inputs are "director", "writer", or "star". Returns: A pandas data frame with the average score for each filmmaker of the given filmmaker type appended to the end as a column. """ copied = data.copy() # Calculate average IMDB score for each filmmaker of the given type, # and append it to the return data frame. copied[filmmaker_type + '_score'] = \ copied.groupby(filmmaker_type)['score'].transform('mean') return copied def profit_by_category(categories): """ Given a dictionary called categories that maps from the IMDB score tier to the dataset containing film information for filmmakers within that tier, calculates the profit for each film in the tier and forms a column that ascribes each film to the tier, returning an updated version of the input dictionary with datasets that now reflect film profits and the tier they fall into. Arguments: categories: A dictionary that has the tier the film falls into (based upon the calculated filmmaker score) as keys and the filtered dataset according to filmmaker score as values. Returns: A dictionary with updated values of datasets that contain profit information and a column of strings that indicate which tier the films fall into. """ for category in categories: # obtain dataset for the category. data_set = categories[category] # Calculate the profit for each film in the tier. data_set = calculate_profit(data_set) # Create a column in the dataset that details what tier the film is in. data_set['rating_category'] = category # Update value for the key in the dictionary to be the modified data # set. categories[category] = data_set return categories def plot_filmmaker_trends(data, filmmaker_type): """ Given a pandas data frame and the filmmaker_type, sorts filmmakers within the type according to their average IMDB scores into three tiers, and produces a box plot visualization of the profit by each tier. Arguments: data: A pandas data frame of movie data, containing a column representing each filmmaker's average IMDB score. filmmaker_type: A string argument representing the desired type of filmmaker to display profit and tier information for. Returns: None. """ # Obtain the average score for each filmmaker. score = data[filmmaker_type + '_score'] # Create masks to filter filmmakers into three tiers (bottom third, # middle third and top third) based upon their average IMDB score. bottom_mask = (score >= 0.0) & (score < 3.3) middle_mask = (score >= 3.3) & (score < 6.6) top_mask = score >= 6.6 # Obtain filtered data for each tier. bottom = data[bottom_mask] middle = data[middle_mask] top = data[top_mask] # Establish dictionary mapping from score tier to the associated # data frames. data_sets = {'bottom third': bottom, 'middle third': middle, 'top third': top} # Calculate profit for each tier. data_sets = profit_by_category(data_sets) # Bring all tier data frames into one data frame. categories = list(data_sets.values()) total = pd.concat(categories) # Plot box plot of profit by IMDB score tiers. fig = px.box(total, x='rating_category', y='profit', points=False, title='profit distribution by ' + filmmaker_type + ' IMDB perception') # Save figure and display it. save_figure(fig, filmmaker_type + '_profit_distribution.png') fig.show() def obtain_average_profit_by_rating(data): """ Given a pandas data frame of film data, calculates the average profit for films according to their MPAA rating, returning a data frame with these calculations appended as a column. Arguments: data: A pandas data frame of film data that contains profit data for each film. Returns: A pandas data frame with the average profit for each rating appended as a column. """ copied = data.copy() # Obtain column of average profit for each MPAA rating. copied['average_profit'] = \ copied.groupby('rating')['profit'].transform('mean') return copied def plot_profit_by_rating(data): """ Given a pandas data frame containing film and average profit data, produces a plotly box plot of the average profit by films according to their MPAA ratings (including only G, PG, PG-13 and R rated films), saving this visualization and displaying it. Arguments: data: A pandas data frame which has film and average profit data. Returns: None. """ # Obtain only films with MPAA ratings of G, PG, PG-13 or R. data = clean_data(data, initial=False) # Create box plot visualization, save it and display it. fig = px.box(data, x='rating', y='profit', points='all', title='Film profits by MPAA ratings') save_figure(fig, 'film_profits_by_rating.png') fig.show() def conduct_regression(data, lasso=False, rf=False): """ Given a pandas data frame containing film data from the movies.csv file, performs machine learning algorithms in order to determine if we can accurately predict a film's IMDB score based upon some set of independent variables. By default, linear regression is performed, although the method can construct lasso and random forest regressions if the given parameter is specified to be true. Only one type of model may be built from the method per call. Arguments: data: A pandas data frame containing film data. lasso: A boolean parameter to determine if lasso regression is used. This occurs if lasso is True. rf: A boolean parameter to determine if random forest regression is used. This occurs if rf is True. Returns: None. """ # In order to reproduce results, set random seed. np.random.seed(123) # Obtain features and label. desired = ['budget', 'company', 'country', 'director', 'genre', 'gross', 'rating', 'runtime', 'star', 'writer', 'votes', 'year'] features = data.filter(items=desired) label = data['score'] # Convert binary variables. features = pd.get_dummies(features) # Obtain a 80% training, 20% testing split of the data. x_train, x_test, y_train, y_test = \ train_test_split(features, label, test_size=0.20) # Standardize independent variables. scaler = StandardScaler().fit(x_train) x_train = scaler.transform(x_train) x_test = scaler.transform(x_test) if lasso is True: # Fit cross-validated lasso model, with 5 k-folds, number of alphas # is reduced from the default to speed up computation time. model = linear_model.LassoCV(cv=5, n_alphas=20).fit(x_train, y_train) elif rf is True: # Fit random forest regressor model, with the maximum number # of features used for each tree as the square root of the # number of features (default behavior). model = RandomForestRegressor(n_estimators=100) model.fit(x_train, y_train) else: model = linear_model.LinearRegression().fit(x_train, y_train) if rf is False: # Print out model coefficients for parametric models. coefficients = pd.DataFrame(model.coef_, features.columns, columns=['Coefficient']) print(coefficients) # Obtain predictions for the IMDB score on test set. y_test_pred = model.predict(x_test) print(type(y_test_pred)) # Round predictions to match format of actual IMDB scores. y_test_pred = np.round(y_test_pred, 1) # Acquire the mean squared error of the actual scores and the predicted # ones. test_error = mean_squared_error(y_test, y_test_pred) # Report on testing error rate, R2 value, and a portion of the actual # scores versus the predicted ones. results = pd.DataFrame({'Actual': y_test, 'Predicted': y_test_pred}) print(results) print('testing error is:', test_error) print('R2 value:', r2_score(y_test, y_test_pred))
e86825bdea2e1d2f60f7c8e4671d6e904240b805
Msubasi1/Hurap
/src/Mission00.py
2,264
3.734375
4
def encrypted(file, hex_result, encrypt_result): for line in hex_result: split_two = [] for index in range(0, len(line), 2): split_two.append(line[index: index + 2]) # print(split_two) line_result = "" # print("line_result = " + line_result) for keys in split_two: # print("keys == "+keys) for lines in file: splitted = lines.split("\t") # print("splitted[1] = "+splitted[1]) if splitted[1] == keys: line_result += splitted[0] # print(line_result) file.seek(0, 0) encrypt_result.append(line_result) def key_decryption(key): # print(key) string_key = "" for elements in key: for char in elements: if char != "0" and char != "1": continue else: string_key += char # print(string_key) def twos_comp(val, bits): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: val = val - (1 << bits) return val return twos_comp(int(string_key, 2), len(string_key)) def decrypted(file, shift_amount, encryption_result, decryption_result): # print(shift_amount) # print(encryption_result) for elements in encryption_result: dec_line = "" for char in elements: char_loc = 0 line_count = 1 for lines in file: splitted = lines.split("\t") # print("splitted[0] = "+splitted[0]) if splitted[0] == char: char_loc = line_count break line_count += 1 file.seek(0, 0) original_loc = (char_loc - shift_amount) % 94 line_count = 1 for lines in file: splitted = lines.split("\t") # print("splitted[0] = "+splitted[0]) if line_count == original_loc: dec_line += splitted[0] line_count += 1 file.seek(0, 0) decryption_result.append(dec_line)
85660ce6bf794d7ba0ed87b63ff9a2f934f30c90
pr4nshul/CFC-Python-DSA-March
/Alinpreet-Assign-1/A1-Q7-h.py
414
3.703125
4
n = 5 row=1 row_mirror = 1 while(row_mirror<=2*n-1): col=1 col_mirror = 1 while(col_mirror<=2*n-1): if(col<=(n-row)+1): print(' *',end="") else: print(' ',end="") if(col_mirror < n): col+=1 else: col-=1 col_mirror+=1 print() if(row_mirror < n): row+=1 else: row-=1 row_mirror+=1
cc069bb61b6a434fef33828184cd3878533ce2d2
dunderzutt/diablo3test
/diablo3.py
1,048
3.875
4
print(" Only enter numbers no prefix after as m,b or tr") print(" as sfp is included in gph you will need to check urself how many keys used per hour for exact") side1 = float(input(' T13 GPH: ')) side2 = float(input(' xp/hr getting keys in billions ex 55: ')) side3 = float(input(' input xp/hr with stacked in billions ex 1000 for 1t: ')) side4 = float(input(' Keys used per hour: ')) print(" 1r2gr information") bas = float(input(' 1r2gr xp/hr: ')) gph = side1 * 2 * 100 + (side1 * 100 / 4) circumference = side2 * 100 keys = gph / side4 hours = 100 + keys total = keys * side3 + circumference area = bas * hours print(" keys per 100 hours on average = %.2f" %gph) print(" xp after 100 hours of gathering keys in billions = %.2f" %circumference) print(" hours keys will last = %.2f" %keys) print(" total hours of t13 and using all keys = %.2f" %hours) print(" total exp after all hours = %.2f" %total) print(" total exp from 1r2gr same time = %.2f" %area) print(" Every number is in billions!") q = input("Enter to quit")
d1c6dd7b2d80edb1db31b1ae2ed6619e5a39e30a
pnoga190401/projekt
/python_inf/tabliczka.py
345
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tabliczka.py # def tabliczka(): for k in range(1, 11): for w in range(1, 11): print("{:>3} ".format(k * w), end='') print() def main(args): tabliczka() return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
3bbf935b509ec8609be3108aad3cb202a54d4a4b
robbyvan/-
/バックトラッキング/10_Regular Expression Matching.py
720
3.515625
4
# 10_Regular Expression Matching # 1) dp, 参见字符串10 # 2) 回溯. # class Solution: # def isMatch(self, s, p): # m, n = len(s), len(p) # dp = [[False] * (n + 2) for _ in range(m + 1)] # dp[0][0] = True # dp[0][1] = True # for j in range(n): # if p[j] == "*": # dp[0][j + 2] = dp[0][j] # for i in range(m): # for j in range(n): # if p[j] == "." or p[j] == s[i]: # dp[i + 1][j + 2] = dp[i][j + 1] # if p[j] == "*": # if p[j - 1] == s[i] or p[j - 1] == ".": # dp[i + 1][j + 2] = dp[i][j + 2] or dp[i + 1][j + 1] or dp[i + 1][j] # else: # dp[i + 1][j + 2] = dp[i + 1][j] # return dp[-1][-1]
22a68384b6e6281b9b1ef94511b9b0abc4b9acdd
geooff/ProjectEulerSolutions
/PE_Q36.py
1,448
3.765625
4
""" The decimal number, 585 = 1001001001(2) (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) Thoughts: - Due to the increased number of characters in base 10 palindroms are likely more rare - Limiting to under one milion 6 chars is the max length of a palindrome """ double_pals = 0 def is_binary_pal(n): binary = str(bin(n)[2:]) bin_pal = all([i == j for i, j in zip(binary, binary[::-1])]) if bin_pal: print(n, binary) return True for pal_length in range(1, 7): if pal_length % 2 == 0: # Pal is even length need len // 2 chars len_unique_chars = 10 ** (pal_length // 2) for i in range(len_unique_chars // 10, len_unique_chars): pal_part = str(i) pal = int(pal_part + pal_part[::-1]) if is_binary_pal(pal): double_pals += pal else: len_unique_chars = 10 ** (pal_length // 2) for i in range(10): for j in range(len_unique_chars // 10, len_unique_chars): pal_part = str(j) if j != 0: pal = int(pal_part + str(i) + pal_part[::-1]) else: pal = i if is_binary_pal(pal): double_pals += pal print(double_pals)
7cd785dd12712783da86821cc0d5abc420a38469
mailtoatanu/Python-Learning-Projects
/01. Dice Rolling Simulator.py
1,364
4.375
4
#This is Dice Rolling Simulator #Asks user minimum and maximum value of the dice #Throws up a random number within the minimum and the maximum number import random gameon = 'yes' #The game repeat controller print("Hello There! Welcome to an all new Dice Rolling Simulator!\n") #Welcome statement. Does not add value to the code #try-except block is used to make the workable all the time try: while gameon == 'yes': print("What is going to be the minimum value of your dice?") dice_min_val = int(input()) print("What is going to be the minimum value of your dice?") dice_max_val = int(input()) dice_output = random.randint(dice_min_val,dice_max_val) print("And here goes the result. The dice has rolled out to",dice_output) print("Do you want to roll another dice?(y/n)") user_input = input() while user_input != 'y' and user_input != 'n': #Check for valid input and ask for till a valid input is provided print("Input not recognized. Please provie y/n as valid input.") user_input = input() if user_input == 'n': gameon = "no" print("It was nice playing dice with you. Have a great day. Bye bye.") except: print("Oop! Something went wront. Please try again.")
4f6bc3069e7fbfed1fc5d6dfc6decaf52d8c4474
kluke6175/FinalProject.py
/2_2/Shapes.py
1,551
4.09375
4
import math class Shape: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return'<'+'Shape x='+str(self.x)+' y='+str(self.y)+'>' def area(self): print(self.x * self.y) class Circle(Shape): def __init__(self, x, y, radius): super().__init__(x, y) self.radius = radius def __repr__(self): return '<' + 'Circle x=' + str(self.x) + ' y=' + str(self.y) + ' Radius='+str(self.radius) + '>' def area(self): print(math.pi * self.radius ** 2) def circumference(self): print(2 * math.pi * self.radius) class Rectangle(Shape): def __init__(self, x, y): super().__init__(x, y) def __repr__(self): return '<' + 'Rectangle x=' + str(self.x) + ' y=' + str(self.y) + '>' def area(self): print(self.x * self.y) class Square(Rectangle): def __init__(self, x, y): super().__init__(x, y) def __repr__(self): return'<' + 'Square x=' + str(self.x) + ' y=' + str(self.y) + '>' def area(self): print(self.x * self.y) class Triangle(Shape): def __init__(self, x, y): super().__init__(x, y) def __repr__(self): return '<' + 'Triangle x=' + str(self.x) + ' y=' + str(self.y) + '>' def area(self): print(self.x * self.y * 0.5) p = Shape(1, 1) print(p) p.area() a = Circle(3, 4, 7) print(a) a.area() a.circumference() b = Rectangle(2, 8) print(b) b.area() c = Square(4, 4) print(c) c.area() d = Triangle(4, 6) print(d) d.area()