blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2c4619eae992331fb8566e593d3bfd57eaaceeb0
mjdall/leet
/medium/all_permutations.py
1,037
4
4
def permute(self, nums): """ Given a list of numbers, returns all possible permutations of the numbers. :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [] permutations = [] self.backtrack(permutations, nums, []) return permutations def backtrack(self, permutations, nums, current_combination): # if we've exhausted nums, then we've finished the current permutation if not nums: permutations.append(current_combination) return nums_len = len(nums) for i, num in enumerate(nums): # make the current combination this_combination = current_combination + [num] # remove the current number from remaining numbers remaining_nums = nums[:i] if i + 1 < nums_len: remaining_nums += nums[i+1:] # carry on trying to find a combination self.backtrack(permutations, remaining_nums, this_combination)
8f67d863c9edae98a5a44daf5c826381c9e4a873
vinayvarm/programs
/fun.py
162
3.703125
4
'''def add(a,b): c=a+b return c var=add(20,60) print(var)''' n= int(input("enter number")) if n>0: print('positive') else: print('negative')
e1b3aef3632d92313ea3c3506bcffeb8a4c69edc
eunj00/2020-Python-Code
/ch04/04-06nestedmenu.py
635
3.640625
4
category=int(input('원하는 음료는? 1.커피 2.주스')) if category==1: menu= int(input('번호 선택? 1.아메리카노 2.카페라떼 3.카푸치노')) if menu==1: print('1.아메리카노 선택') elif menu ==2: print('2.카페라떼 선택') elif menu ==3: print('3.카푸치노 선택') else: menu=int(input('번호 선택? 1.키위주스 2.토마토주스 3.오렌지주스')) if menu==1: print('1.키위주스 선택') elif menu ==2: print('2.토마토주스 선택') elif menu ==3: print('3.오렌지주스 선택')
bd3ef0f070984405fdf429073cd5708f7015d157
sbmarriott/nltk
/chapter2.py
3,867
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 15 22:13:37 2017 @author: Sarah Beth Marriott """ import nltk, random from nltk import FreqDist from nltk.corpus import gutenberg, state_union, brown # Question 2: Use the corpus module to explore austen-persuasion.txt. How many word tokens does this book have? How many word types? austen = gutenberg.words('austen-persuasion.txt') print('This book has ', len(austen), 'word tokens and ', len(set(austen)), 'word types.') len(set(austen)) # Question 3: Use the Brown corpus reader nltk.corpus.brown.words() or the Web text corpus reader nltk.corpus.webtext.words() to access some sample text in two different genres. nltk.corpus.brown.words(categories=['news']) nltk.corpus.brown.words(categories=['mystery']) # Question 4: Read in the texts of the State of the Union addresses, using the state_union corpus reader. Count occurrences of men, women, and people in each document. What has happened to the usage of these words over time? nltk.corpus.state_union.fileids() nltk.corpus.state_union.words() cfd = nltk.ConditionalFreqDist( (word, id[:4]) for id in state_union.fileids() for y in state_union.words(id) for word in ["men", "women", "people"] if y.lower() == word) cfd.plot() print("It appears that for the most part the use of men, women, and people has been fairly steady. However, over time there have been several notable peaks, especially in the use of 'people.' The largest peak occured in the mid to late 1990s.") ''' Question 7: According to Strunk and White's Elements of Style, the word however, used at the start of a sentence, means "in whatever way" or "to whatever extent", and not "nevertheless". They give this example of correct usage: However you advise him, he will probably do as he thinks best. (http://www.bartleby.com/141/strunk3.html) Use the concordance tool to study actual usage of this word in the various texts we have been considering. See also the LanguageLog posting "Fossilized prejudices about 'however'" at http://itre.cis.upenn.edu/~myl/languagelog/archives/001913.html ''' gutenberg.fileids() mobydick = nltk.Text(nltk.corpus.gutenberg.words('melville-moby_dick.txt')) austen = nltk.Text(nltk.corpus.gutenberg.words('austen-emma.txt')) mobydick.concordance('however') austen.concordance('however') print("In the Moby Dick text, where the word 'however' was used at the beginning of a sentence, it seemed to have the meaning of 'nevertheless,' so this would contradict Strunk and White's hypothesis. There was one instance that complied with the hypothesis in Moby Dick: 'However contracted, that definition is the...'. In the Austen-Emma text, I found the same results. I would argue that the presence of a comma immediately after the word 'however' often correlates to it holding the meaning of 'nevertheless' instead of 'to whatever extent.") # Question 8: Define a conditional frequency distribution over the Names corpus that allows you to see which initial letters are more frequent for males vs. females (cf. 4.4). names = nltk.corpus.names male_names = names.words('male.txt') female_names = names.words('female.txt') cfd = nltk.ConditionalFreqDist( (fileid, name[0]) for fileid in names.fileids() for name in names.words(fileid)) cfd.plot() # Question 12: The CMU Pronouncing Dictionary contains multiple pronunciations for certain words. How many distinct words does it contain? What fraction of words in this dictionary have more than one possible pronunciation? entries = nltk.corpus.cmudict.entries() words = [word for word, pron in entries] distinct = set(words) fraction = 1-(len(distinct))/len(words) print("There are ", len(distinct), "distinct words in the CMU Pronouncing Dictionary.", format(fraction, '.5f'), " of words in the dictionary have more than one possible pronunciation.")
a96445740403bf4d285acd07630522e02733818b
JITproject/DotDesktop
/gui.py
3,272
3.625
4
from Tkinter import * import Image class Application(Frame): def say_hi(self): print "hi there, everyone!" def TerminalToggle(self): if (self.terminal('relief')[-1] == 'sunken'): self.terminal(relief='sunken') else: self.terminal(relief='sunken') def StartupToggle(self): if (self.snotifstate('relief')[-1] == 'sunken'): self.snotifstate(relief='raised') else: self.snotifstate(relief='sunken') def createfile(self): self.DotDesktop = open(self.name.get() + ".desktop",'w') def createWidgets(self): #App icon #self.iconlabel = Label(self, text = "Icon Route") #self.iconlabel.grid(row=0,column=1) self.iconroute = Entry(self) self.iconroute.insert(END, 'icon route') self.iconroute.grid(row=0,column=1) #App name self.name = Entry(self) self.name.insert(END, 'Name') self.name.grid(row=0, column = 0) #Type self.typelabel = Label(self, text = "Type") self.typelabel.grid(row=2,column=0) self.application = Entry(self) self.application.insert(END, 'Application') self.application.grid(row=2,column=1) #Path self.pathlabel = Label(self, text = "Application Path") self.pathlabel.grid(row = 1, column = 0) self.path = Entry(self) self.path.insert(END, '/opt/') self.path.grid(row=1,column=1) #Categories self.catlabel = Label(self, text = "Categories") self.catlabel.grid(row =3, column=0) categories = ("Education","Languages","Java", "Network", "Accesories") # change for a text file later self.catselector = Spinbox(self, values = categories) self.catselector.grid(row=3,column=1) self.allcats = Text(self, height = 3, width = 15) #the categories chosen in the spiner go here self.allcats.grid(row=4,column=1) #terminal? self.trmyesno = Label(self, text = "Run on a Terminal?") self.trmyesno.grid(row=5,column=0) self.terminal = Button(self, text = 'true', relief='raised') #self.terminal["command"] = self.TerminalToggle self.terminal.grid(row=6,column=0) #startupnotify? self.startnotif = Label(self, text = "Startup Notify?") self.startnotif.grid(row=5,column=1) self.startup = Button(self, text = 'true', relief='raised') #self.startup["command"] = self.StartupToggle self.startup.grid(row=6,column=1) #Quit Button self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.grid(row=15,column=1) #create button self.create = Button(self) self.create["text"] = "Create .desktop" self.create["fg"] = "green" self.create["command"] = self.createfile self.create.grid(row=15,column=0) def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy()
2ef48d6a10b020b5f1857db68217455d7531ec04
lizhihui16/aaa
/pbase/day17/shili/instance_method.py
756
3.953125
4
#示意为Dog类添加吃,睡,玩等实例方法,以实现Dog对象的相应行为 class Dog: '''这是一种可爱的小动物''' def eat(self,food): '''此方法用来描述小狗吃的行为 ''' print('id为%d的'%id(self),end='') print('小狗正在吃',food) def sleep(self,hour): print('id为%d的小狗睡了%d小时'%(id(self),hour)) def play(self,a): print('id为%d的小狗正在玩%s'%(id(self),a)) #方法内可以用return返回对象的引用 dog1=Dog() dog1.eat('骨头') dog2=Dog() #创建另一个对象 dog2.eat('狗粮') dog1.sleep(1) dog2.sleep(2) dog1.play('球') dog2.play('飞盘') Dog.play(dog2,'飞盘') # 借助类来调用方法
48c22b24c909aaa7b6ad02cb8d97c849c3afe5c0
cyberbono3/leetcode
/amazon/N-queens.py
1,718
3.640625
4
class Solution(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ def safe_place(r, c, choices): find_safe = True for row, col in choices: if row + col == r + c or row - col == r - c or col == c: find_safe = False break return find_safe def solve_puzzle(row, choices): if row == R: return True else: for col in range(C): if safe_place(row, col, choices): choices.append((row, col)) if solve_puzzle(row+1, choices): return True choices.pop() return False def print_result(): result = [None]*len(res) for i, solution in enumerate(res): chess_board = [None]*R for r in range(R): s = "" for c in range(C): if c == solution[r][1]: s += "Q" else: s += "." chess_board[r] = "".join(s) result[i] = chess_board return result R, C = n, n res = [] for c in range(C): choices = [] choices.append((0, c)) if solve_puzzle(1, choices): res.append(choices) return print_result()
7218d340a71525890f581c0b2c3f43cd6127a983
j-rewerts/practice-problems
/misc/parse-input/main.py
111
3.671875
4
n = int(input()) values = list(map(int, input().split())) for value in values: print("Value " + str(value))
00c7a2238c832cf2c7a5b826feb4820d183b9d1e
charliechocho/py-crash-course
/pets.py
313
3.75
4
def my_pet(pet_type = 'alien', pet_name = 'ET'): """display pet and its name""" print(f"I have a {pet_type.title()}!") print(f"\tMy {pet_type.title()}'s name is {pet_name.title()}\n") pet_type = input("Vad har du för husdjur? ") pet_name = input("Vad heter ditt djur? ") my_pet(pet_type, pet_name)
3bd9d61fc116cb3feb0689fe82a49e8b0b6a545a
AntZuev/CourceraPython
/lesson3#.py
3,089
3.734375
4
'''a = float(input()) b = float(input()) c = float(input()) p = (a + b + c) / 2 s = (p * (p - a) * (p - b) * (p - c)) ** (1 / 2) print('{0:.6f}'.format(s)) n = int(input()) i = 1 s = 0 while i <= n: s += 1 / i ** 2 i += 1 print('{0:.6}'.format(s)) x = float(input()) x = x - int(x) print('{0:.6f}'.format(x)) x = float(input()) rub = int(x) cop = round((x - int(x)) * 100) print(rub, cop) import math x = float(input()) epsilon = 5 * 10**-10 if x - int(x) < 0.5 - epsilon: print(math.floor(x)) else: print(math.ceil(x)) p = int(input()) x = int(input()) y = int(input()) xCop = 100 * x + y xCopNew = xCop + xCop * p / 100 xNew = int(xCopNew / 100) yNew = int(xCopNew - xNew * 100) print(xNew, yNew) p = int(input()) x = int(input()) y = int(input()) k = int(input()) i = 1 while i <= k: xCop = 100 * x + y xCopNew = xCop + xCop * p / 100 x = int(xCopNew / 100) y = int(xCopNew - x * 100) i += 1 print(x, y) 2 задача по округлению вещественных чисел import math a = float(input()) b = float(input()) c = float(input()) d = b ** 2 - 4 * a * c if d == 0: x0 = -b /(2 * a) print('{0:.6f}'.format(x0)) if d > 0: x1 = (-b - math.sqrt(d)) /(2 * a) x2 = (-b + math.sqrt(d)) /(2 * a) if x1 > x2: x1, x2 = x2, x2 print('{0:.6f}'.format(x1), '{0:.6f}'.format(x2)) 1 задачи по округлению вещественных чисел a = float(input()) b = float(input()) c = float(input()) d = float(input()) e = float(input()) f = float(input()) if a == 0 and (c != 0 and b != 0): y = e / b x = (f * b - d * e) / (c * b) elif b == 0 and (a != 0 and d != 0): x = e / a y = (f * a - c * e) / (a * d) elif c == 0 and (a != 0 and d != 0): x = (e * d - b * f) / (a * d) y = f / d elif d == 0 and (c != 0 and e != 0): x = f / c y = (e * d - b * f) / (e * d) else: y = (f - c * e / a) / (d - b * c / a) x = (e - b * y) / a print('{0:.6f}'.format(x), '{0:.6f}'.format(y)) 1 задача по округлению вещественных чисел s = input() print(s[2]) print(s[-2]) print(s[:5]) print(s[:-2]) print(s[::2]) print(s[1::2]) print(s[::-1]) print(s[::-2]) print(len(s)) string = input() pos1 = string.find('f') if pos1 != -1: print(pos1, end=' ') pos2 = string.rfind('f', pos1 + 1) if pos2 != -1: print(pos2) string = input() pos1 = string.find('h') pos2 = string.rfind('h', pos1+1) string1 = string[:pos1] string2 = string[pos2+1:] print(string1 + string2) 1 задача по find string = input() pos = string.find('f') substring = string[pos + 1:] if pos == -1: print(-2) elif substring.find('f') != -1: print(substring.find('f') + len(string[:pos+1])) else: print(-1) string = input() pos = string.find(' ') substring1 = string[:pos] substring2 = string[pos + 1:] print(substring2 + ' ' + substring1) string = input() print(string.count(' ') + 1) string = input() print(string.replace('1', 'one')) string = input() print(string.replace('@', '')) 3 задачи на replace '''
b8e075a8c0918e7bc5d5d233cbdaea6b9f547bf2
corey-marchand/401-py-data-structures
/array_reverse/array_reverse.py
239
4.21875
4
numbers = [0, 1, 2, 3, 4, 5, 6] def reverseArray(array): L = len(numbers) for i in range(int(L/2)): n = numbers[i] numbers[i] = numbers[L-i-1] numbers[L-i-1] = n print(numbers) reverseArray(numbers)
5b9869bdbb836e5740b05167de17b0d2ab13b9b5
Hemangi3598/p22.py
/p9.py
159
4.40625
4
# wapp to read an integer # and print if its even or odd num = float(input("enter your num = ")) if num % 2 == 0 : print(" even") else: print(" odd")
d41118e24cbfaa932646ad7cb529268e5c5cfb96
basilkjose/Python-coding
/selection sort.py
369
3.515625
4
# SELECTION SORT def selectionsort(seq): for start in range(len(seq)): minpos=start for i in range(start,len(seq)): if seq[i] < seq[minpos]: minpos=i (seq[start],seq[minpos])=(seq[minpos],seq[start]) return seq result=selectionsort([74,32,89,55,21,64]) print(result)
aa0a2daee6cb9e5638bc09f0b115d04401c0191a
odom-data-science/data-science-portfolio
/foodscanner/db_2019/module_utils/scoreRegression.py
3,733
3.9375
4
import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder def scoreClassif(y_true, y_pred): """Computes a classification score by setting the threshold of y_true, then determines whether the learning algorithm predicted well or not (0 or 1) (with y_pred) Parameters ---------- y_true : array-like y is a list or an array that contain the target variable. y_pred : array-like Result of model.predict(x) Returns ------- score_classifier (loss) : float or ndarray of floats Computes the sum of good prediction divided by the product of y_pred.shape""" threshold = np.percentile(y_true, 50, axis=0) y_true_classif = y_true < threshold y_true_classif = y_true_classif.flatten() y_pred_classif = y_pred < threshold y_pred_classif = y_pred_classif.flatten() score_classifier = np.sum( y_pred_classif == y_true_classif) / np.prod(y_pred.shape) return score_classifier def scoreClassifier(model, x, y): # do not use it """Computes classification score Parameters ---------- model (object) : The object to predict the data. Compute y_pred of the model x : array-like (0 or 1) x is a list or an array that contain the independent variables. y : array-like (0 or 1) y is a list or an array that contain the dependent variables. Return ------ score_classifier (loss) : float or ndarray of floats Computes the sum of good prediction divided by the product of y_pred.shape""" # On reshape y_pred pour le mettre dans la même shape que y_true pour pouvoir les comparer y_pred = model.predict(x) y_pred = y_pred.reshape(y.shape[0], y.shape[1]) score_classifier = np.sum(y_pred == y) / np.prod(y_pred.shape) return score_classifier # ----------------------------------------- # ---------- ONE HOT ENCODING ---------- # ----------------------------------------- # GET DUMMIES def one_hot_encoder(df, column_list): """Takes in a dataframe and a list of columns for pre-processing via one hot encoding""" df_to_encode = df[column_list] df = pd.get_dummies(df_to_encode) # ONE HOT ENCODER def onehot_encoder(values, index_df, columns_df): """ Create a dataframe with value of a one-hot-encoded column: unique categorical variables are transformed into columns Parameters ---------- values : np.darray categorial values of a column into np array format example : values = np.array(df[['Type']]) index_df : pandas indexes index of the one hot encoded values Must be the same size as the concatenated dataframe example : index_df = df.index -> df is the original dataframe columns_df : columns of the one-hot-encoded values Length of columns must be the same size as the number of unique value in a categorical variable exameple : columns_df = np.sort(df['Type'].unique()) Return ------ Dataframe of the one-hot-encoded column Example ------- values = np.array(df[['Type']]) index_df = df.index columns_df = np.sort(df['Type'].unique()) df_ohe = onehot_encoder(values, index_df, columns_df) df_final = pd.concat([df_final, df_ohe], axis=1).drop("Type", axis=1) """ label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(values) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) return pd.DataFrame(data=onehot_encoded, index=index_df, columns=columns_df).astype(int)
ef44c86fe58a9d296e5897834f340da6dea7b1bd
Jay54520/Learn-Algorithms-With-Python
/011-数值的整数次方/v1/test_power.py
582
3.8125
4
# -*- coding: utf-8 -*- import unittest from power import Solution s = Solution() class Test(unittest.TestCase): def test_positive(self): got = s.Power(2, 3) want = 8 self.assertEqual(got, want) def test_zero(self): got = s.Power(2, 0) want = 1 self.assertEqual(got, want) def test_base_zero_exponent_negative(self): got = s.Power(0, -2) want = 1 self.assertEqual(got, want) def test_negative(self): got = s.Power(2, -3) want = 1 / 8 self.assertEqual(got, want)
359c62f4ef2566cc4912f20e468944c5883bb3d2
samuei/Schoolwork
/EECS-565/Lamb_Samuel_Miniproject_1.py
1,069
3.578125
4
#Samuel Lamb #Miniproject 1 #2/9/2015 #Python 2.7.5 def vigenere(text, key): alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] text = text.lower() text = text.replace(' ','') key = key.lower() key = key.replace(' ','') outtext = "" for i,letter in enumerate(text): outtext += alphabet[(alphabet.index(letter) + alphabet.index(key[(i % len(key))])) % 26] return outtext def devigenere(text, key): alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] text = text.lower() text = text.replace(' ','') key = key.lower() key = key.replace(' ','') outtext = "" for i,letter in enumerate(text): outtext += alphabet[(alphabet.index(letter) - alphabet.index(key[(i % len(key))])) % 26] return outtext #print vigenere("to be or not to be that is the question", "relations") #print devigenere(vigenere("To be or Not to Be That is the Question", "relations"), 'relations')
b1167e506e1efe57a9735982f503dbed3be1fc29
dcastrocs/CursoPython
/Mundo 2/ex051.py
215
3.84375
4
termo = int(input('Digite o primeiro termo: ')) razao = int(input('Digite a Razão: ')) decimo = termo + (10 -1 ) * razao for c in range(termo, decimo+razao, razao): print('{}'.format(c), end='-> ') print('Fim')
ea1452112eb638b25e8deadf70f83be1152ebbbf
ImCabbage/CS501
/HW1/3.py
464
3.875
4
#!/usr/bin/python # This is a simple program on calculating alphabetic character. # It is No.3 problem in HW 1 import sys L = list(sys.argv[1]) # transfer to string to list Result = [0]*26 for x in L: # classification if str.isalpha(x) == 1: y = str.lower(x) y = ord(y)-97; Result[y] = Result[y]+1; for i in range(26): # output the result if Result[i] != 0: print (chr(i+97),': ',Result[i])
8ba8e66542edc91f82aa79472e64d764fd8e9bf5
gabi15/VPython_labs
/laby8/lab8_ex3.py
2,286
3.71875
4
"""In this program the ball is bouncing from the box's walls and changes color to the color of a touched wall""" from vpython import * import random scene = canvas(width=800, height=580) wallL = box(pos=vector(-5,0,0), size=vector(0.3, 10, 10), color=color.red) wallR = box(pos=vector(5,0,0), size=vector(0.3,10,10), color=color.blue) wallD = box(pos=vector(0,-5,0), size=vector(10,0.3,10), color=color.yellow) wallU = box(pos=vector(0,5,0), size=vector(10,0.3,10), color=color.green) wallB = box(pos=vector(0,0,-5), size=vector(10,10,0.3), color=color.magenta) t=0 dt=0.005 N=20 balls=[] counter = N cx=7 # counter to position balls next to the box cy=7 #counter to position balls next to the box for x in range(-4,5): for y in range(-4,5): if counter <= 0: break balls.append(sphere(pos=vector(x, y, 0), radius=0.4, color=color.white,vel = vector(random.random(), random.random(), random.random()))) counter -= 1 d = balls[0].radius + 0.15 while 1: rate(1000) for i in range(N): balls[i].pos = balls[i].pos + balls[i].vel *dt if abs(balls[i].pos.x) +d >= wallR.pos.x and balls[i].pos.x<6: if balls[i].pos.x > 0: balls[i].color = wallR.color else: balls[i].color = wallL.color balls[i].vel.x = -balls[i].vel.x elif abs(balls[i].pos.y) +d >= wallU.pos.y and balls[i].pos.x<6: if balls[i].pos.y > 0: balls[i].color = wallU.color else: balls[i].color = wallD.color balls[i].vel.y = -balls[i].vel.y elif abs(balls[i].pos.z) +d >= abs(wallB.pos.z): if balls[i].pos.z < 0: balls[i].color = wallB.color else: balls[i].color = color.white balls[i].vel.z = -balls[i].vel.z for m in range(i+1,N): dif = balls[i].pos - balls[m].pos if mag(dif) <= 2*balls[0].radius: cy -= 2 if cy<-5: cx+=1; cy=5 balls[i].vel = vector(0,0,0) balls[m].vel = vector(0, 0, 0) balls[i].pos = vector(cx,cy, 4) balls[m].pos=vector(cx,cy+1,4) t=t+dt
e5ecb91314441c57f444d37d36e7d5aa9235cc6d
nadendlachandana/Training_Progress
/python practice/functions.py
667
3.84375
4
import math # 1 def spam(): # print eggs print("Eggs!") spam() # 4 def power(base, exponent): result = base ** exponent print("%d to the power of %d is %d." % (base, exponent, result)) power(37, 4) # 6 def cube(number): return number ** 3 def by_three(number): if number % 3 == 0: return cube(number) else: return False # 8 # import math print(math.sqrt(25)) # 9 from math import sqrt print(sqrt(25)) # 10 from math import * print(sqrt(25)) # 19 def distance_from_zero(n): if type(n) == int or type(n) == float: return abs(n) else: return "Nope" distance_from_zero("-asdas")
a51b02bc2b27e6ab61438a1d1e4adda345dd3f05
keigorori/python-plots
/trials.py
1,563
3.515625
4
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def set_display(fig, ax): """ 表示周りの設定 Parameters ---------- fig : Figure 対象のFigure ax : Axes 対象のAxes """ # 枠線を非表示 ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) # 表示範囲 ax.set_xlim(0, 50) ax.set_ylim(0, 105) # ラベル ax.set_xlabel("trials [times]") ax.set_ylabel("distance [m]") # 目盛間隔 ax.set_xticks(np.arange(0,50, 5)) ax.set_yticks(np.arange(0,105, 5)) # 背景透明 fig.patch.set_alpha(0.0) ax.patch.set_alpha(0.0) def plot_series(ax, trials, begin, end, step, marker_begin, marker_end): y = np.arange(begin, end, step) x = np.arange(trials, trials+len(y), dtype="int") ax.scatter(x, y, marker=marker_begin, color="royalblue") ax.scatter(trials+len(y), end, marker=marker_end, color="royalblue") return len(y) + 1 def main(): # データ trials = 1 step = 5 # プロット fig = plt.figure() ax = fig.add_subplot(1,1,1) trials += plot_series(ax, trials, 5, 45, step, "x", "o") trials += plot_series(ax, trials, 100, 30, -step, "o", "x") trials += plot_series(ax, trials, 5, 40, step, "x", "o") trials += plot_series(ax, trials, 100, 30, -step, "o", "x") # 表示設定 set_display(fig, ax) # ファイル保存 fig.savefig("trials.png") # 表示 plt.show() if __name__ == '__main__': main()
a341317b9e0d63eac28fe355321a9fa85da62eec
beckysx/python_basic
/数据类型转换&运算符/运算符.py
899
4.09375
4
""" 1. 算数运算符 arithmetic operator 1.1 / 除 1.2 // 整除 floor division 1.3 % modulus 2. comparison operator 3. logical operator and or not 4. assignment operator 复合赋值 = += -= *= 5. bitwise operator & | Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name. """ # 多变量赋值 num1, str1, float2 = 1, "hello", 1.1 a = b = 1 c = 10 c += 1 + 2 # c = 10+1+2 ? # c += 3 ? 先计算预算符右面表达式 d = 10 d *= 1 + 2 print(d) # d = 30 d= 10 * (1+2) num1 = 0 num2 = 1 num3 = 2 # and 一个值为0,结果为0,否则为最后一个非0数字 print(num1 and num2) # 0 print(num2 and num1) # 0 print(num2 and num3) # 2 # or 所有值为0才输出0,否则结果为第一个非0数字 print(num2 or num1) # 1 print(num1 or num2) # 1 print(num2 or num3) # 1
44067dfaf0c0bbd0108547dde14513a28b2a208f
skhlivnenko/Python
/Yarmak_course/L02X2_input.py
155
4.0625
4
USD = input("How much USD do you want yo change?\n") RATE = input ("What is rate?\n") UAH = USD*RATE print "You'll get {} UAH for {} USD".format(UAH, USD)
b514152dc7c918d32eb339285376ba4ab9810e64
tiagoleonmelo/ia
/python_practice/one/ex1.py
1,949
3.890625
4
# Funçoes para processamento de listas def size_lista(lista, i=0): if lista==[]: return 0 return 1 + size_lista(lista[1:]) def sum_list(lista): if lista == []: return 0 return lista[0] + sum_list(lista[1:]) def listContains(element, lista): if lista == []: return False elif lista[0] == element: return True return listContains(element, lista[1:]) def listConcat(list_a, list_b): if list_a == []: return list_b c = listConcat(list_a[1:], list_b) c[:0] = [list_a[0]] return c def listReversal(lista): if lista == []: return [] return [lista[-1]]+listReversal(lista[:-1]) def isCapicua(lista): if listReversal(lista) == lista: return True return False def bigListConcat(lista_grande): if lista_grande == []: return [] return lista_grande[0]+bigListConcat(lista_grande[1:]) def replace(l, x, y): if l == []: return [] elif l[0] == x: l[0] = y return [l[0]]+replace(l[1:], x, y) def merge(l1, l2): if l1 == [] and l2 == []: return [] if not l1: return l2 if not l2: return l1 if l1[0] <= l2[0]: return [l1[0]]+merge(l1[1:], l2) else: return [l2[0]]+merge(l1, l2[1:]) def subset(set): if not set: return [set] rest = subset(set[1:]) return rest + [[set[0]] + item for item in rest] lista = ['a','b','c','d','e'] nums = [1, 2, 3, 4, 5,163,170,200] reversable = [1,2,3,162,164,201] capicua = ['a','n','a'] a = [1,2,3] big_list = [lista, nums, reversable, capicua] print(size_lista(lista)) print(sum_list(nums)) print(listContains('r', lista)) print(listContains(1, nums)) #print(listConcat(lista, nums)) print(listReversal(reversable)) print(isCapicua(capicua)) print(bigListConcat(big_list)) print(replace(nums, 2, 64)) print(merge(nums,reversable)) print(subset(a))
424a63a43d76be014f10d70d232327921a0da761
bernardosequeir/CTFSolutions
/HackerRank/10DaysOfStats/Day2_BasicProbability.py
172
3.6875
4
i = 1 j = 1 below_or_equal = 0 while (i <= 6): while (j <= 6): if(i + j <= 9): below_or_equal += 1 j += 1 i += 1 print(below_or_equal)
24986ccd766bdf2eba79f3265fdbee17847d7dcd
YutoTakaki0626/My-Python-REVIEW
/fileIO/file_write.py
316
3.75
4
with open('writing_file.txt', mode='w') as f: # truncatedされる:byte=0に切り詰める f.write('You can write contents here\n') f.write('new write() doesn`t break no') print('You can add a new row using "file" parameter', file=f) print('new print() method breaks the row for you!!', file=f)
bbf0bb4f6bbb36887acd2d1dfde839cf4b7c98a0
lidianxiang/leetcode_in_python
/二分查找/50-Pow(x,n).py
788
3.734375
4
""" 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25 """ class Solution: """利用二分查找思想,每次记录连乘的次数count,每次倍乘""" def myPow(self, x, n): def re_binarySearch(x, n): if n < 1: return 1 count, sums = 1, x while count * 2 <= n: count += count sums *= sums return re_binarySearch(x, n-count) * sums res = re_binarySearch(abs(x), abs(n)) res = -res if x < 0 and n % 2 != 0 else res res = 1/res if n < 0 else res return res
46f6252a29d89caf0fcc61fe8ce55ffd57a7dfdf
akankshanayak2111/Practice_problems
/anagram_of_palindrome.py
698
4.125
4
def is_anagram_of_palindrome(word): """Is the word an anagram of a palindrome?""" # add count of characters to a dict # check if all the values in the dict are divisible by 2 except one, return True # else False letter_count = {} for letter in word: if letter not in letter_count: letter_count[letter] = 1 else: letter_count[letter] += 1 list_count = sorted(letter_count.values()) if len(list_count) == 1: return True if list_count[0] == 1: for i in range(1, len(list_count)): if list_count[i] % 2 != 0: return False else: return True
4dda03277d5a1b0270fcd1dfa2bc19f2a03b18dc
DrGaster/Friday
/Jarvis Mark 2/Name_Identify.py
419
3.515625
4
user = input("What is your name? ") class Jarvis: def __init__(self, user): self.user = user def intro(self): print("Hello", self.user + ", ", "I'm Jarvis") def assist(self): cmd = True while cmd: cmd = input("What can I do for you? ") if cmd == "exit": cmd = False break J = Jarvis(user) J.intro() J.assist()
40e23b4bb089617d9adfa7c00517319bf21a0d3b
palmtree5/Applications
/guess/guess.py
2,088
3.5625
4
# Import random from the standard library so we can pick random numbers. import random from discord.ext import commands class Mycog: """My custom cog that does stuff!""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def guess(self, ctx): """Guess what number I am thinking!""" # Grab the author object author = ctx.message.author # Make the bot output a prompt for the user await self.bot.say("Guess a number from 1 to 10.") # We use wait_for_message() to capture the response # You can set a timeout for how long they have to respond. Will make guess None. # Author is the object it should be expecting the response from. # Check let's you pass a regular function to perform advanced checks. guess = await self.bot.wait_for_message(timeout=15, author=author, check=self.digit_check) # Pick a number 1 through 10 answer = random.randint(1, 10) # Now we run the logic to determine the right output. # When checking for no response, we simply use guess is None # When checking the author's input, we need to use guess.content # If the response.content does not equal our answer then it is wrong and moves to else if guess is None: msg = "Sorry, you took too long. I was thinking {}." elif int(guess.content) == answer: msg = "You are right! I was thinking {} too!" else: msg = "Sorry. I was actually thinking {}." await self.bot.say(msg.format(answer)) # We write a function for our check(optional) # Because the response is a string. We need to determine, for example, if "10" is 10 # If this throws an error(exception), then the exception is propagated. # The guess will not be accepted, unless this function runs without an exception. def digit_check(self, message): return message.content.isdigit() def setup(bot): bot.add_cog(Mycog(bot))
476f844b30b5d07c4852cd66cf55d0592be3df8e
Susan-Wangari/python
/password.py
324
3.9375
4
x = str(input('Please Enter username: ')) username = "kay" password = "1234" if x == username : y = str(input ('Enter password: ')) if y == password : print(len(y)) # print(x.upper()) print(y.replace('1', '2')) print(y) print(username[1:]) else: print("wrong username")
d9a522734da8c2a76fb0c8ea33a0f833361462b6
Marlenqyzy/PP2
/week1/w3school/70.py
196
3.953125
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict.values(): print(x) for x in thisdict.keys(): print(x) for y, x int thisdict.items(): print(y, x)
e5978b9991036fc2900599c67891afec29e3a83d
MacLure/Code-Wars-Solutions
/Python/8 kyu - Filter out the geese.py
212
3.78125
4
geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"] def goose_filter(bird): def not_goose(x): return True if x not in geese else False return list(filter(not_goose, bird))
d20dc55f51db35a161fb070bbc9ba00404616eab
Lmanea25/gitjenkinsIntegration
/Loops.py
11,611
3.8125
4
# import os # # # # import selenium # # a =200 # # b =30 # # c=500 # # if a > b: print("a is greater than b") # # print("A")if a > b else print("=") if a==b else print("B") # # if a>b and c>a: # # # print("Both conditions are true") # # pass # # # # x =41 # # if x > 10: # # print("Above ten,") # # if x > 20: # # print("and also above 20!") # # else: # # print( # # "but not above 20.") # # # i =0 # # while i <6: # # i +=1 # # if i ==3: # # continue # # print(i) # # # # fruits = ["apple","banana","cherry"] # # for x in fruits: # # if x == 'banana': # # continue # # print(x) # # # # count=0 # # for x in "banana": # # if 'a' in x: # # count+=1 # # print(count) # # # # for x in range(6): # # if x==3:break # # print(x) # # else: # # print("Finally finished") # # # adj = ["red","big","tasty"] # # fruits = ["apple","banana","cherry"] # # for x in adj: # # for y in fruits: # # print(x, y) # # # def my_function(fname, lname): # # print(fname+" "+lname) # # my_function("Emil") # # # # def my_function(child3, child2, child1): # # print("The youngest child is "+ child3) # # my_function(child1 ="Emil", child2 ="Tobias", child3 ="Linus") # # # # def my_function(**kid): # # print("His last name is " + kid["lname"]) # # my_function(fname = "Tobias", lname = "Refsnes") # # # def my_function(country ="Norway"): # # print("I am from "+country) # # my_function() # # my_function("India") # # my_function() # # my_function("Brazil") # # # def my_function(food): # # for x in food: # # print(x) # # fruits = ["apple","banana","cherry"] # # my_function(fruits) # # # def my_function(x=3): # # return 5 * x # # print(my_function()) # # print(my_function(5)) # # print(my_function(9)) # # # def factorial(x): # # """This is a recursive function # # to find the factorial of an integer""" # # if x ==1: # # return 1 # # else : # # return (x * factorial(x-1)) # # num = 10 # # print("The factorial of", num, "is", factorial(num)) # # # def recursor(): # # recursor() # # recursor() # # # # def my_function(): # # """Demonstrates triple double quotes # # docstrings and does nothing really.""" # # return None # # print("Using __doc__:") # # print(my_function.__doc__) # # print("Using help:") # # help(my_function) # # # def my_function(arg1): # # """ # # Summary line. # # Extended description of function. # # Parameters: # # arg1 (int): Description of arg1 # # Returns: # # int: Description of return value # # """ # # return arg1 # # print(my_function.__doc__) # # # # class ComplexNumber: # # """ # # This is a class for mathematical operations on complex numbers. # # # # Attributes: # # real (int): The real part of complex number. # # imag (int): The imaginary part of complex number. # # """ # # # # # # def __init__(self, real, imag): # # """ # # The constructor for ComplexNumber class. # # # # Parameters: # # real (int): The real part of complex number. # # imag (int): The imaginary part of complex number. # # """ # # # # def add(self, num): # # """ # # The function to add two Complex Numbers. # # # # Parameters: # # num (ComplexNumber): The complex number to be added. # # # # Returns: # # ComplexNumber: A complex number which contains the sum. # # """ # # # # re = self.real + num.real # # im = self.imag + num.imag # # # # return ComplexNumber(re, im) # # # # # # help(ComplexNumber) # to access Class docstring # # help(ComplexNumber.add) # to access method's docstring # # # f =open("demofile.txt","rt") # # # print(f.read(5)) # # print(f.readline()) # # f.close() # # # f.write("Woops! I have deleted the content!") # # f.close() # # # # f =open("myfile.txt","x") # # # # # os.remove("demofile.txt") # # # # f =open("demofile.txt","x") # # if os.path.exists("demofile.txt"): # # os.remove("demofile.txt") # # else: # # print("The file does not exist") # # # # os.rmdir("Folder") # # # f =open("demofile.txt","r") # # # print(f.tell()) # # # f.write("Woops! I have deleted the content!") # # print(f.readline()) # # print(f.tell()) # # # # f =open("demofile.txt","r") # # f.seek(4) # # print(f.readline()) # # # file = open('demofile.txt', 'w') # # file.write('hello world !') # # file.close() # # # file = open('demofile.txt', 'w') # # try: # # file.write('hello world') # # finally: # # print("Finally") # # file.close() # # # with open('demofile.txt', 'w') as file: # # file.write('hello world !') # # # class MessageWriter(object): # # def __init__(self, file_name): # # self.file_name = file_name # # def __enter__(self): # # self.file = open(self.file_name, 'w') # # return self.file # # def __exit__(self): # # self.file.close() # # # using with statement with MessageWriter # # with MessageWriter('demofile2.txt') as xfile: # # xfile.write('hello world') # # # x = lambda a : a + 10 # # print(x(5)) # # # # def myfunc(n): # # return lambda a : a * n # # # # mydoubler = myfunc(2) # # print(mydoubler(11)) # # # val = 'BusyQA' # # print(f"{val}for{val} is a portal for {val}.") # # # # name = 'Tushar' # # age = 23 # # print(f"Hello, My name is {name} and I'm {age} years old.") # # # # # today = datetime.datetime.today() # # print(f"{today:%B %d, %Y}") # # # answer = 456 # # print(f"Your answer is "{answer}"") # # # f"newline: {ord('\n')}” # # # # newline = ord('\n') # # f"newline: {newline}" # # # txt ="For only {price:.2f} dollars!" # # print(txt.format(price =49)) # # # txt = "We have {:<8} chickens." # # print(txt.format(49)) # # # def myFun(*argv): # # for arg in argv: # # print (arg) # # myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') # # # # def myFun(arg1, *argv): # # print ("First argument :", arg1) # # for arg in argv: # # print("Next argument through *argv :", arg) # # # # myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') # # # # # def myFun(**kwargs): # # for key, value in kwargs.items(): # # print("%s == %s" % (key, value)+ 23) # # # # # # # Driver code # # myFun(first='Geeks', mid='for', last='Geeks') # # # print("The values of variable is" + '23') # # # # def myFun(*args,**kwargs): # # print("args: ", args) # # print("kwargs: ", kwargs) # # # Now we can use both *args ,**kwargs # # # to pass arguments to this function : # # myFun('geeks','for','geeks',first="Geeks",mid="for",last="Geeks") # # # # l1 = ["eat","sleep","repeat"] # # s1 = "geek" # # # # # creating enumerate objects # # obj1 = enumerate(l1) # # obj2 = enumerate(s1) # # # # print ("Return type:",type(obj1)) # # print (list(enumerate(l1))) # # # # # changing start index to 2 from 0 # # print (list(enumerate(s1,2))) # # # # l1 = ["eat","sleep","repeat"] # # # # # printing the tuples in object directly # # for x in enumerate(l1): # # print (x) # # # # print ("Always executed") # # # if __name__ == "__main__": # # print ("Executed when invoked directly") # # else: # # print ("Executed when imported") # # # # def my_function(): # # print("I am inside function") # # # We can test function by calling it. # # # my_function() # # # # if __name__ == "__main__": # # my_function() # # import datetime # # print(datetime.datetime.today()) # # # # myTuple = ("John","Peter","Vicky") # # x ="#".join(myTuple) # # print(x) # # # myDict = {"name":"John","country":"Norway"} # # mySeparator ="TEST" # # x= mySeparator.join(myDict) # # print(x) # # # circle_areas = [3.56773, 5.57668, 4.00914, 56.24241, 9.41344, 32.00013] # # result = list(map(round, circle_areas,range(1,7))) # # print(result) # # # circle_areas = [3.56773, 5.57668, 4.00914, 56.24241, 9.01344, 32.00013] # # result = list(map(round, circle_areas, range(1,5))) # # print(result) # # # my_strings = ["a", "b", 'c', 'd', 'e’] # # my_numbers = ['1',2,3,4,5] # # results = list(zip(my_strings, my_numbers)) # # print(results) # # # my_strings = ["a","b","c","d","e"] # # my_numbers = [1,2,3,4,5] # # my_arrays=["abc",1,7,9.4,"apple"] # # results = list(zip(my_strings, my_numbers,my_arrays)) # # print(results) # # # # # # scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65] # # def is_A_student(score): return score < 75 # # over_75 = list(filter(is_A_student, scores)) # # print(over_75) # # # dromes = ("demigod", "rewire", "madam", "freer", "anutforajaroftuna", "kiosk") # # # # palindromes = list(filter(lambda word: word == word[::-1], dromes)) # # # # print(palindromes) # # # # # def shout(text): # # return text.upper() # # print(shout('Hello')) # # yell = shout # # print(yell('Hello')) # # # # # # def shout(text): # # return text.upper() # # # # # # def whisper(text): # # return text.lower() # # # # # # # # def greet(func): # # print(func) # # # storing the function in a variable # # greeting = func("""Hi, I am created by a function passed as an argument.""") # # print(greeting) # # # # greet(shout) # # greet(whisper) # # # # def create_adder(x): # # def adder(y): # # return x + y # # # # return adder # # return x # # add_15 = create_adder(15) # # print(add_15) # # # @gfg_decorator # def hello(): # print("Hello") # hello() # # # def hello_decorator(func): # # inner1 is a Wrapper function in # # which the argument is called # # inner function can access the outer local # # functions like in this case "func" # def inner1(): # print("Hello, this is before function execution") # # calling the actual function now # # inside the wrapper function. # func() # # print("This is after function execution") # # # return inner1 # # # def function_to_be_used(): # # print("This is inside the function !!") # # # passing 'function_to_be_used' inside the # # decorator to control its behavior # function_to_be_used = hello_decorator(function_to_be_used) # # # calling the function # function_to_be_used() # # # # # # # # # # def f1(): # print("Calledf1") # print(f1) # def f1(): # print("Called f1") # # def f2(f): # f() # # f2(f1) # def f1(func): def wrapper(*args,**kwargs): print("Started") val=func(*args,**kwargs) print("Ended") return val return wrapper @f1 def f(a,b=9): print(a,b) # f1(f)() # f = f1(f) # f("Hi!") @f1 def add(x,y): return x+y print(add(4,5)) # def works_for_all(func): # def inner(*args, **kwargs): # print("I can decorate any function") # return func(*args, **kwargs) # # return inner # # @works_for_all # def f(): # print(9,10) # f() # try: # print(x) # except NameError: # print("Variable x is not defined") # except: # print("Something else went wrong") # try: # print("Hello") # except: # print("Something went wrong") # finally: # print("Nothing went wrong") # try: # f = open("demofile.txt",'w') # f.write("Lorum Ipsum") # except: # print("Something went wrong when writing to the file") # finally: # f.close() # x = -1 # if x < 0: # raise TypeError("Sorry, no numbers below zero")
95c9a2ca9ce9110f8526421f1da56983268ecff5
Alichegeni/codes
/BMI.py
746
4.15625
4
w = int(input("please insert your weight in kilogram: ")) h = int(input("please insert your height in centimeter:")) H = ((h/100)**2) BMI = (w / H) if w == 0: print("you can not be zero kg! please enter your weight correctly") if w != 0: if BMI < 18.5: print("your BMI is:", BMI, "you are underweight") if 18.5 <= BMI < 25: print("your BMI is:", BMI, "and you are normal") if 25 <= BMI < 30: print("your BMI is:", BMI, "and you are overweight, please be careful") if 30 < BMI < 35: print("your BMI is:", BMI, "and you are overweight, start workout ASAP") if 35 <= BMI : print("your BMI is:", BMI, "and you are overweight, it's better to call a health consultor")
631836d8bac619c500e2331eeda2d0ea801dd3a0
wekesa/Weather
/weather.py
2,260
3.6875
4
#Author -Wekesa Victor #import regex library import re DATA_FILENAME = "weather.dat" class WeatherSpread: def __init__(self): print "This program finds the row with the maximum spread in the weather.dat file, \n where spread is defined as the difference between MxT and MnT \n" #logic to open the file and read the contents with open(DATA_FILENAME) as fileContents: #Loop to get values and store them in a list of lists lines = [line.split() for line in fileContents] # remove empty lists lines2 = filter(None, lines) #Get the first 3 columns required to get the maximum spread newList = [ [row[0], row[1], row[2]] for row in lines2 ] #remove the first row used for column names newList.pop(0) #remove the last row used for average calculations is not useful for now newList.pop(-1) # log newList #print newList newerList = self.calculate_spread(newList) # Log # print newerList # Get the spread tempItem = self.get_max_spread_list(newerList) # Log #print "Got item" #print tempItem #Log #Prints the final result print "The day: " + str(tempItem[0]) + " The Spread: " + str(tempItem[-1]) # print tempItem[0] # print "The Spread: " # print tempItem[-1] # Function to calculate the spread #It also removes special characters and converts string values to float def calculate_spread(self,items): # Calculate the spread return [[item[0], item[1], item[2], float(re.sub('\D', "", item[1])) - float(re.sub('\D', "", item[2]))] for item in items] # A custom function to get the list with the maximum spread value #return a list with maximum spread def get_max_spread_list(self,items): # Calculate the largest spread and return the list return_item = [] for item in items: if len(return_item) < 1: return_item = item elif return_item[3] > item[3]: continue else: return_item = item return return_item #create an instance of this class weatherSpread = WeatherSpread()
620067c2939f5eece85a52efa414b0be39fc2fd8
surut555/basicpython
/function.py
843
3.5625
4
# การสร้างฟังก์ชันแบบไม่มีการ return value def hello(name): print(f"hell {name}") # สร้างฟังก์ชันแบบมีการ return Vauue def area(width, height): total = width*height return total # เรียกใช้งานฟังก์ชัน hello() hello("surut") # เรียนใชังานฟังก์ชัน area() print(area(2, 3)) print(area(5, 3)) print(area(58.2, 54.2)) # ฟังก์ชันแบบมีค่าเริ่มต้น def show_info(name="", salary=0.00, lang="not define"): print(f"Name:{name}") print(f"salary:{salary}") print(f"lang:{lang}") # เรียนใชังานฟังก์ชัน show_info() show_info() print() show_info('surut', 1200, 'PHP')
a4183508dc90738b5759bb8be953fb4eed887af4
bachiraoun/machinelearning
/utils/Collection.py
34,335
4.03125
4
# standard libraries imports from random import random as generate_random_float from random import randint as generate_random_integer # external libraries imports import numpy as np def is_number(number): """ check if number is convertible to float. :Parameters: #. number (str, number): input number :Returns: #. result (bool): True if convertible, False otherwise """ if isinstance(number, (int, long, float, complex)): return True try: float(number) except: return False else: return True def is_integer(number, precision=10e-10): """ check if number is convertible to integer. :Parameters: #. number (str, number): input number #. precision (number): To avoid floating errors, a precision should be given. :Returns: #. result (bool): True if convertible, False otherwise """ if isinstance(number, (int, long)): return True try: number = float(number) except: return False else: if np.abs(number-int(number)) < precision: return True else: return False class RandomFloatGenerator(object): """ Generate random float number between a lower and an upper limit. :Parameters: #. lowerLimit (number): The lower limit allowed. #. upperLimit (number): The upper limit allowed. """ def __init__(self, lowerLimit, upperLimit): self.__lowerLimit = None self.__upperLimit = None self.set_lower_limit(lowerLimit) self.set_upper_limit(upperLimit) @property def lowerLimit(self): """The lower limit of the number generation.""" return self.__lowerLimit @property def upperLimit(self): """The upper limit of the number generation.""" return self.__upperLimit @property def rang(self): """The range defined as upperLimit-lowerLimit.""" return self.__rang def set_lower_limit(self, lowerLimit): """ Set lower limit. :Parameters: #. lowerLimit (number): The lower limit allowed. """ assert is_number(lowerLimit) self.__lowerLimit = np.float(lowerLimit) if self.__upperLimit is not None: assert self.__lowerLimit<self.__upperLimit self.__rang = np.float(self.__upperLimit-self.__lowerLimit) def set_upper_limit(self, upperLimit): """ Set upper limit. :Parameters: #. upperLimit (number): The upper limit allowed. """ assert is_number(upperLimit) self.__upperLimit = np.float(upperLimit) if self.__lowerLimit is not None: assert self.__lowerLimit<self.__upperLimit self.__rang = np.float(self.__upperLimit-self.__lowerLimit) def generate(self): """Generate a random float number between lowerLimit and upperLimit.""" return np.float(self.__lowerLimit+generate_random_float()*self.__rang) def gaussian(x, center=0, FWHM=1, normalize=True, check=True): """ Compute the normal distribution or gaussian distribution of a given vector. The probability density of the gaussian distribution is: :math:`f(x,\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}} e^{\\frac{-(x-\\mu)^{2}}{2\\sigma^2}}` Where:\n * :math:`\\mu` is the center of the gaussian, it is the mean or expectation of the distribution it is called the distribution's median or mode. * :math:`\\sigma` is its standard deviation. * :math:`FWHM=2\\sqrt{2 ln 2} \\sigma` is the Full Width at Half Maximum of the gaussian. :Parameters: #. x (numpy.ndarray): The vector to compute the gaussian #. center (number): The center of the gaussian. #. FWHM (number): The Full Width at Half Maximum of the gaussian. #. normalize(boolean): Whether to normalize the generated gaussian by :math:`\\frac{1}{\\sigma\\sqrt{2\\pi}}` so the integral is equal to 1. #. check (boolean): whether to check arguments before generating vectors. """ if check: assert is_number(center) center = np.float(center) assert is_number(FWHM) FWHM = np.float(FWHM) assert FWHM>0 assert isinstance(normalize, bool) sigma = FWHM/(2.*np.sqrt(2*np.log(2))) x = np.array(x) expKernel = ((x-center)**2) / (-2*sigma**2) exp = np.exp(expKernel) scaleFactor = 1. if normalize: scaleFactor /= sigma*np.sqrt(2*np.pi) return (scaleFactor * exp).astype(np.float) def step_function(x, center=0, FWHM=0.1, height=1, check=True): """ Compute a step function as the cumulative summation of a gaussian distribution of a given vector. :Parameters: #. x (numpy.ndarray): The vector to compute the gaussian #. center (number): The center of the step function which is the the center of the gaussian. #. FWHM (number): The Full Width at Half Maximum of the gaussian. #. height (number): The height of the step function. #. check (boolean): whether to check arguments before generating vectors. """ if check: assert is_number(height) height = np.float(height) g = gaussian(x, center=center, FWHM=FWHM, normalize=False, check=check) sf = np.cumsum(g) sf /= sf[-1] return (sf*height).astype(np.float) class BiasedRandomFloatGenerator(RandomFloatGenerator): """ Generate biased random float number between a lower and an upper limit. To bias the generator at a certain number, a bias gaussian is added to the weights scheme at the position of this particular number. .. image:: biasedFloatGenerator.png :align: center :Parameters: #. lowerLimit (number): The lower limit allowed. #. upperLimit (number): The upper limit allowed. #. weights (None, list, numpy.ndarray): The weights scheme. The length defines the number of bins and the edges. The length of weights array defines the resolution of the biased numbers generation. If None is given, ones array of length 10000 is automatically generated. #. biasRange(None, number): The bias gaussian range. It must be smaller than half of limits range which is equal to (upperLimit-lowerLimit)/2 If None, it will be automatically set to (upperLimit-lowerLimit)/5 #. biasFWHM(None, number): The bias gaussian Full Width at Half Maximum. It must be smaller than half of biasRange. If None, it will be automatically set to biasRange/10 #. biasHeight(number): The bias gaussian maximum intensity. #. unbiasRange(None, number): The bias gaussian range. It must be smaller than half of limits range which is equal to (upperLimit-lowerLimit)/2 If None, it will be automatically set to biasRange. #. unbiasFWHM(None, number): The bias gaussian Full Width at Half Maximum. It must be smaller than half of biasRange. If None, it will be automatically set to biasFWHM. #. unbiasHeight(number): The unbias gaussian maximum intensity. If None, it will be automatically set to biasHeight. #. unbiasThreshold(number): unbias is only applied at a certain position only when the position weight is above unbiasThreshold. It must be a positive number. """ def __init__(self, lowerLimit, upperLimit, weights=None, biasRange=None, biasFWHM=None, biasHeight=1, unbiasRange=None, unbiasFWHM=None, unbiasHeight=None, unbiasThreshold=1): # initialize random generator super(BiasedRandomFloatGenerator, self).__init__(lowerLimit=lowerLimit, upperLimit=upperLimit) # set scheme self.set_weights(weights) # set bias function self.set_bias(biasRange=biasRange, biasFWHM=biasFWHM, biasHeight=biasHeight) # set unbias function self.set_unbias(unbiasRange=unbiasRange, unbiasFWHM=unbiasFWHM, unbiasHeight=unbiasHeight, unbiasThreshold=unbiasThreshold) @property def originalWeights(self): """The original weights as initialized.""" return self.__originalWeights @property def weights(self): """The current value weights vector.""" weights = self.__scheme[1:]-self.__scheme[:-1] weights = list(weights) weights.insert(0,self.__scheme[0]) return weights @property def scheme(self): """The numbers generation scheme.""" return self.__scheme @property def bins(self): """The number of bins that is equal to the length of weights vector.""" return self.__bins @property def binWidth(self): """The bin width defining the resolution of the biased random number generation.""" return self.__binWidth @property def bias(self): """The bias step-function.""" return self.__bias @property def biasGuassian(self): """The bias gaussian function.""" return self.__biasGuassian @property def biasRange(self): """The bias gaussian extent range.""" return self.__biasRange @property def biasBins(self): """The bias gaussian number of bins.""" return self.__biasBins @property def biasFWHM(self): """The bias gaussian Full Width at Half Maximum.""" return self.__biasFWHM @property def biasFWHMBins(self): """The bias gaussian Full Width at Half Maximum number of bins.""" return self.__biasFWHMBins @property def unbias(self): """The unbias step-function.""" return self.__unbias @property def unbiasGuassian(self): """The unbias gaussian function.""" return self.__unbiasGuassian @property def unbiasRange(self): """The unbias gaussian extent range.""" return self.__unbiasRange @property def unbiasBins(self): """The unbias gaussian number of bins.""" return self.__unbiasBins @property def unbiasFWHM(self): """The unbias gaussian Full Width at Half Maximum.""" return self.__unbiasFWHM @property def unbiasFWHMBins(self): """The unbias gaussian Full Width at Half Maximum number of bins.""" return self.__unbiasFWHMBins def set_weights(self, weights=None): """ Set generator's weights. :Parameters: #. weights (None, list, numpy.ndarray): The weights scheme. The length defines the number of bins and the edges. The length of weights array defines the resolution of the biased numbers generation. If None is given, ones array of length 10000 is automatically generated. """ # set original weights if weights is None: self.__bins = 10000 self.__originalWeights = np.ones(self.__bins) else: assert isinstance(weights, (list, set, tuple, np.ndarray)) if isinstance(weights, np.ndarray): assert len(weights.shape)==1 wgts = [] assert len(weights)>=100 for w in weights: assert is_number(w) w = np.float(w) assert w>=0 wgts.append(w) self.__originalWeights = np.array(wgts, dtype=np.float) self.__bins = len(self.__originalWeights) # set bin width self.__binWidth = np.float(self.rang/self.__bins) self.__halfBinWidth = np.float(self.__binWidth/2.) # set scheme self.__scheme = np.cumsum( self.__originalWeights ) def set_bias(self, biasRange, biasFWHM, biasHeight): """ Set generator's bias gaussian function :Parameters: #. biasRange(None, number): The bias gaussian range. It must be smaller than half of limits range which is equal to (upperLimit-lowerLimit)/2 If None, it will be automatically set to (upperLimit-lowerLimit)/5 #. biasFWHM(None, number): The bias gaussian Full Width at Half Maximum. It must be smaller than half of biasRange. If None, it will be automatically set to biasRange/10 #. biasHeight(number): The bias gaussian maximum intensity. """ # check biasRange if biasRange is None: biasRange = np.float(self.rang/5.) else: assert is_number(biasRange) biasRange = np.float(biasRange) assert biasRange>0 assert biasRange<=self.rang/2. self.__biasRange = np.float(biasRange) self.__biasBins = np.int(self.bins*self.__biasRange/self.rang) # check biasFWHM if biasFWHM is None: biasFWHM = np.float(self.__biasRange/10.) else: assert is_number(biasFWHM) biasFWHM = np.float(biasFWHM) assert biasFWHM>=0 assert biasFWHM<=self.__biasRange/2. self.__biasFWHM = np.float(biasFWHM) self.__biasFWHMBins = np.int(self.bins*self.__biasFWHM/self.rang) # check height assert is_number(biasHeight) self.__biasHeight = np.float(biasHeight) assert self.__biasHeight>=0 # create bias step function b = self.__biasRange/self.__biasBins x = [-self.__biasRange/2.+idx*b for idx in range(self.__biasBins) ] self.__biasGuassian = gaussian(x, center=0, FWHM=self.__biasFWHM, normalize=False) self.__biasGuassian -= self.__biasGuassian[0] self.__biasGuassian /= np.max(self.__biasGuassian) self.__biasGuassian *= self.__biasHeight self.__bias = np.cumsum(self.__biasGuassian) def set_unbias(self, unbiasRange, unbiasFWHM, unbiasHeight, unbiasThreshold): """ Set generator's unbias gaussian function :Parameters: #. unbiasRange(None, number): The bias gaussian range. It must be smaller than half of limits range which is equal to (upperLimit-lowerLimit)/2 If None, it will be automatically set to biasRange. #. unbiasFWHM(None, number): The bias gaussian Full Width at Half Maximum. It must be smaller than half of biasRange. If None, it will be automatically set to biasFWHM. #. unbiasHeight(number): The unbias gaussian maximum intensity. If None, it will be automatically set to biasHeight. #. unbiasThreshold(number): unbias is only applied at a certain position only when the position weight is above unbiasThreshold. It must be a positive number. """ # check biasRange if unbiasRange is None: unbiasRange = self.__biasRange else: assert is_number(unbiasRange) unbiasRange = np.float(unbiasRange) assert unbiasRange>0 assert unbiasRange<=self.rang/2. self.__unbiasRange = np.float(unbiasRange) self.__unbiasBins = np.int(self.bins*self.__unbiasRange/self.rang) # check biasFWHM if unbiasFWHM is None: unbiasFWHM = self.__biasFWHM else: assert is_number(unbiasFWHM) unbiasFWHM = np.float(unbiasFWHM) assert unbiasFWHM>=0 assert unbiasFWHM<=self.__unbiasRange/2. self.__unbiasFWHM = np.float(unbiasFWHM) self.__unbiasFWHMBins = np.int(self.bins*self.__unbiasFWHM/self.rang) # check height if unbiasHeight is None: unbiasHeight = self.__biasHeight assert is_number(unbiasHeight) self.__unbiasHeight = np.float(unbiasHeight) assert self.__unbiasHeight>=0 # check unbiasThreshold assert is_number(unbiasThreshold) self.__unbiasThreshold = np.float(unbiasThreshold) assert self.__unbiasThreshold>=0 # create bias step function b = self.__unbiasRange/self.__unbiasBins x = [-self.__unbiasRange/2.+idx*b for idx in range(self.__unbiasBins) ] self.__unbiasGuassian = gaussian(x, center=0, FWHM=self.__unbiasFWHM, normalize=False) self.__unbiasGuassian -= self.__unbiasGuassian[0] self.__unbiasGuassian /= np.max(self.__unbiasGuassian) self.__unbiasGuassian *= -self.__unbiasHeight self.__unbias = np.cumsum(self.__unbiasGuassian) def bias_scheme_by_index(self, index, scaleFactor=None, check=True): """ Bias the generator's scheme using the defined bias gaussian function at the given index. :Parameters: #. index(integer): The index of the position to bias #. scaleFactor(None, number): Whether to scale the bias gaussian before biasing the scheme. If None, bias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if not self.__biasHeight>0: return if check: assert is_integer(index) index = np.int(index) assert index>=0 assert index<=self.__bins if scaleFactor is not None: assert is_number(scaleFactor) scaleFactor = np.float(scaleFactor) assert scaleFactor>=0 # get start indexes startIdx = index-int(self.__biasBins/2) if startIdx < 0: biasStartIdx = -startIdx startIdx = 0 bias = np.cumsum(self.__biasGuassian[biasStartIdx:]).astype(np.float) else: biasStartIdx = 0 bias = self.__bias # scale bias if scaleFactor is None: scaledBias = bias else: scaledBias = bias*scaleFactor # get end indexes endIdx = startIdx+self.__biasBins-biasStartIdx biasEndIdx = len(scaledBias) if endIdx > self.__bins-1: biasEndIdx -= endIdx-self.__bins endIdx = self.__bins # bias scheme self.__scheme[startIdx:endIdx] += scaledBias[0:biasEndIdx] self.__scheme[endIdx:] += scaledBias[biasEndIdx-1] def bias_scheme_at_position(self, position, scaleFactor=None, check=True): """ Bias the generator's scheme using the defined bias gaussian function at the given number. :Parameters: #. position(number): The number to bias. #. scaleFactor(None, number): Whether to scale the bias gaussian before biasing the scheme. If None, bias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if check: assert is_number(position) position = np.float(position) assert position>=self.lowerLimit assert position<=self.upperLimit index = np.int(self.__bins*(position-self.lowerLimit)/self.rang) # bias scheme by index self.bias_scheme_by_index(index=index, scaleFactor=scaleFactor, check=check) def unbias_scheme_by_index(self, index, scaleFactor=None, check=True): """ Unbias the generator's scheme using the defined bias gaussian function at the given index. :Parameters: #. index(integer): The index of the position to unbias #. scaleFactor(None, number): Whether to scale the unbias gaussian before unbiasing the scheme. If None, unbias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if not self.__unbiasHeight>0: return if check: assert is_integer(index) index = np.int(index) assert index>=0 assert index<=self.__bins if scaleFactor is not None: assert is_number(scaleFactor) scaleFactor = np.float(scaleFactor) assert scaleFactor>=0 # get start indexes startIdx = index-int(self.__unbiasBins/2) if startIdx < 0: biasStartIdx = -startIdx startIdx = 0 unbias = self.__unbiasGuassian[biasStartIdx:] else: biasStartIdx = 0 unbias = self.__unbiasGuassian # get end indexes endIdx = startIdx+self.__unbiasBins-biasStartIdx biasEndIdx = len(unbias) if endIdx > self.__bins-1: biasEndIdx -= endIdx-self.__bins endIdx = self.__bins # scale unbias if scaleFactor is None: scaledUnbias = unbias else: scaledUnbias = unbias*scaleFactor # unbias weights weights = np.array(self.weights) weights[startIdx:endIdx] += scaledUnbias[0:biasEndIdx] # correct for negatives weights[np.where(weights<self.__unbiasThreshold)] = self.__unbiasThreshold # set unbiased scheme self.__scheme = np.cumsum(weights) def unbias_scheme_at_position(self, position, scaleFactor=None, check=True): """ Unbias the generator's scheme using the defined bias gaussian function at the given number. :Parameters: #. position(number): The number to unbias. #. scaleFactor(None, number): Whether to scale the unbias gaussian before unbiasing the scheme. If None, unbias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if check: assert is_number(position) position = np.float(position) assert position>=self.lowerLimit assert position<=self.upperLimit index = np.int(self.__bins*(position-self.lowerLimit)/self.rang) # bias scheme by index self.unbias_scheme_by_index(index=index, scaleFactor=scaleFactor, check=check) def generate(self): """Generate a random float number between the biased range lowerLimit and upperLimit.""" # get position position = self.lowerLimit + self.__binWidth*np.searchsorted(self.__scheme, generate_random_float()*self.__scheme[-1]) + self.__halfBinWidth # find limits minLim = max(self.lowerLimit, position-self.__halfBinWidth) maxLim = min(self.upperLimit, position+self.__halfBinWidth) # generate number return minLim+generate_random_float()*(maxLim-minLim) + self.__halfBinWidth class RandomIntegerGenerator(object): """ Generate random integer number between a lower and an upper limit. :Parameters: #. lowerLimit (number): The lower limit allowed. #. upperLimit (number): The upper limit allowed. """ def __init__(self, lowerLimit, upperLimit): self.__lowerLimit = None self.__upperLimit = None self.set_lower_limit(lowerLimit) self.set_upper_limit(upperLimit) @property def lowerLimit(self): """The lower limit of the number generation.""" return self.__lowerLimit @property def upperLimit(self): """The upper limit of the number generation.""" return self.__upperLimit @property def rang(self): """The range defined as upperLimit-lowerLimit""" return self.__rang def set_lower_limit(self, lowerLimit): """ Set lower limit. :Parameters: #. lowerLimit (number): The lower limit allowed. """ assert is_integer(lowerLimit) self.__lowerLimit = np.int(lowerLimit) if self.__upperLimit is not None: assert self.__lowerLimit<self.__upperLimit self.__rang = self.__upperLimit-self.__lowerLimit+1 def set_upper_limit(self, upperLimit): """ Set upper limit. :Parameters: #. upperLimit (number): The upper limit allowed. """ assert is_integer(upperLimit) self.__upperLimit = np.int(upperLimit) if self.__lowerLimit is not None: assert self.__lowerLimit<self.__upperLimit self.__rang = self.__upperLimit-self.__lowerLimit+1 def generate(self): """Generate a random integer number between lowerLimit and upperLimit.""" return generate_random_integer(self.__lowerLimit, self.__upperLimit) class BiasedRandomIntegerGenerator(RandomIntegerGenerator): """ Generate biased random integer number between a lower and an upper limit. To bias the generator at a certain number, a bias height is added to the weights scheme at the position of this particular number. .. image:: biasedIntegerGenerator.png :align: center :Parameters: #. lowerLimit (integer): The lower limit allowed. #. upperLimit (integer): The upper limit allowed. #. weights (None, list, numpy.ndarray): The weights scheme. The length must be equal to the range between lowerLimit and upperLimit. If None is given, ones array of length upperLimit-lowerLimit+1 is automatically generated. #. biasHeight(number): The weight bias intensity. #. unbiasHeight(None, number): The weight unbias intensity. If None, it will be automatically set to biasHeight. #. unbiasThreshold(number): unbias is only applied at a certain position only when the position weight is above unbiasThreshold. It must be a positive number. """ def __init__(self, lowerLimit, upperLimit, weights=None, biasHeight=1, unbiasHeight=None, unbiasThreshold=1): # initialize random generator super(BiasedRandomIntegerGenerator, self).__init__(lowerLimit=lowerLimit, upperLimit=upperLimit) # set weights self.set_weights(weights=weights) # set bias height self.set_bias_height(biasHeight=biasHeight) # set bias height self.set_unbias_height(unbiasHeight=unbiasHeight) # set bias height self.set_unbias_threshold(unbiasThreshold=unbiasThreshold) @property def originalWeights(self): """The original weights as initialized.""" return self.__originalWeights @property def weights(self): """The current value weights vector.""" weights = self.__scheme[1:]-self.__scheme[:-1] weights = list(weights) weights.insert(0,self.__scheme[0]) return weights @property def scheme(self): """The numbers generation scheme.""" return self.__scheme @property def bins(self): """The number of bins that is equal to the length of weights vector.""" return self.__bins def set_weights(self, weights): """ Set the generator integer numbers weights. #. weights (None, list, numpy.ndarray): The weights scheme. The length must be equal to the range between lowerLimit and upperLimit. If None is given, ones array of length upperLimit-lowerLimit+1 is automatically generated. """ if weights is None: self.__originalWeights = np.ones(self.upperLimit-self.lowerLimit+1) else: assert isinstance(weights, (list, set, tuple, np.ndarray)) if isinstance(weights, np.ndarray): assert len(weights.shape)==1 wgts = [] assert len(weights)==self.upperLimit-self.lowerLimit+1 for w in weights: assert is_number(w) w = np.float(w) assert w>=0 wgts.append(w) self.__originalWeights = np.array(wgts, dtype=np.float) # set bins self.__bins = len( self.__originalWeights ) # set scheme self.__scheme = np.cumsum( self.__originalWeights ) def set_bias_height(self, biasHeight): """ Set weight bias intensity. :Parameters: #. biasHeight(number): The weight bias intensity. """ assert is_number(biasHeight) self.__biasHeight = np.float(biasHeight) assert self.__biasHeight>0 def set_unbias_height(self, unbiasHeight): """ Set weight unbias intensity. :Parameters: #. unbiasHeight(None, number): The weight unbias intensity. If None, it will be automatically set to biasHeight. """ if unbiasHeight is None: unbiasHeight = self.__biasHeight assert is_number(unbiasHeight) self.__unbiasHeight = np.float(unbiasHeight) assert self.__unbiasHeight>=0 def set_unbias_threshold(self, unbiasThreshold): """ Set weight unbias threshold. :Parameters: #. unbiasThreshold(number): unbias is only applied at a certain position only when the position weight is above unbiasThreshold. It must be a positive number. """ assert is_number(unbiasThreshold) self.__unbiasThreshold = np.float(unbiasThreshold) assert self.__unbiasThreshold>=0 def bias_scheme_by_index(self, index, scaleFactor=None, check=True): """ Bias the generator's scheme at the given index. :Parameters: #. index(integer): The index of the position to bias #. scaleFactor(None, number): Whether to scale the bias gaussian before biasing the scheme. If None, bias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if not self.__biasHeight>0: return if check: assert is_integer(index) index = np.int(index) assert index>=0 assert index<=self.__bins if scaleFactor is not None: assert is_number(scaleFactor) scaleFactor = np.float(scaleFactor) assert scaleFactor>=0 # scale bias if scaleFactor is None: scaledBias = self.__biasHeight else: scaledBias = self.__biasHeight*scaleFactor # bias scheme self.__scheme[index:] += scaledBias def bias_scheme_at_position(self, position, scaleFactor=None, check=True): """ Bias the generator's scheme at the given number. :Parameters: #. position(number): The number to bias. #. scaleFactor(None, number): Whether to scale the bias gaussian before biasing the scheme. If None, bias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if check: assert is_integer(position) position = np.int(position) assert position>=self.lowerLimit assert position<=self.upperLimit index = position-self.lowerLimit # bias scheme by index self.bias_scheme_by_index(index=index, scaleFactor=scaleFactor, check=check) def unbias_scheme_by_index(self, index, scaleFactor=None, check=True): """ Unbias the generator's scheme at the given index. :Parameters: #. index(integer): The index of the position to unbias #. scaleFactor(None, number): Whether to scale the unbias gaussian before unbiasing the scheme. If None, unbias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if not self.__unbiasHeight>0: return if check: assert is_integer(index) index = np.int(index) assert index>=0 assert index<=self.__bins if scaleFactor is not None: assert is_number(scaleFactor) scaleFactor = np.float(scaleFactor) assert scaleFactor>=0 # scale unbias if scaleFactor is None: scaledUnbias = self.__unbiasHeight else: scaledUnbias = self.__unbiasHeight*scaleFactor # check threshold if index == 0: scaledUnbias = max(scaledUnbias, self.__scheme[index]-self.__unbiasThreshold) elif self.__scheme[index]-scaledUnbias < self.__scheme[index-1]+self.__unbiasThreshold: scaledUnbias = self.__scheme[index]-self.__scheme[index-1]-self.__unbiasThreshold # unbias scheme self.__scheme[index:] -= scaledUnbias def unbias_scheme_at_position(self, position, scaleFactor=None, check=True): """ Unbias the generator's scheme using the defined bias gaussian function at the given number. :Parameters: #. position(number): The number to unbias. #. scaleFactor(None, number): Whether to scale the unbias gaussian before unbiasing the scheme. If None, unbias gaussian is used as defined. #. check(boolean): Whether to check arguments. """ if check: assert is_integer(position) position = np.int(position) assert position>=self.lowerLimit assert position<=self.upperLimit index = position-self.lowerLimit # unbias scheme by index self.unbias_scheme_by_index(index=index, scaleFactor=scaleFactor, check=check) def generate(self): """Generate a random intger number between the biased range lowerLimit and upperLimit.""" index = np.int( np.searchsorted(self.__scheme, generate_random_float()*self.__scheme[-1]) ) return self.lowerLimit + index
89c1c943d3fad59ec6e8c0cb2f31b11b90f0bd0a
Santiago-Gallego/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
826
4
4
#!/usr/bin/python3 """Finds a peak in a list of unsorted integers""" def find_peak(list_of_integers): """Finds a peak in list_of_integers""" if list_of_integers is None or list_of_integers == []: return None lo = 0 hi = len(list_of_integers) mid = ((hi - lo) // 2) + lo mid = int(mid) if hi == 1: return list_of_integers[0] if hi == 2: return max(list_of_integers) if list_of_integers[mid] >= list_of_integers[mid - 1] and\ list_of_integers[mid] >= list_of_integers[mid + 1]: return list_of_integers[mid] if mid > 0 and list_of_integers[mid] < list_of_integers[mid + 1]: return find_peak(list_of_integers[mid:]) if mid > 0 and list_of_integers[mid] < list_of_integers[mid - 1]: return find_peak(list_of_integers[:mid])
b1f2e780aced33505537702651111e080efe3cd2
madmanmoon93/learning
/BonAppetit.py
691
3.953125
4
# Anna and Brian are sharing a meal at a restuarant and they agree to split the bill equally. # Brian wants to order something that Anna is allergic to though, and they agree that Anna won't pay for that item. # Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct. # https://www.hackerrank.com/challenges/bon-appetit/problem def arraySum(arr): sumArray = 0 for element in arr: sumArray+=element return sumArray def bonAppetit(bill, k, b): correctSplitBill = int((arraySum(bill) - bill[k]) / 2) if correctSplitBill == b: print("Bon Appetit") else: print(b - correctSplitBill)
0ebbc007ca58849eba17c1d492a5e23849cf935f
leguims/Project-Euler
/Problem0007.py
1,588
3.859375
4
Enonce = """ 10001st prime Problem 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import EulerTools # Iterator style class PrimeNumber: def __init__(self, rank=1): self.current = 2 self.index = rank def __iter__(self): return self def __next__(self): if self.index == 0 : raise StopIteration self.index = self.index - 1 while(True): for multiple in range(2, self.current): if (self.current % multiple == 0) and (self.current != multiple): break else: self.current = self.current + 1 return self.current - 1 self.current = self.current + 1 def main(): print(40*"=") print(Enonce) print(40*"-") import time rank = 10_001 #6 # About 3mins ! start = time.perf_counter() for prime in PrimeNumber(rank): #print(prime) pass end = time.perf_counter() Solution = prime print(f"{Solution} en {round(end-start,2)} secondes") print(f"The {rank}th prime number is {Solution}") # About 3s ! start = time.perf_counter() for prime in EulerTools.PrimeNumber(rank = rank): #print(prime) pass end = time.perf_counter() Solution = prime print(f"{Solution} en {round(end-start,2)} secondes") print(f"The {rank}th prime number is {Solution}") print(40*"-") print(f"Solution = {Solution}") print(40*"=") if __name__ == "__main__": # execute only if run as a script main()
181742d4dacff79e51101de20c82b0fe3fc08036
lawaloy/Practice
/mergeSortedArr.py
386
4
4
def mergeSortedArr(arr1, arr2): if not arr1 and not arr2: return arr1 if not arr2: return arr1 if not arr1: return arr2 if arr1[0] < arr2[0]: return [arr1[0]] + mergeSortedArr(arr1[1:], arr2) else: return [arr2[0]] + mergeSortedArr(arr1, arr2[1:]) print(mergeSortedArr([1,2,32,52,300,1000], [0,10,11,90,900]))
c12055ece24e1fcfd3bc3dd43db6cf930a83f242
JayWu7/Code
/leetcode_110.py
896
3.765625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: # dfs, 递归,分别计算左、右子树的深度,然后根据深度差,判断左右子树是否是平衡二叉树,利用val来存储深度值 def helper(node, depth): if node: depth += 1 depth_left = helper(node.left, depth) depth_right = helper(node.right, depth) if depth_left is False or depth_right is False or abs(depth_left - depth_right) > 1: return False else: return max(depth_right,depth_left) else: return depth return helper(root,0) is not False
f81e349419029b412f8cd73679a1e8373da39772
MilindShingote/Python-Assignments
/Assignment8_3.py
549
3.90625
4
from threading import * def OddList(Arr1): iSum=0; for j in Arr1: if Arr1[j]%2!=0: iSum=iSum+Arr1[j]; print("The Addition of Odd Number",iSum); def EvenList(Arr1): iSum=0; for k in Arr1: if Arr1[k]%2==0: iSum=iSum+Arr1[k]; print("The Addition of Even Number",iSum); def main(): No=int(input("Enter The Number: ")); Arr=[0]; for i in range(No): No2=int(input()); Arr.append(No2); t1=Thread(target=EvenList,args=(Arr,)) t2=Thread(target=OddList,args=(Arr,)) t1.start() t2.start() if __name__=="__main__": main()
db2c0016238582cfb822d9be4f08c7cd9b55b534
egbeyongtanjong/MIT_Data_Analysis_2020
/Lecture_notes/Lecture2.py
2,823
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 22:48:44 2020 @author: Egbeyong Lecture 2, problem set#0 """ #********************************************************************* """ #Printing name and date of birth DOB = input("Enter your date of birth:") print("**",DOB) name = input("Enter your last name:") print("**",name) print(name, DOB) """ #********************************************************************* """ Notes: A luddite is someone opposed to new technologies or stuck in the past Usage: I am abit of a luddite The Spyder IDE offers: syntax highlighting, auto-completion, smart-indent, integrated debugger Everything in python is an object Each object has a type (python provides a built in function can be called to obtain) and info about the type lets you know what you can with the object There are two base types: scalar and non-scalar scalar (primitive types) e.g. integers, float, boolean, none (you can try to beak further, but results will not be pleasant) There is no char in python, char is considered a string of length 1 expressions: e.g. 3 + 2 3/2 = 1.50 (integer division is not allowed) 3.0/2.0 = 1.5 The plus operator is overloaded, depending on the type of operands its function changes 1 + 2 = 3 (addition) 'a' + 'b' = ab (concatenaiton) Executed from a script (run from IDE), or executed directly in the interpreter (type in shell, and press enter) In a striaght line program with no loops/repetition every command gets executed exactly once This concept can be used to measure levels of complexity, and identify the types of functions that can be solved with such programs Programs are intended to be read not just executed, because if they are not read, they cannot be debugged. So enforcing indentation to make code more readable is a very good design decision. Visual structure matches the semantic structure in Python. In Java and C you can fool the reader with a misrepresented visual structure When thinking about program complexity, analyzing just the legnth of the program is not enough since the size of the data you want to use to evaluate the program is also important. Once loops are added, we have a turing complete language! You have to type cast, since input reads values as string """ #********************************************************************* """ # This program computes the cuberoot of a perfect cube (Simple method) # Example of a guess and check method # Exhaustive enumeration x = int(input("Enter an integer: ")) ans = 0 while ans * ans * ans < abs(x): ans = ans + 1 if ans*ans*ans != abs(x): print( x, " is not a perfect cube ") else: if x < 0: ans = -ans print("The cuberoot of ",x," is ",ans) """ #*********************************************************************
c17c00b82d55f053e66cb2c936b8d45abd7d85b3
jianjian198710/PythonStudy
/chapter2/In.py
138
3.625
4
permission="rw" print "w" in permission print "x" in permission users=["Tom","Mary","Peter"] print raw_input("Enter you name: ") in users
b4cc38cdd819fd27c9986df1a053ad2025d25206
ChHarding/python_ex_2
/ex_2_task_1.py
2,638
3.84375
4
# Python refresher exercises 2 - task 1 # Write and test a function is_valid_email_address(s) that evaluates string s as a valid email address # Returns: tuple of 2 elements (res, err): # res contains the result (None or error code) # err contains an error string ("seems legit" for None, a short error message for the error code # # Rules: (these are mine, not the official web standards!) # must have 3 parts: <A>@<B>.<C> # A must have between 3 and 16 alpha numeric chars (test: isalnum()) # B must have between 2 and 8 alpha numeric chars (test: isalnum()) # C must be one of these: com edu org gov # # Here are some tests and the expected results: # # charding@iastate.edu (None, 'Seems legit') # chris.edu (1, 'Must have exactly one @!') # chris@edu (4, 'post @ part must have exactly one dot!') # @bla.edu (2, 'pre @ part must contain 3 - 16 alfanum chars') # throatwobblermangrove@mpfc.org (2, 'pre @ part must contain 3 - 16 alfanum chars') # chris@X.com (5, 'part after @ and before . must contain 2 - 8 alfanum chars') # chris.harding@iastate.edu (3, 'pre @ part must only contain alfanum chars') # chris@pymart.biz (7, 'past-dot part invalid, must be from: com, edu, org, gov') # chris@letsgo!.org (6, 'part after @ and before . must only contain alfanum chars') # chris@megasavings.org (5, 'part after @ and before . must contain 2 - 8 alfanum chars') # tc@tank.com (2, 'pre @ part must contain 3 - 16 alfanum chars') # # your function MUST react the same (OK or error) but you don't have to use my exact error messages or codes # just something similar to that effect. You could even be more helpful e.g. # "throatwobblermangrove is too long (21 chars), must be 3 - 16" # It's OK to bail out at the first proven error, even if there would have been more errors later! # Also, I prb. forgot some possible edge cases, please add more if needed! # As proof, please manually copy/paste the console output for one run into a file called # results1.txt def is_valid_email_address(s): # your code here # This if ensures that the following is NOT run if this file was imported as a module (which we'll do next!) if __name__ == "__main__": # tests, including edge cases (incomplete? add more!) email_list = ["charding@iastate.edu", "chris.edu", "chris@edu", "@bla.edu", "throatwobblermangrove@mpfc.org", "chris@X.com", "chris.harding@iastate.edu", "chris@pymart.biz", "chris@letsgo!.org", "chris@megasavings.org", "tc@tank.com", ] # validate each email from the list for e in email_list: r, s = is_valid_email_address(e) if r == None: print(e, s) # OK else: print(f"{e} - error: {s}, error code: {r}") # Error
477414897d96731432e56536ffb3a96a0552c33b
Lutshke/Python-Tutorial
/functions.py
537
4.25
4
"i will show you how to create functions" # a function will return a value or will execute a certain part of code # we instaciate a function with the keyword "def" def test(): # your code will compile return # we can call this funtion now with test() # this function will now be called # for example def add(a,b): # a and b will be numbers we want to add return a + b print(add(1,4)) # print is the keyword to give us output in the console # this function should print "5" in the console
3eb9a713d22019140d149d09307df22cc4f69f0a
erazo-janet/math_with_python
/perfect_number.py
674
3.984375
4
#!/bin/python #In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the integer itself n = int(input("Enter any number: ")) sum = 0 # For loop is used to calculate all divisors of the number n entered by the user, and sum the divisors to check if it equals n for i in range(1, n): #This calculates the divisors of n, and sums all diviors together until all divisors have been added if(n % i == 0): sum = sum + i # Condition to check if the sum of n divisors equals n if (sum == n): print(n, "is a Perfect number!") else: print(n, "is not a Perfect number!")
2b5f5388b94212519e4603fc4e0f0dec2be8110c
rclamb27/Python-build-in-data-types
/part-1/mult3or5.py
698
4.21875
4
#!/usr/bin/env python3 # # Ryan Lamb # CPSC 223P-03 #2020-9-16 #rclamb27@cus.fullerton.edu """Ouputs the sum of all multiples of 3 or 5 below 10000000""" def main(): """Takes the multiples of 3 and 5 and sums them""" total_nums = int(input('Please input a range of numbers below 1000000: ')) print('You chose {} as the range.'.format(total_nums)) lst_3 = range(3, total_nums, 3) lst_5 = range(5, total_nums, 5) final_list = [] for i in lst_3: final_list.append(i) for i in lst_5: if not i in lst_3: final_list.append(i) print('The sum of all the multiples of 3 or 5 below 1000000 is {}'.format(sum(final_list))) if __name__ == '__main__': main()
fdf5d59ed7ddd3699e3bff34025cf5478550b47c
aletcherhartman/pong.py
/Old Files/importmath.py
2,731
3.921875
4
import pygame # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) pygame.init() # Set the height and width of the screen size = [700, 500] screen = pygame.display.set_mode(size) pygame.display.set_caption("Instruction Screen") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Starting position of the rectangle rect_x = 50 rect_y = 50 # Speed and direction of rectangle changeX = 5 changeY = 5 # This is a font we use to draw text on the screen (size 36) font = pygame.font.Font(None, 36) display_instructions = True instruction_page = 1 # -------- Instruction Page Loop ----------- while not done and display_instructions: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN and posY > 250: instruction_page += 1 changeX = 6 changeY = 7 if instruction_page == 2: display_instructions = False if event.type == pygame.MOUSEBUTTONDOWN and posY < 250: instruction_page += 1 changeX = 3 changeY = 4 if instruction_page == 2: display_instructions = False # Set the screen background screen.fill(WHITE) pos = pygame.mouse.get_pos() posY = pos[1] if instruction_page == 1: text = font.render("Choose Your Level", True, BLACK) screen.blit(text, [10, 10]) text = font.render("Easy", True, BLACK) screen.blit(text, [150,470]) text = font.render("Hard", True, BLACK) screen.blit(text, [350,470]) # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # Set the screen background screen.fill(BLACK) # Draw the rectangle pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50]) # Move the rectangle starting point rect_x += rect_change_x rect_y += rect_change_y # Bounce the ball if needed if rect_y > 450 or rect_y < 0: rect_change_y = rect_change_y * -1 if rect_x > 650 or rect_x < 0: rect_change_x = rect_change_x * -1 # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
28d3c49313c81a22bd9e88cd790db620c180c992
xiaoqianchang/DemoProject
/sample/datatype/dictionary_test.py
2,371
4.09375
4
#!/usr/bin/python3 # Dictionary(字典) dict_test = {} # 创建空字典 dict_test['one'] = "1 - 菜鸟教程" dict_test[2] = "2 - 菜鸟工具" tinydict = {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'} print(dict_test['one']) # 输出键为 'one' 的值 print(dict_test[2]) # 输出键为 2 的值 print(tinydict) # 输出完整的字典 print(tinydict.keys()) # 输出所有键 print(tinydict.values()) # 输出所有值 # 构造函数 dict() 创建一个字典 # 构造函数 dict() 可以直接从键值对序列中构建字典 print(dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])) # 元素为元组的列表 print(dict({('Runoob', 1), ('Google', 2), ('Taobao', 3)})) # 元素为元组的集合 print(dict([['Runoob', 1], ['Google', 2], ['Taobao', 3]])) # 元素为列表的列表 print(dict((('Runoob', 1), ('Google', 2), ('Taobao', 3)))) # 元素为元组的元组 print({x: x**2 for x in (2, 4, 6)}) print(dict(Runoob=1, Google=2, Taobao=3)) def example(a, b): # 函数返回多个值的时候,不一定是以元组的方式返回的,还要看自己定义的返回形式是什么。 return a, b def example2(a, b): return [a, b] print(type(example(3, 4))) print(type(example2(3, 4))) def test(*args): # 函数还可以接收可变长参数,比如以 "*" 开头的的参数名,会将所有的参数收集到一个元组上。 return args print(test(1, 2, 3, 4)) print(type(test(1, 2, 3, 4))) def sample(d): # 对字典进行for遍历,遍历的是字典的键,而不是值。 for c in d: print(c) print(sample(dict(Runoob=1, Google=2, Taobao=3))) def sample2(d): # 对字典进行for遍历,遍历的是字典的键,而不是值。 for c in d: # print(c, ':', dict[c]) print(c, end=':') # print(dict.keys()) print() sample2(dict(Runoob=1, Google=2, Taobao=3)) dict1 = {'abs': 1, 'cde': 2, 'd': 4, 'c': 567, 'd': 'key1'} print(dict1.items()) # 对于重复的键,后面的value会覆盖前面的value print(dict1.keys()) print(dict1.values()) for k, v in dict1.items(): print(k, ':', v) """ 字典推导式 """ p = {i: str(i) for i in range(1, 5)} print('p:', p) x = ['A', 'B', 'C', 'D'] y = ['a', 'b', 'c', 'd'] n = {i: j for i, j in zip(x, y)} print('n:', n) s = {x: x.strip() for x in ('he', 'she', 'I')} print('s:', s)
30a2c6a8ef9207c4649974f5ed88986d82226736
JaySurplus/online_code
/leetcode/python/52_n_queens_ii.py
2,433
3.828125
4
""" 51. N-Queens The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. """ import itertools class Solution(object): def totalNQueens2(self, n): solutions = [] for solution in itertools.permutations(range(n)): if len(set(x-y for x,y in enumerate(solution))) == \ len(set(x+y for x,y in enumerate(solution))) == n: solutions.append(solution) return len(solutions) def totalNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ col = [True] * n pDig = [True] * 2 * n nDig = [True] * 2 * n self.res = 0 self.dfs(0, n , col , pDig , nDig) return self.res def dfs(self, row , n , col , pDig , nDig): if row == n : self.res += 1 return else: for j in range(n): if col[j] and pDig[row+j] and nDig[row-j]: col[j] = False pDig[row+j] = False nDig[row-j] = False self.dfs(row+1, n , col ,pDig, nDig) col[j] = True pDig[row+j] = True nDig[row-j] = True """ def solveNQueens(self, n): def check(k, j): # check if the kth queen can be put in column j! for i in range(k): if board[i]==j or abs(k-i)==abs(board[i]-j): return False return True def dfs(depth, valuelist): if depth==n: res.append(valuelist); return for i in range(n): if check(depth,i): board[depth]=i s='.'*n dfs(depth+1, valuelist+[s[:i]+'Q'+s[i+1:]]) board=[-1 for i in range(n)] res=[] dfs(0,[]) return res """ import time sol = Solution() s1 = time.time() for i in range(1): res = sol.totalNQueens(10) e1 = time.time() s2 = time.time() for i in range(1): res = sol.totalNQueens2(8) e2 = time.time() print e1 - s1 print e2 - s2 print res
7feae3673f98de06b57434e03c5b179e78f61bc7
bopopescu/python-practice
/pycharm/telusko/anonymous-function.py
208
4.15625
4
#--- Anonymous functions can be denoted with lambda function f = lambda a : a*a result = f(5) print(result) #---- Adding 2 numbers using lambda function f = lambda a,b : a+b result = f(3,4) print(result)
0abc5140faeef6a1fe16ee6469840cde76483dfe
mxmiramontes/Python-Programs-
/WeatherDataSQL.py
2,021
3.65625
4
import sqlite3 as lite import sys try: cnxn = lite.connect('weather.db') #connecting to weather.db & returns an object of type, .db exisits in the current working directory print("Databse opened successfully") crsr = cnxn.cursor() #cursor- is the workhorse of database processing supports the excute() method crsr.execute("DROP TABLE IF EXISTS WeatherTable") #takes a sql statement, as a string, and executes it crsr.execute('''CREATE TABLE WeatherTable( ID INT NOT NULL, #holds integer values City TEXT(20)NOT NULL, #holds string values, delimited w/quotes Country TEXT(20)NOT NULL, Season INT NOT NULL, Temperature REAL, #holds floating-point values Rainfall REAL, PRIMARY KEY (ID));''') print("Table Created successfully") crsr.execute("INSERT INTO WeatherTable VALUES (1, 'Dallas', 'USA',1,24.8,5.9) ") #Insert- used to insert new record into database. crsr.execute("INSERT INTO WeatherTable VALUES (2, 'Dallas', 'USA',2,28.4,16.2) ") # Insert- is passed as an input to the execute() function crsr.execute("INSERT INTO WeatherTable VALUES (3, 'Dallas', 'USA',3,27.9,1549.4) ") #ID, City, Country, Season, Temp, Rainfall crsr.execute("INSERT INTO WeatherTable Values (4, 'Dallas', 'USA',4,27.6,346.0)") crsr.execute("INSERT INTO WeatherTable Values (5, 'London', 'United Kingdom',1,4.2,207.7)") crsr.execute("INSERT INTO WeatherTable Values (6, 'London', 'United Kingdom',2,8.3,169.6)") crsr.execute("INSERT INTO WeatherTable Values (7, 'London', 'United Kingdom',3,15.7,157.0)") crsr.execute("INSERT INTO WeatherTable Values (8, 'London', 'United Kingdom',4,10.4,218.5)") crsr.execute("INSERT INTO WeatherTable Values (9, 'Cairo', 'Egypt',1,13.6,16.5)") crsr.execute("INSERT INTO WeatherTable Values (10, 'Cairo', 'Egypt',2,20.7,6.5)") crsr.execute("INSERT INTO WeatherTable Values (11, 'Cairo', 'Egypt',3,27.7,0.1)") crsr.execute("INSERT INTO WeatherTable Values (12, 'Cairo', 'Egypt',4,22.2,4.5)") cnxn.commit() cnxn.close()
669c7e1d2a2c8988fb5830ee71859047c6f20d26
EnochEronmwonsuyiOPHS/Y11Python
/StringSliceChallanges03.py
200
3.96875
4
#StringSliceChallanges03.py #Enoch firstname = str(input("Enter your first name in lower case")) lastname = str(input("Enter your last name in lower case")) s = " " print(firstname + s + lastname)
53b0d6b6bfaebc3d33cad040944b6b21d0927d49
b4824583/HungarianMethod
/Function.py
2,860
3.71875
4
import numpy as np #----------------------------建立畫線矩陣 def build_draw_line_matrix(): draw_line_matrix=np.zeros((4,4)) draw_line_matrix=draw_line_matrix.astype(int) return draw_line_matrix #------------------------------- 如果發現所有的零都已經被劃線了則,則跳出迴圈。 def if_there_is_no_zero_in_matrix_than_break(display_zero_matrix): zero_number=0 for i in range(0,4): zero_number+=list(display_zero_matrix[i]).count(0) if zero_number==0: return False else: return True #-----------------------------------------------------開始畫線 #------------------------方法2用list與turple組合來劃線 #------------------------------計算總共有多少個零 def count_zero_in_this_matrix(matrix,whether_reverse): how_many_zero_in_matrix = [] # 這個變數是為了計算s有多少個0在同一列或者同一行 for i in range(0, 4): name = "row-" + str(i) how_many_zero_in_matrix.append((name, list(matrix[i]).count(0))) for i in range(0, 4): name = "col-" + str(i) how_many_zero_in_matrix.append((name, list(matrix[:, i]).count(0))) # print(how_many_zero_in_matrix) if whether_reverse==1: sort_how_many_zero_in_matrix = sorted(how_many_zero_in_matrix, key=lambda s: s[1], reverse=True) else: sort_how_many_zero_in_matrix = sorted(how_many_zero_in_matrix, key=lambda s: s[1], reverse=False) return sort_how_many_zero_in_matrix def build_display_zero_matrix(matrix): display_zero_matrix=np.zeros((4,4)) display_zero_matrix=display_zero_matrix.astype(int) for i in range(0,4): for j in range(0,4): if matrix[i][j]==0: display_zero_matrix[i][j]=0 else: display_zero_matrix[i][j]=-99 return display_zero_matrix #--------------------------------------------------畫完線之後檢查,所有的0是否都被畫到了,沒有畫到則繼續loop下去 def if_element_have_zero_than_draw_a_line(sort_how_many_zero_in_matrix,display_zero_matrix,draw_line_matrix): for i in range(0,4): which_row_or_column=sort_how_many_zero_in_matrix[i][0].split("-") j=int(which_row_or_column[1]) print (sort_how_many_zero_in_matrix[i][0]) if which_row_or_column[0]=="row": for i in range(0,4): if display_zero_matrix[j][i]==0: display_zero_matrix[j][i]=1 draw_line_matrix[j][i]+=1 elif which_row_or_column[0]=="col": for i in range(0,4): if display_zero_matrix[i][j]==0: display_zero_matrix[i][j]=1 draw_line_matrix[i][j] += 1 if if_there_is_no_zero_in_matrix_than_break(display_zero_matrix)==False: break return draw_line_matrix
0265906c8ef85fdcabf71334bfaa6c677652925c
amitagrahari2512/PythonBasics
/Iterator/Iterator.py
408
4.375
4
print("List have provide a function called iter(listObject)") print("Then we can use iteratorObj.__next__() method to print next value") print("Or we can use next(iteratorObj) to print next value") nums = [2,10,4,17] it = iter(nums) print("it.__next__() : ",it.__next__()) print("it.__next__() : ",it.__next__()) print("next(it) : ",next(it)) print("Iterate Through for loop") for i in it: print(i)
d6ba9590e1c05432479285e206396f41d4f1a986
maokaiqi/learn_Python_Hard_Way
/ex5.py
2,294
3.5625
4
# -- coding:utf-8 -- my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 #lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth #this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight) #加分题 print "第一题;" name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # weight = 180 #lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' print "Let's talk about %s." % name # %s是输出字符串 %d是有符号的十进制整数 print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth #this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight) print "第二题:" print "Let's talk about %r." % name print "第三题:" print "%a 和 %A 是浮点数、十六进制数字和p-计数法" print "%c 字符" print "%d 有符号十进制整数" print "%f 浮点数(包括float和doulbe)" print "%e(%E) 浮点数指数输出[e-(E-)计数法]" print "%g(%G) 浮点数不显示无意义的零‘0’" print "%i 有符号十进制整数(与%d相同)" print "%u 无符号十进制整数" print "%o 八进制整数" print "%x(%X) 十六进制整数" print "%p 指针" print "%s 字符串" print "%% % 如同转义字符\\ " print "第四题:" num = input("输入要转换的数字:") index = input("请问你是要转换什么结果?输入数字1:英寸转换为厘米,输入数字2:磅转换为千克:") if index == 1: inches_to_cm = num * 2.54 print "您输入的 %g 英寸的转换结果为 %g 厘米。" % (num , inches_to_cm) elif index == 2: lb_to_kg = num * 0.4536 print "您输入的 %g 磅的转换结果为 %g 千克。" % (num , lb_to_kg) else: print "您输入的数字有误!"
7c256c7daabe94193b1b1abe352d8976b74ea71a
taka16a23/.pylib
/confirm/confirmobj.py
3,830
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- r"""confirm -- DESCRIPTION """ from abc import ABCMeta, abstractmethod from userinput import UserInputer, ConsoleUserInput import Tkinter import tkMessageBox class Confirm(object): r"""Confirm Confirm is a object. Responsibility: """ __metaclass__ = ABCMeta @abstractmethod def confirm(self, ): raise NotImplementedError() class ConsoleConfirm(Confirm): r"""ConsoleConfirm ConsoleConfirm is a Confirm. Responsibility: """ def __init__(self, prompt=None, acceptables=None, disacceptables=None): r""" @Arguments: - `prompt`: - `acceptables`: - `disacceptables`: """ self._prompt = prompt or 'Confirm y or n: ' self._acceptables = acceptables or ['y', 'yes'] self._disacceptables = disacceptables or ['n', 'no'] def _input(self, ): r"""SUMMARY _input() @Return: @Error: """ string = UserInputer(ConsoleUserInput(self._prompt)).input() return string.lower() def confirm(self, ): r"""SUMMARY confirm() @Return: @Error: """ got = self._input() if got in self._acceptables: return True if got in self._disacceptables: return False return None def get_prompt(self, ): r"""SUMMARY get_prompt() @Return: @Error: """ return self._prompt def set_prompt(self, prompt): r"""SUMMARY set_prompt(prompt) @Arguments: - `prompt`: @Return: @Error: """ self._prompt = prompt def get_acceptables(self, ): r"""SUMMARY get_acceptables() @Return: @Error: """ return self._acceptables def set_acceptables(self, acceptables): r"""SUMMARY set_acceptables(acceptables) @Arguments: - `acceptables`: @Return: @Error: """ self._acceptables = acceptables def get_disacceptables(self, ): r"""SUMMARY get_disacceptables() @Return: @Error: """ return self._disacceptables def set_disacceptables(self, disacceptables): r"""SUMMARY set_disacceptables(disacceptables) @Arguments: - `disacceptables`: @Return: @Error: """ self._disacceptables = disacceptables class GUIConfirm(Confirm): r"""GUIConfirm GUIConfirm is a Confirm. Responsibility: """ def __init__(self, title=None, msg=None): r""" @Arguments: - `title`: - `msg`: """ self._title = title or 'Confirm' self._msg = msg or 'Confirm' def confirm(self, ): r"""SUMMARY confirm() @Return: @Error: """ root = Tkinter.Tk() root.withdraw() return tkMessageBox.askyesno(self._title, self._msg) def get_title(self, ): r"""SUMMARY get_title() @Return: @Error: """ return self._title def set_title(self, title): r"""SUMMARY set_title(title) @Arguments: - `title`: @Return: @Error: """ self._title = title def get_msg(self, ): r"""SUMMARY get_msg() @Return: @Error: """ return self._msg def set_msg(self, msg): r"""SUMMARY set_msg(msg) @Arguments: - `msg`: @Return: @Error: """ self._msg = msg # For Emacs # Local Variables: # coding: utf-8 # End: # confirm.py ends here
6f5e77d6d0af445e02116f7a505eaa49eb90afb2
Aasthaengg/IBMdataset
/Python_codes/p03719/s406138597.py
89
3.53125
4
a,b,c = map(int,input().split()) ans = 'No' if(a <= c <= b): ans = 'Yes' print(ans)
a9132db6b465ee95d0cf245c21be447031ae5b16
speed785/Python-Projects
/Class Operations.py
505
3.796875
4
#Coded by : James Dumitru class Operations: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 #Mutator methods def addtion(self, num1, num2): result = num1 + num2 return result def subtraction(self, num1, num2): result = num1 - num2 return result def multiplication(self, num1, num2): result = num1 * num2 return result def division(self, num1, num2): result = num1 // num2 return result
f328e19b0f3f2c775dc1918c73f1722d3fb05fb7
Kalebu/Bootcamp
/Bootcamp Day 1/prime.py
664
3.90625
4
def prime(n): if n == 0: return [] elif type(n) is not int: raise TypeError elif n<0: raise ValueError # Create a list with the first prime number lst = [2] # Test each number for primeness, starting with 3 testNum = 3 while True: prime = True # Check if number under test is prime for item in lst: if testNum % item == 0: prime = False break testNum += 1 if prime: lst.append(testNum) testNum += 1 # Break if len(lst) == n if len(lst) == n: break return lst
a689e361a6001ee5b645ddea23fea1dd3d41018d
rafa-santana/Curso-Python
/Aula 07/ex08.py
159
3.78125
4
n = float(input('Digite um valor em metros:')) print('O valor em centímetros é: {:0f}'.format(n*100)) print('O valor em milimetros é: {:0f}'.format(n*1000))
90d322b30932958ece705c842b53efbf91e20999
egemzer/intro2programmingnanodegree
/Movie Website/triforce.py
866
3.796875
4
import turtle #draws a triforce def draw_triforce(): window = turtle.Screen() window.bgcolor("white") index = 0 triangles = 4 #there are 4 triangles in a triforc sides = 3 deg = 120 zelda = turtle.Turtle() zelda.shape("turtle") zelda.speed(1) zelda.color("orange") zelda.pencolor("orange") zelda.fillcolor("yellow") #draw the big left angled line zelda.left(120) zelda.forward(200) #draw the bottom left triangle zelda.left(120) zelda.forward(100) zelda.left(120) zelda.forward(100) #draw the bottom right triangle zelda.right(120) zelda.forward(100) zelda.right(120) zelda.forward(100) zelda.left(120) zelda.forward(100) #draw the big right angled line zelda.left(120) zelda.forward(200) window.exitonclick() draw_triforce()
c2346fe756797425511aaf0343203babd1847d57
deepbsd/OST_Python
/ostPython4/test_subdictclass.py
955
3.875
4
#!/usr/bin/env python3 # # # test_subdictclass.py # # Lesson 6: Using Exceptions Wisely # # by David S. Jackson # 7/24/2015 # # OST Python4: Advanced Python # for Pat Barton, Instructor # """ Tests the subdictclass.py program. """ from subdictclass import SubDict import unittest class TestSubDict(unittest.TestCase): def setUp(self): self.defkey = 'mykey' self.a = SubDict(self.defkey) self.a['one'] = 1 self.a['two'] = 2 def test_subdict(self): 'Tests SubDict.__getitem__ . . . ' self.assertEqual(self.a['one'], 1) self.assertEqual(self.a['two'], 2) def test_missingkey(self): "What happens when key doesn't exist? Shouldn't be KeyError!" boguskey = 'bogus_whatnot' #expected = 'default value' expected = self.a[self.defkey] self.assertEqual(self.a[boguskey], expected) if __name__ == '__main__': unittest.main()
332a566c000bd64bf20dbad6bc42f61936ded1ed
abhishek436/Data_Structure
/Singly_Linked_List/sum_two_linkedlist.py
1,827
3.984375
4
class Node: def __init__(self,data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None def insert(self,data): new_node = Node(data) if(self.head is None): self.head = new_node return else: temp = self.head while(temp.next is not None): temp = temp.next temp.next = new_node def sum_of_num(self,num1,num2): sumnode = None temp = None c = 0 while(num1 is not None or num2 is not None): if(num1 == None): f = 0 else: f = num1.data if(num2 == None): s = 0 else: s = num2.data sum = f+s+c c = 1 if sum >= 10 else 0 sum = sum if sum < 10 else sum%10 sumnode = Node(sum) if self.head is None: self.head = sumnode else: temp.next = sumnode temp = sumnode if num1 is not None: num1 = num1.next if num2 is not None: num2 = num2.next if(c > 0): sumnode.next = Node(c) def print(self): temp = self.head while (temp != None): print(temp.data, end=" ") temp = temp.next if __name__ == '__main__': num1 = linkedlist() num2 = linkedlist() num1.insert(5) num1.insert(6) num1.insert(3) num2.insert(8) num2.insert(4) num2.insert(2) print("num1: ", end=" ") num1.print() print("\nnum2: ", end=" ") num2.print() res = linkedlist() res.sum_of_num(num1.head,num2.head) print("\nSum: ", end=" ") res.print()
8c82054673b1fe7a642ca334dd629c66ddd3d839
DanielMalheiros/geekuniversity_programacao_em_python_essencial
/Exercicios/secao06_estruturas_de_repeticao/exercicio46.py
754
4.15625
4
"""46- Faça um programa que gera um número aleatório de 1 a 1000. O usuário deve tentar acertar qual o número foi gerado, a cada tentativa o programa deverá informar se o chute é menor ou maior que o número gerado. O programa acaba quando o usuário acerta o número gerado. O programa deve informar em quantas tentativas o número foi descoberto.""" from random import randrange count = 1 numero = randrange(1000) escolha = int(input('Escolhi um número de 1 a 1000, tente adivinhar!')) while escolha != numero: if escolha < numero: escolha = int(input('Tá baixo! =>')) count += 1 if escolha > numero: escolha = int(input('Tá alto! =>')) count += 1 print(f'VOCÊ ACERTOU!!!\nForam {count} tentativas!')
99647b0e7db2d239165ab80ff5fd145b85c76839
iandioch/CPSSD
/ca117/lab1.2/pi_12.py
152
3.515625
4
from math import pi import sys n = int(sys.argv[1]) last = str(pi)[n+1] if str(pi)[n+2] >= '5': last = str(int(last) + 1) print(str(pi)[:n+1] + last)
eb13f90228ba3f29a4e6e9d85a4ca2a272468271
riyabhatia26/Code
/convert complex numbers to Polar coordinates.py
178
3.859375
4
# Python code to implement # the polar()function # importing "cmath" # for mathematical operations import cmath # using cmath.polar() method num = cmath.polar(1) print(num)
1ea46afb58f3220516d08578747a8e5a7e411943
gaoshang1999/Python
/interview/insight.py
903
3.6875
4
import random a = [1 , 2, 3] def f(a): a.append(4) f(a) # print(a) # A = [ random.randint(0,9) for _ in range(10)] # print(A) def intersecttions(A, B, C): for a in A: if a in B and a in C: yield a # return True return None A = [ random.randint(0,10) for _ in range(11)] print(A) B = [ random.randint(0,10) for _ in range(11)] print(B) C = [ random.randint(0,10) for _ in range(11)] print(C) def find_intersections(): return list(intersecttions(A, B, C)) #and intersecttions(B, A, C) and intersecttions(C, B, A) def find_intersections_2(): a = set(A) b = set(B) c = set(C) print(a & b & c ) return (a & b & c) a = find_intersections() print(a) b = find_intersections_2() print(b) evens = [a for i, a in enumerate(A) if i % 2==0 and a % 2 == 0] print(evens)
a7206457fd0f66281c599c4fddf79b3e549ff2d4
stevecatt/week1python
/dictionarys.py
2,487
4.25
4
#gonna create a task list #task ={} tasks = [] def view_all_tasks(): for task in tasks: #print(task) #for key,value in task.items(): # print out the index number of the task in user type stuff by adding 1 # end "=" keeps it on the same line # prints tasks by index +1 then task by key print (f"{tasks.index(task) + 1 } - {task['title']} - {task['prior']}") # now we have to step through the keys #for key in task.keys(): #print(key) #print("-" , task[key], end=" ") #print(key, value) #print(key) #print(value) #print("\n") task_del = "" def del_task(): view_all_tasks() task_del = int(input ("which task do you want to delete? " ))-1 #view_all_tasks() #ind_del = task_del-1 #while task_del > len(tasks): #print ("Please select a valid Task Number") if task_del > int(len(tasks)): print ("Please select a valid Task Number") view_all_tasks() elif task_del <= len(tasks): del tasks[task_del] # create a menu def show_menu(): print("Press 1 to add task: ") print("Press 2 to delete task: ") print("Press 3 to view all tasks: ") print("Press q to quit: ") #def nef(): #new line def add_task(): task_input = input("enter task ") task_priority= input("enter priority High Med Low : ") task={"title": task_input,"prior": task_priority} #combining imputs to library # print(task) # get rid of this later tasks.append(task)# adding dict to array # print (tasks)# get rid of this later #show_menu() user_input = "" while user_input != "q": show_menu() user_input = input("Enter choice: ") if user_input == "1": add_task() #moved the rest to function for tidyness #task_input = input("enter task ") #task_priority= input("enter priority High Med Low : ") #task={"title": task_input,"prior": task_priority} #combining imputs to library #print(task) # get rid of this later #tasks.append(task)# adding dict to array #print (tasks)# get rid of this later elif user_input== "2": del_task() #print("delete task") elif user_input=="3": view_all_tasks() # print(tasks(task.key)) # for x in task.keys(): # print (x) #print(task(key)
6bc310de4b15e5721aa0c229f08812570a0f0f6d
shrutikabirje/Python-Programs
/p5.py
449
4.21875
4
Given a two list. Create a third list by picking an odd-index element from the first list and even index elements from second. l1= [3, 6, 9, 12, 15, 18, 21] l2= [4, 8, 12, 16, 20, 24, 28] l3= [] l4=[] l5=[] for i in range (len(l1)): if i%2!=0: l3.append(l1[i]) print("odd elements in list 1:",l3) for j in range (len(l2)): if j%2==0: l4.append(l2[j]) print("even elements in list 2:",l4) l5=(l3+l4) print("Final list:",l5)
58affb9bb758929fca566fbd68e664627437aa09
wolskey/cornway_game_of_life
/main.py
4,826
3.96875
4
import random import time def generate_empty_board(x,y): """ generates matrix x rows y columns filled with zeros :param x: n of rows :param y: n of columns :return: lists of lists of zeros """ board = [[0]*y for i in range(x)] return board def generate_initial_population(board, n): """ replaces n random zeroes with ones in given table :param board: given table :param n: number of cells to replace :return: transformed matrix """ if n > len(board)*len(board[0]): print("More living cells than space on this board") return board i = 0 while i < n: x = random.randint(0, len(board)-1) y = random.randint(0, len(board[0])-1) if board[x][y] == 0: board[x][y] = 1 i = i + 1 print("{}/{} filled.".format(i,n)) return board def count_population(Tab): """ counts number of alive cells Args: Tab - board of given frame Return: number of alive cells """ n = 0 #number of alive cells for i in range(len(Tab)): for j in range(len(Tab[i])): if Tab[i][j] == 1: n = n + 1 return n def compare_generations(Tab1, Tab2): """ Function which compare two given tables :param Tab1: first table :param Tab2: second table :return: True if tables are the same False if not """ if Tab1 == Tab2: return True else: return False def evolve_population(board): """ Function which will apply rules to all board simultaneously :param board: board from present generation :return: new board after applying rules of game to each cell """ new_board = generate_empty_board(len(board),len(board[0])) for i in range(len(board)): for j in range(len(board[i])): if check_if_alive(i , j , board): new_board[i][j] = 1 else: new_board[i][j] = 0 return new_board def check_if_alive(x, y, Tab): """ Function which determine if cell should stay alive :param x: x coordinate of checked cell :param y: y coordinate of checked cell :param Tab: table of current frame :return: True if cell will be alive in the next fram False if not """ length = len(Tab) - 1 width = len(Tab[0]) - 1 n = 0 # number of neighbouring living cells for i in [x - 1, x, x + 1]: # count number of neigh for j in [y - 1, y, y + 1]: if i < 0 or j < 0: continue if i > length or j > width: continue if (i == x and j == y): continue n += Tab[i][j] # adding no of neigh if Tab[x][y] == 1: # return state of cell taking conditions (rules) if n == 2 or n == 3: return True else: return False else: if n == 3: return True else: return False def print_board(board, n): """ Function that prints board and info about state of game :param board: board of current frame :param n: number of generation :return: None """ print("Game of Life | Generation: {} | Alive cells : {} | Dead cells: {} | Size: {} |".format(n, count_population(board), len(board)*len(board[0])- count_population(board), len(board)*len(board[0]))) print("+" +((len(board[0])*2)+1)*"-" + "+") #frame of board for i in range(len(board)): print("|", end=" ") #frame of board for j in range(len(board[0])): if board[i][j] == 1: print("%", end=" ") else: print("-", end=" ") print('|') #frame of board print("+" +((len(board[0])*2)+1)*"-" + "+") #frame of board return x = int(input("Please insert width: ")) y = int(input("Please insert height: ")) board = generate_empty_board(x,y) initial = int(input("Please insert n of alive cells: ")) board = generate_initial_population(board,initial) #board = [[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,1,1,1,0,0,0] # ,[0,0,0,0,1,0,0,0,0,0] # ,[0,0,0,0,0,1,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0] # ,[0,0,0,0,0,0,0,0,0,0]] glider pattern old_board = [] generation = 0 while not compare_generations(board,old_board): generation += 1 print_board(board,generation) old_board = board board = evolve_population(board) time.sleep(0.8) print("Game of Life ended after {} populations, with {} alive cells".format(generation, count_population(board))) # while True: # board = evolve_population(board) # print(*board, sep='\n', end='\n \n') # time.sleep(1)
3cf9e0168a7c7b2bdb01ab3d1fda1680b240713c
wulfebw/algorithms
/scripts/search/ucs.py
1,499
3.6875
4
import priority_queue import search_algorithm class UCS(search_algorithm.SearchAlgorithm): """ Djikstra's Time: O(nlgn) where n is states between start state and goal state in shortest path, lgn factor from the priority queue operations (heapify) """ def solve(self, problem): done = set() start = problem.startState() goal_state = None cache = {start:(0, start)} pq = priority_queue.PriorityQueue() pq.push(0, start) while not pq.is_empty(): cost_to, s = pq.pop() # once we pop a state skip it if s in done: continue done.add(s) # goal then must have traversed shortest path if problem.isGoal(s): self.cost, _ = cache[s] goal_state = s break # add each ns to pq if cost lower now for (a,ns,c) in problem.succAndCost(s): total = cost_to + c if ns not in cache: cache[ns] = (total, s) pq.push(total, ns) elif cache[ns][0] > total: cache[ns] = (total, s) pq.push(total, ns) # collect actions with backpointers self.actions = [goal_state] s = goal_state while s != start: ps = cache[s][1] self.actions.append(ps) s = ps self.actions.reverse()
ee4e5c6479d2561885b458d7c41d8c47243c2aa6
albertojr/estudospython
/ex030.py
140
4.03125
4
numero = int(input('Digite um numero inteiro: ')) if numero%2 == 0: print('Esse numero é Par') else: print('Esse numero é Impar')
b176cce32f1589f3ccb37c632ca8591c7bc8c9c9
andreafresco/Project-Euler
/p010.py
910
3.96875
4
# # Solution to Project Euler problem 10 # Copyright (c) Andrea Fresco. All rights reserved. # # https://projecteuler.net/problem=10 # https://github.com/andreafresco/Project-Euler # def Is_prime(n): # check if the number n is prime assert n > 0 i = 2 # we restrict the search of prime numbers between 2 and sqrt(n) while i*i <= n: # equivalent to i <= sqrt(n) if n%i == 0: return False # if the number has a divisor then it's NOT prime i+=1 return True # if no divisors were found then it's a prime number def summation_of_primes(N_max): somma = 0 # init the sum to 0 for i in range(2, N_max): if Is_prime(i): somma += i return somma if __name__ == "__main__": print(summation_of_primes(2*10**6)) # it gives the right result but it takes 10s - TO BE IMPROVED!
715e90abb2a58a997fc1bd3a02abcc8d81d581cf
fadia-hussain/final-project
/python-final-project.py
567
3.90625
4
# final-project # Fadia Hussain import random students = ["Hasan", "John", "Amira", "Salma", "Ashley", "Peter","Omar", "Shehnaz","Claudio", "Kaie","Mariam", "Rubel", "Mishika", "Fadia"] length = len(students) print("The number of students in this class is: ",length) print("And now they will be separated into groups of two: \n") for index, value in enumerate(students): if index % 2 == 0: print('Group : ' + value + ' + ' + students[index + 1]) # team = random.choice(students) + random.choice(students) # print("Group: " + team) # del (team)
bcdb4ca7db6ba63a1566be6ed9ca72cfe8441425
aanchal1234/Assignment1
/assignment17.py
2,138
4.65625
5
#1Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. import tkinter from tkinter import * import sys root=Tk() root.title("my app") root.geometry("250x250") root.minsize(200,200) root.maxsize(300,300) l=Label(root,text="Hello World!",width=25,font='20') l.pack() b=Button(root,text="Hello World!",width=25,command='exit') b.pack() root.mainloop() #2 Write a python program to in the same interface as above and create a action when the button is click it will display some text. import tkinter from tkinter import * def display(): l = Label(root,text="world",width=25,bg="pink") l.place(x=60,y=120) root=Tk() root.title("myapp") root.geometry("250x250") root.minsize(200,200) root.maxsize(300,300) l = Label(root,text="Hello",width=25,bg="blue") l.place(x=30, y=100) b=Button(text="show",width=25,command=display) b.place(x=20,y=100) root.mainloop() #3. Create a frame using tkinter with any label text and two buttons.One to exit and other to change the label to some other text. # # import tkinter # # from tkinter import * # # root=Tk() # # f1=Frame(root) # # def show(): # # l2=Label(f1,text="new text",fg='blue') # # l2.grid(row=3,column=1) # # # # l1=Label(f1,text="hello world!",fg='red') # # l1.grid(row=1,column=1) # # root.geometry("250x250") # # b=Button(f1,text="exit",bg="blue",width=20,command=exit) # # b.grid(row=0,column=0) # # b=Button(f1,text="label",bg="blue",width=20,command=show) # # b.grid(row=2,column=0) # # f1.pack() # # root.mainloop() # # # #4 Write a python program using tkinter interface to take an input in the GUI program and print it # # import tkinter # # from tkinter import * # # def show(): # # t1=entry.get() # # l2=Label(root,text=1,fg='blue') # # l2.place(x=60,y=70) # # root=Tk() # # root.title("myapp") # # root.geometry("250x250") # # root.minsize(200,200) # # root.maxsize(300,300) # # root.resizable(false,false) # # b=Button(f1,text="exit",bg="blue",width=20,command=exit) # # b.place(x=40,y=140) # b=Button(f1,text="show",bg="blue",width=20,command=show) # b.place(x=50,y=100) root.mainloop()
38dd8d776eb5eba1fbd89a7bb70f20329f4e1080
KevinChen1994/leetcode-algorithm
/problem-list/Tree/687.longest-univalue-path.py
950
3.890625
4
# !usr/bin/env python # -*- coding:utf-8 _*- # author:chenmeng # datetime:2021/2/4 15:54 # 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 longestUnivaluePath(self, root: TreeNode) -> int: self.result = 0 self.dfs(root) return self.result def dfs(self, root): if not root: return 0 left = self.dfs(root.left) right = self.dfs(root.right) left = left + 1 if root.left and root.val == root.left.val else 0 right = right + 1 if root.right and root.val == root.right.val else 0 # 判断左右子树的unipathvalue的和是否大于result的值 self.result = max(self.result, left + right) # 返回的时候只能返回左右子树最大的一个unipathvalue return max(left, right)
862975cb6685d97ba6ac2047673c4df8d8b55aa3
jhaze420/smiesznepsy
/fhfhfhfhfhf.py
202
3.59375
4
for j in range(1, 5): print("***") for k in range(1,5): print(k * "*") for l in range(1,5): print((4-l)*" " + l*"*") for m in range(1,5): print((4-m)*" " + m*"*" + (m-1)*"*")
3422311f0acf9faeee7c0a9468d81fedb045a4e4
Anjualbin/workdirectory
/Functional programming by sajay/nested dictionary accessing values.py
823
3.765625
4
users={ 1000:{"acconu_num":1000,"password":"user1","balance":3000}, 1001: {"acconu_num": 1001, "password": "user2", "balance": 4000}, 1002: {"acconu_num": 1002, "password": "user2", "balance": 5000}, 1003: {"acconu_num": 1003, "password": "user3", "balance": 6000} } # Check for username and password def validate(accno,passw): if accno in users: if passw==users[accno]["password"]: print("Succes") else: print("Wrong password") else: print("Invalid accountno") user=int(input("Enter the account number:")) passw=input("Enter the password:") validate(user,passw) # getbalance def getbalance(accno): if accno in users: print(users[accno]["balance"]) else: print("Invalid account no") getbalance(1003)
f49da0f4c21f50ee607b7e4e0b46c1a3ff7128f2
ashiqcvcv/guvi
/DS/task01.py
8,701
3.734375
4
''' 3Sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] ''' nums = [-1, 0, 1, 2, -1, -4] stack = [] length = len(nums) out = [] def isabsent(out,array): for element in out: numleft = 0 for j in range(len(array)): if element[j] < 0: numleft += element[j] elif element[j] > 0: numleft -= element[j] if array[j] < 0: numleft -= array[j] elif array[j] > 0: numleft += array[j] if numleft == 0: return False return True def summ(current,sumtotal,stack): if len(stack) == 3: if sumtotal == 0 and isabsent(out,stack): out.append(stack.copy()) return if current == length: return stack.append(nums[current]) summ(current+1,sumtotal+nums[current],stack) stack.pop() current += 1 summ(current,sumtotal,stack) return start = 0 # summ(0,0,stack) # print(out) ################################################################################################################################## ''' Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] ''' matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] def zerospread(matrix): row = [] column = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: row.append(i) column.append(j) for i in row: for j in range(len(matrix[i])): matrix[i][j] = 0 for j in column: for i in range(len(matrix)): matrix[i][j] = 0 return matrix # print(zerospread(matrix)) ################################################################################################################################## ''' Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] ''' def comp(string1,string2): if len(string1) == len(string2): summ = 0 for i in range(len(string1)): summ += ord(string1[i]) summ -= ord(string2[i]) return True if summ == 0 else False def dequeue(array,index): stack = [] length = len(array) - 1 while len(array) > 0: if length == index: array.pop() while len(stack) > 0: array.append(stack.pop()) return array else: stack.append(array.pop()) length -= 1 def anagramFind(array): out = [] temp = [] temp.append(array[0]) dequeue(array,0) i = 0 while len(array) > 0: if i == len(array): out.append(temp) temp = [array[0]] dequeue(array,0) i = -1 elif comp(array[i],temp[0]): temp.append(array[i]) dequeue(array,i) i -= 1 i += 1 out.append(temp) return out def lexo(array): i,j = 0,0 k,l = 1,0 while i < len(array)-2: if k == len(array): i += 1 k = i+1 while ord(array[i][j]) == ord(array[k][l]): j += 1 l += 1 if ord(array[i][j]) > ord(array[k][l]): array[i],array[k] = array[k],array[i] j = 0 l = 0 k += 1 return array array = ["eat", "tea", "tan", "ate", "nat", "bat"] # out = anagramFind(array) # for i in out: # i = lexo(i) # print(out) ################################################################################################################################### # Linked List problems class node: def __init__(self,value): self.value = value self.next = None ''' Add Two Numbers You are given two non-empty linked lists representing two non-negative digits are stored in reverse order and each of their nodes contain a single digit. Add the integers. The two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ''' list1 = node(2) list1.next = node(4) list1.next.next = node(3) list2 = node(5) list2.next = node(6) list2.next.next = node(4) def addNode(list1,list2): temp = 0 outNode = node(0) out = outNode while True: if list1 == None and list2 == None: return out elif list1 != None and list2 != None: outNode.value = (list1.value+list2.value+temp)%10 temp = (list1.value+list2.value+temp)//10 elif list1 != None: outNode.value = (list1.value+temp)%10 temp = (list1.value+temp)//10 elif list2 != None: outNode.value = (list2.value+temp)%10 temp = (list2.value+temp)//10 list1 = list1.next list2 = list2.next if list1 != None or list2 != None: outNode.next = node(0) outNode = outNode.next def printNode(head): counter = 1 while True: if head == None: return if counter == 1: print(head.value,end="") else: print(" -> ",head.value,end="") head = head.next counter += 1 # out = addNode(list1,list2) # printNode(out) ################################################################################################################################### ''' Write a program to find the node at which the intersection of two singly linked lists begins. ''' sll2 = node(3) sll2.next = node(2) sll2.next.next = node(4) sll1 = node(0) sll1.next = node(9) sll1.next.next = node(1) sll1.next.next.next = sll2.next def node(head): nodes = [] currentNode = head while True: if currentNode == None: return nodes nodes.append(currentNode) currentNode = currentNode.next def intersection(head1,head2): nodeList1 = node(head1) nodeList2 = node(head2) start1 = len(nodeList1) start2 = len(nodeList2) while start1 > 0 and start2 > 0: if nodeList1[start1-1] != nodeList2[start2-1]: return nodeList2[start2].value start1 -= 1 start2 -= 1 # print(intersection(sll1,sll2)) ################################################################################################################################### ''' Find Peak Element A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. ''' def peakfinder(start,end,arr): mid = start + (end - start)//2 if arr[mid] > arr[mid -1] and arr[mid] > arr[mid+1]: return arr[mid] elif arr[mid] > arr[mid -1] and arr[mid] < arr[mid+1]: return peakfinder(mid,end,arr) elif arr[mid] < arr[mid -1] and arr[mid] > arr[mid+1]: return peakfinder(start,mid,arr) nums = [1,2,3,1] # print(peakfinder(0,len(nums)-1,nums)) ################################################################################################################################### ''' Merge Intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. ''' def isinterval(intrvl1,intrvl2): if intrvl1[0] <= intrvl2[0] and intrvl2[0] <= intrvl1[1]: return True elif intrvl1[0] <= intrvl2[1] and intrvl2[1] <= intrvl1[1]: return True else: return False def merge(intrvl1,intrvl2): if intrvl1[0] <= intrvl2[0] and intrvl2[0] <= intrvl1[1]: return [intrvl1[0],intrvl2[1]] elif intrvl1[0] <= intrvl2[1] and intrvl2[1] <= intrvl1[1]: return [intrvl2[0],intrvl1[1]] def mergeinterval(array): out = [] def remove(index): stack = [] current = len(array) while current > index: stack.append(array.pop()) current -= 1 ret = stack.pop() while len(stack) > 0: array.append(stack.pop()) return ret temp = 0 pointer = 0 while len(array) > 0: if temp == 0: temp = remove(0) if pointer == len(array): out.append(temp) temp = remove(0) pointer = 0 if len(array) != 0 and isinterval(temp,array[pointer]): temp = merge(temp,array[pointer]) remove(pointer) pointer += 1 if len(array) == 0: out.append(temp) return out # ip = [[1,3],[2,6],[8,10],[15,18]] # print(mergeinterval(ip))
cf1c5c63a9b04b7f1cb51c0232acbac58f561e8e
DamonZCR/PythonStu
/47Tkinter/Toplevel顶级窗口/26-Toplevel顶级窗口.py
522
3.578125
4
from tkinter import * """Toplevel (顶级窗口)组件类似于Frame组件,但Toplevel组件是一个独立的顶级窗口, 这种窗口通常拥有标题栏、边框等部件。 何时使用Toplevel组件? Toplevel组件通常用在显示额外的窗口、对话框和其他弹出窗口上。""" root = Tk() def create(): top = Toplevel() top.title("Damon") msg = Message(top, text="现在是晚上23点39分!") msg.pack() Button(root, text="创建顶级窗", command=create).pack() mainloop()
4499f609e08b7ee993b16db444e47f252b2d1ec9
gitlearn212/My-Python-Lab
/Aac/cross_numbers.py
271
4.09375
4
num = input(" Enter an odd length number: ") length = (len(num)) for row in range(length): for col in range(length): if row==col or row+col ==length-1: print(num[row], end=" ") else: print(" ", end=" ") print(" ")
c866b83580f5f775e9a24b9f9fec288600365e7e
bayanijulian/robot-arm-path-analyzer
/transform.py
9,030
3.515625
4
# transform.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Created by Jongdeog Lee (jlee700@illinois.edu) on 09/12/2018 """ This file contains the transform function that converts the robot arm map to the maze. """ import copy from arm import Arm from maze import Maze from search import * from geometry import * from const import * from util import * def transformToMaze(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ if(arm.getNumArmLinks() == 3): return transformToMazeFor3Arms(arm, goals, obstacles, window, granularity) if(arm.getNumArmLinks() == 1): return transformToMazeFor1Arm(arm, goals, obstacles, window, granularity) alphaLimits, betaLimits = arm.getArmLimit() alphaMin, alphaMax = alphaLimits betaMin, betaMax = betaLimits rows = int(((alphaMax - alphaMin) / granularity) + 1) cols = int(((betaMax - betaMin) / granularity) + 1) startAngles = arm.getArmAngle() map = [] # subtracts one because it will just add one in first loop alpha = alphaMin - granularity for x in range(rows): # all alpha values row = [] alpha += granularity # subtracts one because it will just add one in first loop beta = betaMin - granularity for y in range(cols): # all beta values at the current alpha beta += granularity arm.setArmAngle((alpha, beta)) armPos = arm.getArmPos() armEnd = arm.getEnd() isWallFirstArm = doesArmTouchObstacles([armPos[0]], obstacles) or not isArmWithinWindow([armPos[0]], window) if(isWallFirstArm): for y in range(cols): row.append(WALL_CHAR) map.append(row) break isWall = doesArmTouchObstacles(armPos, obstacles) or not isArmWithinWindow(armPos, window) if isWall: row.append(WALL_CHAR) continue doesGoThrough = not doesArmTouchGoals(armEnd, goals) and doesArmTouchObstacles(armPos, goals) if doesGoThrough: row.append(WALL_CHAR) continue isObjective = doesArmTouchGoals(armEnd, goals) if isObjective: row.append(OBJECTIVE_CHAR) continue # not objective or wall then free space row.append(SPACE_CHAR) map.append(row) # transforms start angles to index in maze startIndexes = angleToIdx(startAngles, (alphaMin, betaMin), granularity) startAlpha, startBeta = startIndexes # adds start to maze map[startAlpha][startBeta] = START_CHAR maze = Maze(map, (alphaMin, betaMin), granularity) return maze def transformToMazeFor3Arms(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ alphaLimits, betaLimits, gammaLimits = arm.getArmLimit() alphaMin, alphaMax = alphaLimits betaMin, betaMax = betaLimits gammaMin, gammaMax = gammaLimits rows = int(((alphaMax - alphaMin) / granularity) + 1) cols = int(((betaMax - betaMin) / granularity) + 1) depths = int(((gammaMax - gammaMin) / granularity) + 1) startAngles = arm.getArmAngle() map = [] # subtracts one because it will just add one in first loop alpha = alphaMin - granularity for x in range(rows): # all alpha values row = [] alpha += granularity # subtracts one because it will just add one in first loop arm.setArmAngle((alpha, betaMin, gammaMin)) armPos = arm.getArmPos() isWallFirstArm = doesArmTouchObstacles([armPos[0]], obstacles) or not isArmWithinWindow([armPos[0]], window) if(isWallFirstArm): depth = [] for y in range(cols): for z in range(depths): depth.append(WALL_CHAR) row.append(depth) map.append(row) continue beta = betaMin - granularity for y in range(cols): # all beta values at the current alpha depth = [] beta += granularity gamma = gammaMin - granularity arm.setArmAngle((alpha, beta, gammaMin)) armPos = arm.getArmPos() isWallSecondArm = doesArmTouchObstacles([armPos[0]], obstacles) or not isArmWithinWindow([armPos[0]], window) if(isWallSecondArm): depth = [] for z in range(depths): depth.append(WALL_CHAR) row.append(depth) continue for z in range(depths): gamma += granularity arm.setArmAngle((alpha, beta, gamma)) armPos = arm.getArmPos() armEnd = arm.getEnd() isWall = doesArmTouchObstacles(armPos, obstacles) or not isArmWithinWindow(armPos, window) if isWall: depth.append(WALL_CHAR) continue doesGoThrough = not doesArmTouchGoals(armEnd, goals) and doesArmTouchObstacles(armPos, goals) if doesGoThrough: depth.append(WALL_CHAR) continue isObjective = doesArmTouchGoals(armEnd, goals) if isObjective: depth.append(OBJECTIVE_CHAR) continue # not objective or wall then free space depth.append(SPACE_CHAR) row.append(depth) map.append(row) # transforms start angles to index in maze startIndexes = angleToIdx(startAngles, (alphaMin, betaMin, gammaMin), granularity) startAlpha, startBeta, startGamma = startIndexes # adds start to maze map[startAlpha][startBeta][startGamma] = START_CHAR maze = Maze(map, (alphaMin, betaMin, gammaMin), granularity) return maze def transformToMazeFor1Arm(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ alphaLimits = arm.getArmLimit()[0] alphaMin = alphaLimits[0] alphaMax = alphaLimits[1] rows = int(((alphaMax - alphaMin) / granularity) + 1) startAngles = arm.getArmAngle() map = [] # subtracts one because it will just add one in first loop alpha = alphaMin - granularity for x in range(rows): # all alpha values alpha += granularity # subtracts one because it will just add one in first loop arm.setArmAngle((alpha,)) armPos = arm.getArmPos() armEnd = arm.getEnd() isWall = doesArmTouchObstacles(armPos, obstacles) or not isArmWithinWindow(armPos, window) if isWall: map.append(WALL_CHAR) continue doesGoThrough = not doesArmTouchGoals(armEnd, goals) and doesArmTouchObstacles(armPos, goals) if doesGoThrough: map.append(WALL_CHAR) continue isObjective = doesArmTouchGoals(armEnd, goals) if isObjective: map.append(OBJECTIVE_CHAR) continue # not objective or wall then free space map.append(SPACE_CHAR) # transforms start angles to index in maze startIndexes = angleToIdx(startAngles, (alphaMin,), granularity) startAlpha = startIndexes[0] # adds start to maze map[startAlpha] = START_CHAR maze = Maze(map, (alphaMin,), granularity) return maze
2ed9e63e724c0faf7be94505a150aa7cb4532b09
CNieves121/lps_compsci
/class_samples/4-9_classes/studentStorer.py
850
3.921875
4
class Student(object): """ Encapsulates a Student, their gpa and college app list. """ def __init__(self, name, gpa, fav_snack): self.name = name self.gpa = gpa self.fav_snack = fav_snack self.collegelist = [] def getSnack(self): return self.fav_snack class College(object): """Encapsulates a school.""" def __init__(self, name, minGPA): self.name = name self.minGPA = minGPA def acceptStudent(self, studentGPA): if studentGPA > self.minGPA: return(True) else: return(False) #code execution starts here myFirstChoice = College("Columbia", 3.95) KrystalGPA = 4.0 print("Did Krystal get in?") print(myFirstChoice.acceptStudent(KrystalGPA)) myFirstStudent = Student("Jenny", 4.0,"Carrots") print(myFirstStudent.getSnack()) mySecondStudent = Student("Kelvin", 3.0,"Takis") print(mySecondStudent.getSnack())
72abac35e521d7c612e8684c44ee2a916da36239
Surbhi-Golwalkar/Python-programming
/loop/sum of square and cube.py
207
4.03125
4
n=int(input("Enter no. upto which you want to add:")) sum=0 i=1 while(i<=n): sum = sum + (i*i) #sum= sum+(i*i*i) i = i+1 print("Sum of square of no. is",sum) #print("Sum of cube of no. is",sum)
a325618e8ac6a5b5fdd61fd45d03095b05e858ad
rohankk2/hackerrank
/Cracking the coding Interview/hashtablesicecreamparlor.py
809
3.546875
4
def whatFlavors(cost, money): index1=0 index2=0 i=0 m={} for ele in cost: try: m[ele]=m[ele]+1 except: m[ele]=1 for ele in cost: index1=ele; try: if(m[money-index1]>=1): flag=1 if(money-index1==index1): flag=0 if(m[money-index1]>1): flag=1 if(flag==1): index2=money-index1 break; except: continue index1=cost.index(index1) cost[index1]=0 index2=cost.index(index2) if(index1>index2): print(index2+1,end=' ') print(index1+1,end=' ') else: print(index1+1,end=' ') print(index2+1,end=' ') print()
d0901d4a188d77e1261d2336856ab27ae3d8df13
momado350/tow_int_sum
/tow_num_sum.py
1,272
4.1875
4
# define the function that takes an array of ints ang a target number that is sum of two ints def tow_num_sum(arr, target): # sort the array arr.sort() # we want to start from the beginning of the array and move towards the end leftindex = 0 # we also want to determine where to stop rightindex = len(arr) - 1 # start a while loop while leftindex < rightindex: # we need to get a sum of each tow ints in the array moving right from index[0] and moving left from index[-1] # define a variable that holds this sums possibleSum = arr[leftindex] + arr[rightindex] # right Here if this possibleSum == our target, we want to return possibleSum if possibleSum == target: return [arr[leftindex], arr[rightindex]] # however; if possibleSum is less than our target, we move our left index by 1 to the right elif possibleSum < target: leftindex += 1 # and if possibleSum is greater than target we move our right index by 1 to the left elif possibleSum > target: rightindex -= 1 # if any of these conditions not met, just return an ampty array return [] # test our function test1 = tow_num_sum([4, 5, 2, 0, 8, 7, 16], 13) print(test1)
9765d97890708ad90aa79dc6246f1892d91ada0f
Serikaku/Treinamento-Python
/CursoemVideo/ex010.py
134
3.921875
4
x = float(input('Digite quantos reais você possui na carteira: R$')) print('Você pode comprar US${:.2f} Dólares'.format(x / 3.27))
20513ebc3d5d15eec23a1f8c0eaf820367e1379d
VuThiThuyB/vuthithuy-labs-c4e22
/lab3/hw/Turtle_2.py
70
3.734375
4
def sum(a,b): print("Sum :",a,"+",b,"=",a+b) a = 2 b = 3 sum(a,b)
86db09f5aa57dcf34db75a1fa15439be4b746948
tectronics/bogboa
/mudlib/world/money.py
1,340
4.15625
4
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # mudlib/world/money.py # Copyright 2009 Jim Storch # Distributed under the terms of the GNU General Public License # See docs/LICENSE.TXT or http://www.gnu.org/licenses/ for details #------------------------------------------------------------------------------ #from mudlib.hardwired import COPPER_COIN #from mudlib.hardwired import SILVER_COIN #from mudlib.hardwired import GOLD_COIN ## 100 copper = 1 silver ## 10,000 copper = 100 silver = 1 gold ## In other words; 1 copper = 1 cent, 1 silver = 1 dollar, 1 gold = $100 bill SILVER = 100 GOLD = 10000 def money_str(amount): """ Given an INT value, returns a string describing the amount of gold, silver, and copper therein. Empty units are not displayed, unless they are all empty, in which case you get '0 coppers'. """ copper = int(amount % SILVER) silver = int((amount % GOLD) / SILVER) gold = int(amount / GOLD) if gold: retval = '%d gold' % gold if silver and not gold: retval = '%d silver' % silver elif silver: retval += ', %d silver' % silver if not silver and not gold: retval = '%d coppers' % copper elif copper: retval += ', %d coppers' % copper return retval
12813ddf1d5b952ef6dccf7ea7fa191f68cabb41
joeyscl/Programming_Challenges
/Sorting & Searching/largestIntervals.py
679
3.90625
4
from copy import deepcopy ''' given an array of integer pairs (as tuple or list), minimize the number of overlapping or consecutive ones. Test Input: [4, 8], [3, 5], [-1, 2], [10, 12] Test ouput: [-1, 8], [10,12] ''' def func(pairs): pairs = sorted([sorted(pair) for pair in pairs]) res = [] curr = deepcopy(pairs[0]) i = 1 start = curr[0] end = curr[1] while True: if i >= len(pairs): res.append(curr) break if end+1 >= pairs[i][0]: if end >= pairs[i][1]: pass else: curr[1] = pairs[i][1] end = pairs[i][1] else: res.append(curr) curr = deepcopy(pairs[i]) i+=1 return(res) print(func([[4, 8], [3, 5], [-1, 2], [10, 12]]))
36bedf0ccadf7af9995137290b08f5ca63db2b84
pbhuss/ProjectEuler
/problems/p037.py
624
3.5625
4
from util.factorizer import PrimeGenerator def truncations(x): s = str(x) result = set() for i in range(len(s)): result.add(int(s[:i + 1])) result.add(int(s[i:])) return result def main(): truncatable_primes = [] prime_gen = PrimeGenerator() while len(truncatable_primes) != 11: prime = next(prime_gen) if prime < 10: continue if all( t in prime_gen for t in truncations(prime) ): truncatable_primes.append(prime) return sum(truncatable_primes) if __name__ == '__main__': print(main())
f50381d5f9f18629d45de661a47ab49cd8d54312
nicander2708/NicanderChance_ITP2017_Exercise4
/exercise4.py
210
3.953125
4
def recursive(x): try: if x == 1: return 1 else: return x * recursive(x-1) except (RecursionError, TypeError): return None num = recursive(5) print(num)
463382e1bf43c844d7888fc5b2eaa1bf0bf95f24
jkcadee/A01166243_1510_labs
/Lab03/doctests.py
575
3.625
4
import doctest def base_divisor(inputted_value, divisor): """Divides the first parameter by the second. >>> base_divisor(4, 2) 2 >>> base_divisor(2, 1) 2 """ quotient = inputted_value / divisor return int(quotient) def base_remainder(divisor_remainder, modulo): """Calculates the remainder between the first parameter divided by the second >>> base_remainder(3, 5) 3 >>> base_remainder(5, 6) 5 """ remainder = divisor_remainder % modulo return remainder if __name__ == "__main__": doctest.testmod()
eb7988c142c3c3d207b2ec384d1825de474ecf87
FlintHill/SUAS-Competition
/UpdatedSyntheticDataset/SyntheticDataset2/ElementsCreator/circle.py
955
3.609375
4
from PIL import ImageDraw, Image from SyntheticDataset2.ElementsCreator import Shape class Circle(Shape): def __init__(self, radius, color): """ Initialize a Circle shape :param radius: radius in pixels :type radius: int :param color: color of shape - RGB :type color: 3-tuple ints """ super(Circle, self).__init__(color, 0) self.diameter = radius*2 self.coordinates = self.get_coordinates() def get_coordinates(self): """ :param coordinates: drawing coordinates for the shape :type coordinates: list of 2-tuple xy pixel coordinates """ return [(0,0), (self.diameter,self.diameter)] def draw(self): new_circle = Image.new('RGBA', (self.diameter,self.diameter), color=(255,255,255,0)) draw = ImageDraw.Draw(new_circle) draw.ellipse(self.coordinates, fill=self.color) return new_circle
3bdfb913f9e2620794c2c00952a190120dc803dc
tanvir362/Python
/turtle_random_walk.py
1,549
3.984375
4
import turtle as tl import random import time STEP_LENGTH = 30 tl.speed(1) tl.left(90) def walk1(): for i in range(1000): angle = random.randrange(0, 360, 45) # print(turn) # if turn == 0: # tl.forward(STEP) # elif turn == 1: # tl.left(90) # tl.forward(STEP) # elif turn == 2: # tl.backward(STEP) # else: # tl.right(90) # tl.forward(STEP) step = 'forward' if angle<=90 or angle>=270 else 'backward' turn = 'left' if angle<=90 or (angle>=180 and angle<270) else 'right' if turn == 'left': angle = angle if angle<180 else (angle-180) else: angle = (360-angle) if angle>=270 else (angle-90) if turn == 'left': tl.left(angle) else: tl.right(angle) # print(turn, step, angle) # time.sleep(0.5) if step == 'forward': tl.forward(STEP_LENGTH) else: tl.backward(STEP_LENGTH) def walk2(n=1000): x,y = 0,0 for i in range(n): # dx, dy = random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)]) dx, dy = random.choice( [ (0, 1), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 0), (-1, 1), (-1, -1) ] ) x += dx y += dy tl.goto(x*STEP_LENGTH, y*STEP_LENGTH) if __name__ == "__main__": walk1()
c9a545552cf1dd1e2b901285b4b3631979de939d
isisbinder/python_challenge
/level_5.py
334
3.546875
4
#!python3 # Level 5 import urllib from urllib import urlopen PICKLE_SOURCE = "http://www.pythonchallenge.com/pc/def/banner.p" page_source = urlopen(PICKLE_SOURCE).read() import pickle pick = pickle.loads(page_source) new_text = '' for line in pick: new_text += ''.join([char * times for char,times in line]) + '\n' print(new_text)