blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ae6e0cef502e94ad6832ed22bbad0ff674aec3d
bema97/home_work
/ch2task_14.py
443
4.1875
4
# Given a string that may or may not contain the letter of interest. Print the index location of the second occurrence of the letter f. If the string contains the letter f only once, then print -1, and if the string does not contain the letter f, then print -2. name=str(input('enter a word that have "f"')) if name.count('f') == 1: print(-1) elif name.count('f') < 1: print(-2) else: print(name.find('f', name.find('f') + 1))
true
5935b56210c63abb25a8010074d5f1c7a9f7f879
vaageeshadas/-OddOrEven-
/hello_world.py
332
4.125
4
inputNum = input("Enter an integer: \n") #Check if enter value is proper try: savedNum = int(inputNum) except ValueError: print("That's not proper!") quit() if savedNum == 2: print("That's 2!") elif savedNum == 5: print("That's 5, you silly!") elif savedNum % 2 == 1: print("Odd") else: print("Even")
false
0589679259c7fbab2e5b2564abab7c07cd3b85df
Ayush7911/Python-Rn
/ifex1.py
380
4.125
4
age=int(input('Age: ')) if age<=0: print('Invalid input for age') elif age<=1: print('Youre an infant') elif age<=12: print('Youre a kid') elif age<=19: print('You are teenager') elif age<=45: print('you are a adult') elif age<=59: print('you are middle-aged') elif age<=60: print('tou are old') elif age<=120: print('You are way too old')
false
36db0477a049a7589e2157bbb7526326cbcd3a6d
khomyakovskaya/startPython
/guess.py
1,258
4.21875
4
#Компьютер выбирает слово, сообщает количество букв, дает 5 попыток угадать #Пользователь должен угадать это слово #Компьютер отвечает да или нет, есть буква в слове или нет import random WORDS = ("словарь", "пользователь", "компьютер", "слова", "молодец") word = random.choice(WORDS) correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print("\nВ слове - ", len(correct), "букв") print("\nТы можешь 5 раз спросить меня, есть ли буква в этом слове") for a in range(5): i = input("\nКакую букву проверим?") if i in correct: print("\nТакая буква есть") else: print("\nТакой буквы в этом слове нет(") guess = input("\nКакое слово загадано?") if guess == correct: print("Верно!") else: print("Не угадал(((((")
false
53fa9315ac3f7c31d6406f382003ee6168c875be
vmchenni/PythonTest
/Module -2 Case Study-1 Assignment 10.py
415
4.15625
4
# 10.By using list comprehension, # please write a program to # print the list after removing the value 24 in [12,24,35,24,88,120,155] listOriginal = [12, 24, 35, 24, 88, 120, 155] # listOriginal.remove(24) iValueToBeRemoved = 24 # Removing value from list for x in listOriginal: if x == int(iValueToBeRemoved): listOriginal.remove(24) # Print updated List print("Updated list is ::-", listOriginal)
true
99b759cf4a902896dcfba709fb7d983782c2de47
ShahKrish/Hangman
/Hangman.py
1,358
4.1875
4
import random movie = ('iron man','captain america','thor','ant man','avengers infinity war' ,'avengers endgame','guardians of the galaxy','avengers','avengers age of ultron','spiderman') chances = 7 name=input('Whats your name?') print('Hello', name, ',', 'Time to play HANGMAN: MARVEL EDITION!') def letters(word): return list(word) guess = random.choice(movie) answer = letters(guess) char = "" length=(len(guess)) print('There are', length, 'letters in the movie you have to guess') print('You have 7 chances to guess the movie. Type in a letter you think is in the movie.') print('Once You enter the name of the entire movie the game will be over. Good Luck!') i = "" while chances > 0 and char.lower() != guess: char = input("ENTER HERE") if char.lower() == guess: print("CONGRATULATIONS, YOU WON!") elif char.lower() in guess: if answer.count(char.lower()) == 1: print('This is letter No.', answer.index(char.lower()) + 1, "of the movie") elif answer.count(char.lower()) > 1: for i in range(length): if answer[i] == char.lower(): print('This is letter No.', i+1, 'of the movie') else: chances = chances - 1 print('Try again.You have', chances, 'chances left') if chances == 0: print('SORRY, YOU LOST:(')
true
4aef6886d658e02b571f23cadac1bb9696d6001f
Jaredewilkinson/ML
/Python_Module_Mastery/io.py
562
4.15625
4
def input_output(): """ This function reads in text files line by line. 'r' = read mode. 'w' = open clear contents write. 'a' = open append to existing contents. 'rt' = open in read and text mode. 'wt' = open in write and text mode. 'rb' = open in read and binary. 'wb' = open in write and binary. """ x = str(input("Enter file path name.")) y = str(input("Enter in read argument (r,w,a). ")) f= open(x, y) for line in f: print(line.rstrip())# strips newlines from end of line.
true
fc5b9fbc28fe95d3fbf6f79100d1095f838f9574
victor-o-silva/python3-itertools
/grouper.py
977
4.15625
4
import itertools """ Given a list of values inputs and a positive integer n, write a function that splits inputs into groups of length n. For simplicity, assume that the length of the input list is divisible by n. For example, if `inputs = [1, 2, 3, 4, 5, 6]` and `n = 2`, your function should return `[(1, 2), (3, 4), (5, 6)]`. """ def naive_grouper(inputs, n): """Too much memory and time consumption.""" num_groups = len(inputs) // n return [tuple(inputs[i*n:(i+1)*n]) for i in range(num_groups)] def better_grouper(inputs, n): """Better, but discards trailing, unmatched values.""" iters = [iter(inputs)] * n return zip(*iters) def final_grouper(inputs, n): iters = [iter(inputs)] * n return itertools.zip_longest(*iters, fillvalue=None) nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] print(naive_grouper(nums, 3)) print(list(better_grouper(nums, 3))) print(list(final_grouper(nums, 3)))
true
67e67bafa65ec6df2da380555cae67035b98dbac
skashika/Python-Assignment1
/Problem1.py
364
4.46875
4
# Write a Python program which prompts the user for a Celsius temperature, converts the # temperature to Fahrenheit, and prints out the converted temperature. Celsius = input('Please Enter Temperature in Degree Celsius: ') Fahrenheit = (float(Celsius) * 9/5 + 32) print('Temperature in Celsius: ', Celsius) print('Temperature in Fahrenheit: ', Fahrenheit)
true
cd747eb11d9b0af2c6c5ca4a251c59d015166f34
SBK78MC/raytrashing
/backend/RayTracing/Classes/Models/Vector.py
2,145
4.3125
4
import math import sys class Vector: """This class specifies a 3D Vector by having 3 values, the x,y and z that specify the Vector position on the 3D space""" def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def normalize(self): length = self.calcLength() if length == 0: return self return Vector(self.x/length, self.y/length, self.z/length) def getNormalizedLength(self): return self.normalize().calcLength() def calcLength(self): return math.sqrt(self.dotProduct(self)) def add(self, v): return Vector(self.x + v.x, self.y + v.y, self.z + v.z) def sub(self, v): return Vector(self.x - v.x, self.y - v.y, self.z - v.z) def multiply(self, d): v = Vector(self.x * d, self.y * d, self.z * d) return v def dotProduct(self, v): return (self.x * v.x) + (self.y * v.y) + (self.z * v.z) def crossProduct(self, v): newX = self.y * v.z - self.z * v.y newY = self.z * v.x - self.x * v.z newZ = self.x * v.y - self.y * v.x return Vector(newX, newY, newZ) def print(self): print("(", self.x, ",", self.y, ",", self.z, ")") def setX(self, x): self.x = x def setY(self, y): self.y = y def setZ(self, z): self.z = z def getX(self): return self.x def getY(self): return self.y def getZ(self): return self.z def equals(self, v): if self.x == v.getX() and self.y == v.getY() and self.z == v.getZ(): return True else: return False def getNegative(self): v = Vector(- self.x, - self.y, - self.z) return v def getInverse(self): v = Vector() if self.x == 0: v.x = sys.float_info.max else: v.x = 1/self.x if self.y == 0: v.y = sys.float_info.max else: v.y = 1 / self.y if self.z == 0: v.z = sys.float_info.max else: v.z = 1 / self.z return v
false
d4ee3de9945f53f4e169b365636404cb00afc45c
vmaddara/izdruka
/for_cikls.py
1,861
4.1875
4
#iterācija - kādas darbības atkārtota izpildīšana mainigais = [1, 2, 3] for elements in mainigais: print(elements) #darbības, kas jāveic #drukā list elementus myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for sk in myList: print(sk) for _ in myList: print("Sveiki!") #var nerakstīt cikla mainīgā nosaukumu #izdrukā tikai pāra skaitļus for sk in myList: if sk % 2 == 0: print(sk) else: print(f"{sk} ir nepāra skaitlis") #-------------------- #SUMMAS APRĒĶINĀŠANA #-------------------- myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] summa = 0 for sk in myList: summa = summa + sk print(f"Pēc {sk} skaitļu saskaitīšanas ir {summa}") print(summa) #drukā ar tekstu myString = "Sveika, pasaule!" for burts in myString: print(burts) for burts in "programma": print(burts, end=" ") #drukā tuple tup = (1, 2, 3, 4) for elements in tup: print(elements) myList = [(1, 2), (3, 4), (5, 6), (7, 8)] #packed tuple print(len(myList)) for elements in myList: print(elements) for (a,b) in myList: #atpako tuple print(a) for viens,otrs in myList: #var nelikt iekavas print(viens) print(otrs) myList=[(1,2,3),(4,5,6),(7,8,9)] for a,b,c in myList: print(b) #vārdnīcas d = {"k1":11, "k2":12, "k3":13} for elements in d: print(elements) #izdrukā tikai atslēgas for elements in d.items(): print(elements) #drukā pārus for key,vertiba in d.items(): print(vertiba) #ar skaitļiem izmanto funciju range() for skaitlis in range(15): #izdrukā visus skaitļus no [0:15) print(skaitlis) for skaitlis in range(5, 15):#izdrukā visus skaitļus no [5:15) print(skaitlis) for skaitlis in range(5,15,2):#izdrukā visus skaitļus no [5:15) ar soli 2 print(skaitlis) N=int(input("Ievadi skaitli: ")) for sk in range(1, N+1): print(sk)
false
d4d47c780209a8849c94f33549dc45b30ed69075
sashulkin/DS_2
/3.lists.py
2,514
4.46875
4
# **** Списки (lists) **** # создание пустого списка my_list = [] my_list_2 = list() # метод append my_list.append(100) my_list.append(200) my_list.append("hello") my_list.append([1,2,3]) # создание заполненного списка my_list = [10, 20, 30, 40, "A", 3.14, True] s = "Привет, Мир!" list_1 = list(s) # *** функция range() *** numbers = list(range(10) ) # создается набор чисел от 0 до 10 не включительно numbers = list(range(2, 10) ) # создается набор чисел от 2 до 10 не включительно numbers = list(range(2, 10, 2) ) # создается набор чисел от 2 до 10 не включительно с шагом 2 numbers = list(range(10, 1, -1) ) # создается набор чисел от 2 до 10 не включительно с шагом -1 # *** методы списков *** a = [10,20,30,40,30,30,50] # шпаргалка: объект.название метода => a.insert #добавление элемента по индексу a.insert(0, "A") # удаление элемента по значению # a.remove(30) # очистка списка # print(a) # a.clear() # print(a) # сортировка списка b = [8,4,1,6,8,34,2,5,2,35] # b.sort() # в сторону возрастания b.sort(reverse=True) # в сторону убывания # обращения к элементам c = [1, 2, 3, 4, 5] # # print(c[0]) # извлечение (чтение) значения элемента # del c[1] #удаление элемента по индексу # c[3] = 10 # print(c) # print(len(c)) # длина # c[-1] = 10 # замена значения элемента через обратный индекс # *** срезы (slice) *** c = c + [6,7,8,9,10,11] c_slice = c[0:3] # срез с 0 индекса по 3 индекс не включительно c_slice = c[:3] # срез с 0 индекса по 3 индекс не включительно c_slice = c[1:4] # срез с 1 индекса по 4 индекс не включительно c_slice = c[1:8:2] # срез с 1 индекса по 4 индекс не включительно c_slice = c[::2] # срез всего списка с шагом 2 c_slice = c[::-1] # поворот списка c_slice = c[-1:-4:-1] # срез списка в обратном направлении print(c_slice)
false
9a579e97314cc588fe36eca69927e90bf3adf8a8
MollyDepew/Python-Assignments-
/mpg.py
2,878
4.1875
4
#Molly Depew #CS21 #Assignment 11 ex 1 #pg 562 #3 #write a GUI program that allows the user to input miles and gallons #when calculate mpg button pressed should display mpg import tkinter class MPGGUI: def __init__(self): # Create the main window. self.main_window = tkinter.Tk() # Frames self.gas_held = tkinter.Frame(self.main_window) self.mile_tank = tkinter.Frame(self.main_window) self.mpg = tkinter.Frame(self.main_window) self.bottom = tkinter.Frame(self.main_window) # widget for gas held self.label_gas = tkinter.Label(self.gas_held, \ text='Enter the number of gallons:') self.gas_entry = tkinter.Entry(self.gas_held, width=10) # Pack the gas held self.label_gas.pack(side='left') self.gas_entry.pack(side='left') # Create the widgets for miles traveled. self.label_miles = tkinter.Label(self.mile_tank, \ text='Enter the number of miles:') self.miles_entry = tkinter.Entry(self.mile_tank, width=10) #pack self.label_miles.pack(side='left') self.miles_entry.pack(side='left') #create label for answer self.label = tkinter.Label(self.mpg,\ text='mpg:') self.value = tkinter.StringVar() #string variable self.mpg_label = tkinter.Label(self.mpg,\ textvariable=self.value) self.label.pack(side='left') self.mpg_label.pack(side='left') # Create the buttons self.calc_button = tkinter.Button(self.bottom, \ text='Convert', \ command=self.convert) self.quit_button = tkinter.Button(self.bottom, \ text='Quit', \ command=self.main_window.destroy) self.calc_button.pack(side='left') self.quit_button.pack(side='left') # Pack the frames. self.gas_held.pack() self.mile_tank.pack() self.mpg.pack() self.bottom.pack() # Enter the tkinter main loop. tkinter.mainloop() # The convert method is a callback function for # the Calculate button. def convert(self): # Get the value entered by the user into the # gas held widget gas = float(self.gas_entry.get()) miles = float(self.miles_entry.get()) # Convert to mpg mpg = miles/gas # store it in our string variable self.value.set(mpg) # Create an instance of this class mpg_found = MPGGUI()
true
3fe1b8aaab9595f675b2b91f2d8f0ccc830a1e55
markku63/mooc-tira-s20
/Viikko_4/fliplist.py
944
4.15625
4
from collections import deque class FlipList: def __init__(self): self.__list = deque() self.__forward = True def push_last(self,x): if self.__forward: self.__list.append(x) else: self.__list.appendleft(x) def push_first(self,x): if self.__forward: self.__list.appendleft(x) else: self.__list.append(x) def pop_last(self): if self.__forward: return self.__list.pop() else: return self.__list.popleft() def pop_first(self): if self.__forward: return self.__list.popleft() else: return self.__list.pop() def flip(self): self.__forward = not self.__forward if __name__ == "__main__": f = FlipList() f.push_last(1) f.push_last(2) f.push_last(3) print(f.pop_first()) # 1 f.flip() print(f.pop_first()) # 3
false
168c9a8b68e0aa35c5fe94cc4da50811a3ded337
Viccari073/exercises_collections
/exer_colecoes_02.py
287
4.1875
4
""" Crie um programa que lê 6 valores inteiros e, em seguida, mostre os valores lidos. """ lista_valores = list() for n in range(1, 6 + 1): valor = int(input(f'Digite o {n}º valor: ')) lista_valores.append(valor) print(f'Os valores lidos foram: {lista_valores}')
false
9ede4fd0a4cad84d215034d1a3d28be9db72d226
sunsx512/csdn-python-study
/day7/day7.py
2,700
4.21875
4
#注释 #打印圆的周长 import math r=10 print(2*math.pi*r) ''' 1、单行注释(行注释) Python中使用#表示单行注释。单行注释可以作为单独的一行放在被注释代码行之上,也可以放在语句或表达式之后。 # 这是单行注释 当单行注释作为单独的一行放在被注释代码行之上时,为了保证代码的可读性,建议在#后面添加一个空格,再添加注释内容。 当单行注释放在语句或表达式之后时,同样为了保证代码的可读性,建议注释和语句(或注释和表达式)之间至少要有两个空格。 2、多行注释(块注释) 当注释内容过多,导致一行无法显示时,就可以使用多行注释。Python中使用三个单引号或三个双引号表示多行注释。 ''' ''' 这是使用三个单引号的多行注释 ''' ''' """ 这是使用三个双引号的多行注释 """ 3、注意 注释不是越多越好。对于一目了然的代码,不需要添加注释。 对于复杂的操作,应该在操作开始前写上相应的注释。 对于不是一目了然的代码,应该在代码之后添加注释。 绝对不要描述代码。一般阅读代码的人都了解Python的语法,只是不知道代码要干什么。 4、关于代码规范 Python官方提供有一系列PEP文档,其中第8篇文档专门针对Python的代码格式给出了建议,也就是俗称的PEP 8。PEP 8文档地址。 注释部分内容工具书不够详细,此部分博文内容摘自简书: 作者:reldi 链接:https://www.jianshu.com/p/93fb41041e1a ''' #字符串 print('hello,world!!!') print("hello,world!!!") ''' 单双引号结果完全相同,既然如此,为什么要支持两种方式,因为适用以下情况 ''' str1="let's go!" print(str1) str2='"Hello world!" she said' print(str2) ''' str1,如果用同样的单引号会报错,str2同理 一定要用的话,可以用"\"转义字符来实现,如: ''' str1='let\'s go!' print(str1) str2="\"Hello world!\" she said" print(str2) # 字符串拼接 # “+”实现 str1="let's go! "+'say ' str2='"Hello world!" she said' print(str1+str2) # \n代表换行符 # str函数和repr函数 strx='"Hello world!" she said' # 当字符串中含有\n时,会自动换行,如: str1='"Hello world!" \nshe said' print(str1) # 我想原样输出,使用函数repr print('repr原样输出:'+repr(str1)) # 我想识别\n输出,使用函数str(即默认情况下) print('str识别输出:'+str(str1)) # P.S. 在使用str函数时,如果前面定义了str变量,会报错,不可同名。。。
false
b354476fc67e33ab0897229a62200e165cc93a3f
AnakinCNX/PythonChallenges
/challenge_8.py
208
4.125
4
# write program to change munber into grades num = int(input("Please enter score: ")) if num >= 75: print("A") elif num >= 60: print("B") elif num >= 35: print("C") elif num < 35: print("D")
false
b3f4e414846df14bb573878feb305acf31e87164
AnakinCNX/PythonChallenges
/challenge_7.py
260
4.25
4
#ask user how much tv whey watch per day tv_per_day = input("how much tv_per_day:") #if less than 2 hours your not brain ded # mind your spelling! if tv_per_day == "2": print("your brain no ded") #if not your brain ded else: print("your brain is ded")
true
727184d6f38442d67463865545e318d5816919ec
MaximeGoyette/projecteuler
/034.py
223
4.15625
4
from math import factorial def is_factorial_number(n): return n == sum([factorial(int(x)) for x in str(n)]) total = 0 i = 3 while True: if is_factorial_number(i): total += i print total i += 1
false
11ef95b18bf2e34c6b9a2bea0cd0bd0f637a634a
jackeiel/riddler
/2020_02_21/express.py
962
4.34375
4
''' On a warm, sunny day, Nick glanced at a thermometer, and noticed something quite interesting. When he toggled between the Fahrenheit and Celsius scales, the digits of the temperature — when rounded to the nearest degree — had switched. For example, this works for a temperature of 61 degrees Fahrenheit, which corresponds to a temperature of 16 degrees Celsius. However, the temperature that day was not 61 degrees Fahrenheit. What was the temperature? ''' import pandas as pd def f_to_c(temp): return round(((temp-32)*5)/9) def reverse_int(number): return int(''.join(list(reversed(str(number))))) print('Test\nF Temp is 61') print('C Temp is: ', f_to_c(61)) print('F Temp is reversed C Temp-->', 61 == reverse_int(f_to_c(61))) print('\n') df = pd.DataFrame({'f_temp':range(32,400)}) df['c_temp'] = df.f_temp.apply(f_to_c) df['reverse_true'] = df.apply(lambda x: x.f_temp == reverse_int(x.c_temp), axis=1) print(df[df.reverse_true==True])
true
b180bd2e800796c149f2ae722cf4702bd6436b64
btoll/howto-algorithm
/python/string/palindrome_number.py
1,300
4.125
4
#def palindrome_number(n): # if n < 0: # return False # # k = n # ret = 0 # while k: # rem = k % 10 # ret = ret * 10 + rem # k //= 10 # return ret == n def palindrome_number(n): # As discussed above, when x < 0, x is not a palindrome. # Also if the last digit of the number is 0, in order to be a palindrome, # the first digit of the number also needs to be 0. # Only 0 satisfy this property. if n < 0 or (n % 10 == 0 and n != 0): return False ret = 0 # Now the question is, how do we know that we've reached the half of the number? # Since we divided the number by 10, and multiplied the reversed number by 10, when the original number # is less than the reversed number, it means we've processed half of the number digits. while n > ret: rem = n % 10 ret = ret * 10 + rem n //= 10 # When the length is an odd number, we can get rid of the middle digit by revertedNumber/10 # For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123, # since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it. return n == ret or n == (ret // 10) print(palindrome_number(12321))
true
da2d0841efe324817d931587d58990c969e38860
therealmaxkim/Playground
/Codesignal/Arcade - Intro/adjacent_Elements_Product/code.py
950
4.125
4
''' Questions 1. can the array be empty? Observations 1. The elements must be next to each other. That means that for each element, there are two possible products -> multiply with left or multiply with right element. 2. Because the elements must be adjacent, we can use the "window sliding technique". 3. Running from left to right with window sliding technique gives you all possible products of adjacent elements. 4. Keep a separate variable to remember the largest and compare with sum from window sliding technique. ''' def adjacentElementsProduct(inputArray): #The smallest size is two elements, default this as the largest product largestProduct = inputArray[0]*inputArray[1] #Calculate all other adjacent products and update the variable if it is bigger. for i in range(0, len(inputArray)-1): largestProduct = max(inputArray[i] * inputArray[i+1], largestProduct) return largestProduct
true
5a914a136b41bb8453f0891f830655c890216857
Srujana6188/sdet
/python/python/Activity3.py
952
4.21875
4
""" Rock beats scissors Scissors beats paper Paper beats rock """ # Get the users names user1 = input("What is player1's name? ") user2 = input("What is player2's name? ") # Get the user choices user1_ans = input(user1 + ", do you want to choose rock, paper or scissors? ").lower() user2_ans = input(user2 + ", do you want to choose rock, paper or scissors? ").lower() if user1_ans == user2_ans: print("Its a tie!") elif user1_ans == 'rock': if user2_ans == 'scissors': print("rock wins") else: print("paper wins!") elif user1_ans == 'scissors': if user2_ans == 'paper': print("Scissors win!") else: print("Rock wins!") elif user1_ans == 'paper': if user2_ans == 'rock': print("Paper wins!") else: print("Scissors win!") else: print("Invalid input! You have not entered rock, paper or scissors, try again.")
true
25fd15c02b65777b061a5611f3d3afeef1c41f84
korkeatw/pythainlp
/pythainlp/util/thai.py
1,559
4.1875
4
# -*- coding: utf-8 -*- """ Check if it is Thai text """ import string _DEFAULT_IGNORE_CHARS = string.whitespace + string.digits + string.punctuation def isthaichar(ch: str) -> bool: """ Check if a character is Thai เป็นอักษรไทยหรือไม่ :param str ch: input character :return: True or False """ ch_val = ord(ch) if ch_val >= 3584 and ch_val <= 3711: return True return False def isthai(word: str, ignore_chars: str = ".") -> bool: """ Check if all character is Thai เป็นคำที่มีแต่อักษรไทยหรือไม่ :param str word: input text :param str ignore_chars: characters to be ignored (i.e. will be considered as Thai) :return: True or False """ if not ignore_chars: ignore_chars = "" for ch in word: if ch not in ignore_chars and not isthaichar(ch): return False return True def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float: """ :param str text: input text :return: float, proportion of characters in the text that is Thai character """ if not text or not isinstance(text, str): return 0 if not ignore_chars: ignore_chars = "" num_thai = 0 num_ignore = 0 for ch in text: if ch in ignore_chars: num_ignore += 1 elif isthaichar(ch): num_thai += 1 num_count = len(text) - num_ignore return (num_thai / num_count) * 100
false
6e068fb4489a5e268d473227eca95d5d64cf0c91
oopsiamgopi/algorithm
/selection_sort.py
679
4.15625
4
import sys def selection_sort_practice(source_list): source_length = len(source_list) for i in range(source_length): minimum = i for j in range(i+1, source_length): if source_list[j] < source_list[minimum]: minimum = j source_list[i],source_list[minimum] = source_list[minimum],source_list[i] return source_list if __name__== "__main__": number_of_element = int(input("Enter List Size:")) source_list = [] for i in range(int(number_of_element)): source_list.append(int(input("Enter %s Element Value:" % str(i+1)))) print("Output Index: %s" % selection_sort_practice(source_list))
true
1f22bb69a3429a40fd28eee9c81e734cf354c122
BrandonSersion/fibonacci-sequence-with-and-without-recursion
/fibonacci.py
556
4.28125
4
"""Fibonacci sequence - with and without recursion.""" def with_recursion(num1, num2, limit=1000000): print(num1, end=' ') num1, num2 = num2, num1 + num2 if num1 < limit: with_recursion(num1, num2, limit) def without_recursion(num1, num2, limit=1000000): while num1 < limit: yield num1 num1, num2 = num2, num1 + num2 def main(): print('With recursion:') with_recursion(0, 1, 200) print() print('Without recursion:') print(*without_recursion(0, 1, 200)) if __name__ == "__main__": main()
true
6cabc4b44a120605b33e263f10addef0e3f32299
Sravanthi-cb/Crypto
/helpers.py
1,069
4.3125
4
""" Utility methods to help in encryption. """ lowerLetters = 'abcdefghijklmnopqrstuvwxyz' upperLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def alphabet_position(char): """ Return the alphabet position. Returns -1 for all invalid input. """ if type(char) != type(''): return -1 if len(char) != 1: return -1 if char.isalpha(): return lowerLetters.find(char.lower()) return -1 def rotate_character(char, rot): """ Return the character shifted by rot amount. char must be a single character and rot must be a positive integer. char is returned AS IS if any errors, including if it is not a character """ if type(char) != type(''): return char if type(rot) != type(1): return char if len(char) != 1: return char if not char.isalpha(): return char letters = lowerLetters if char.isupper(): letters = upperLetters pos = letters.find(char) pos += rot pos = pos % 26 return letters[pos]
true
081be97b97a18907e791ac14f6fa059e85244872
sucrete/web-ceasar
/ceasarporweb.py
977
4.15625
4
def encrypt(text, rot): slate = "" for corrida in text: if corrida.isalpha(): slate += rotate_character(corrida, rot) else: slate += corrida return slate def rotate_character(char, rot): """Returns a one-letter string rot number of places to the right of char""" alphabet = "abcdefghijklmnopqrstuvwxyz" UPPERS = alphabet.upper() pos = alphabet_position(char) where_to = pos + rot if where_to >= 26: if char.isupper(): return UPPERS[where_to % 26] else: return alphabet[where_to % 26] else: if char.isupper(): return UPPERS[where_to] else: return alphabet[where_to] def alphabet_position(letter): alphabet = "abcdefghijklmnopqrstuvwxyz" UPPERS = alphabet.upper() """Finds the position of a letter in the alphabet""" ensmallened_letter = letter.lower() return alphabet.index(ensmallened_letter)
true
9074c9929aa9b0c30b8c4ceab345c9f15496c17f
tejamupparaju/LeetCode_Python
/leet_code274.py
2,219
4.21875
4
""" 274. H-Index Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of hindex on Wikipedia"A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. Hint: An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. Hide Company Tags Bloomberg Google Facebook Show Tags Show Similar Problems """ # Looked up solution ''' Solution: It is easy to solve if we sort the array, But there is O(n) solution The max H-index can go is n (where n is the length of the citation array) So we create a temp array (Index of this array specify H-index) and if any citation is greater than n we increment temp_arry[n] else we increment the temp_array[i] where i is the current iterating index. Now we read the array from the backwards and at any point of the count of papers increase by index we return https://discuss.leetcode.com/topic/40765/java-bucket-sort-o-n-solution-with-detail-explanation/2 ''' class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ n = len(citations) result_arr = [0]*(n+1) for i in range(n): if citations[i] >= n: result_arr[n] += 1 else: result_arr[citations[i]] += 1 i, result = n, 0 while i > 0: result += result_arr[i] if result >= i: return i else: i -= 1 return 0
true
67f83726ce2904bb5b6435facc7195b5cff3d16a
tejamupparaju/LeetCode_Python
/leet_code53.py
1,148
4.21875
4
""" 53. Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. click to show more practice. Hide Company Tags LinkedIn Bloomberg Microsoft Hide Tags Array Dynamic Programming Divide and Conquer Show Similar Problems """ # MOWN solution class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return None #max_sum_list = [nums[0]] maxer = nums[0] #temp_max_list = [nums[0]] temp_sum = nums[0] for i in range(1, len(nums)): if nums[i] + temp_sum < nums[i]: #temp_max_list = [nums[i]] temp_sum = nums[i] else: #temp_max_list.append(nums[i]) temp_sum += nums[i] if temp_sum > maxer: maxer = temp_sum #max_sum_list = temp_max_list[:] #print max_sum_list return maxer
true
f9eb6b32b10b1f3d77a5806c8251ef0b2dd458ac
tejamupparaju/LeetCode_Python
/leet_code739.py
1,291
4.15625
4
""" 739. Daily Temperatures Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. Companies Google """ # MOWN solution after doing Next Greater num # Iterate through the nums list, Use stack to save all the descending sub sequence of numbers from nums # everytime you hit higher number, that will the greatest number for the nums in stack that are, # less than the number (so we pop all of them out class Solution(object): def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ stack, result = list(), [0] * len(temperatures) for idx, temp in enumerate(temperatures): while stack and stack[-1][-1] < temp: tidx, ttemp = stack.pop() result[tidx] = idx - tidx stack.append([idx, temp]) return result
true
0f0dd8899dfa0f2e91b7e8d494fee65330a68671
tejamupparaju/LeetCode_Python
/leet_code36.py
1,151
4.125
4
""" 36. Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. """ # LUP # Save everything to set, for each element we save # row(value) # (value)col # row_quad(value)(col_quad) class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ exists = set() for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == ".": continue tstr = "(%s)" % board[i][j] if (str(i) + tstr) in exists or (tstr + str(j)) in exists or (str(i / 3) + tstr + str(j / 3)) in exists: return False exists.add(str(i) + tstr) exists.add(tstr + str(j)) exists.add(str(i / 3) + tstr + str(j / 3)) return True
true
fc6f58e4411338e061e0a92ac93ec646b98c9836
tejamupparaju/LeetCode_Python
/leet_code836.py
1,232
4.125
4
""" A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two rectangles, return whether they overlap. Example 1: Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] Output: true Example 2: Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] Output: false Notes: Both rectangles rec1 and rec2 are lists of 4 integers. All coordinates in rectangles will be between -10^9 and 10^9. """ # MOWN solution # check if x axes intersect or y axes intersect class Solution(object): def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ x1, y1 = [rec1[0], rec1[2]], [rec1[1], rec1[3]] x2, y2 = [rec2[0], rec2[2]], [rec2[1], rec2[3]] if ((x2[0] < x1[1] and x2[1] > x1[0]) and (y2[0] < y1[1] and y2[1] > y1[0])) or ( (x1[0] < x2[1] and x1[1] > x2[0]) and (y1[0] < y2[1] and y1[1] > y2[0])): return True return False
true
280ae9a797213c0ada31aa50fbaac04e60e1b553
jstocks/armstrong_number
/armstrong.py
2,208
4.125
4
# Jeffrey Stockman # This program will output a list of Armstrong numbers and a total count based # on user input. Only integer input is allowed in the range of [10-100,000,000]; # else an error and re-prompt will appear. # Extra Credit attempted for non-integer input. # BigO notation is O(N log(N)); The calculate_armstrong is O(1) for digit_count # and sum, and O(logN) for power; iterating over a range of numbers is O(N). # Time spent programming = 12 hours. # No bugs detected. # function verifies 1) an integer is entered and 2) range between 10 and # 100,000,000; re-prompt if invalid input def verify_int(): user_input = input('Please enter an integer from 10 through 100,000,000 ' '(without the commas):') try: user_num = int(user_input) except ValueError: print('You entered a non-integer value. Please try again.') return (verify_int()) if user_num < 10: print('Your integer must be 10 or more.') return (verify_int()) if user_num > 100000000: print('Your integer must be less than 100,000,000:') return (verify_int()) else: return (user_num) # function calculates and prints Armstrong Numbers from a list, prints a count. def calculate_armstrong(): total_count = 0 for x in num_list: # count number of digits in integer digit = int(x) digit_count = 0 while digit > 0: digit_count += 1 digit = digit // 10 # powers each digit by digit count, sums total string = str(x) sum = 0 for y in string: sum += int(y)**digit_count # compare sum to integer if sum == x: print(x) total_count += 1 print('\nThe total number of Armstrong numbers found was', total_count) # initial prompt print('Welcome to the Armstrong number calculator.') user_input = verify_int() # create list of integers based on user input num_list = [] start, end = 10, user_input + 1 num_list.extend(range(start, end)) print('\nThe Armstrong numbers from 10 through 100000000 are:\n') calculate_armstrong()
true
3f923dac7ba8928c0f30ef13236a787d31730d02
diganthdr/python_august_bootcamp
/count_coins.py
673
4.1875
4
coins = [2,1,5,2,1,1,2,2,1,1,5] def count_coins(coins): ''' this function calculates sum of coins. coins are in list v2.3: fixed bug in counting new coins ''' #comment sum = 0 for coin in coins: #coin is a varialbe, you can use any name like 'for x in coins' is also fine. #iterator --> finger. for(i = 0, i< len(coins); i++) print(coin) sum = sum + coin print(sum) return sum count_coins(coins) # def loop_example(): # coins = [2,1] # sum = 0 # for coin in coins: # sum = sum + coin # print(sum) # import dis # print(dis.dis(loop_example))
true
44e4c0ff011d32dd6dc09d3c16c1de0d85c78098
genocem/Exercices
/exercices/partie 2 exercice 3.py
205
4.125
4
x= int(input("entrer un nembre:")) if x==0 or x==1: print("carré") for i in range(1,x): if x/i==i: print("carré") break if i==x-1: print ("n'est pas carré")
false
1cdf806358e49f4bfb273a9ebaec5b87a2472c11
1131057908/yuke
/7-23/异常捕获的练习.py
2,333
4.125
4
""" 座右铭:吃饱不饿,努力学习 @project:预科 @author:Mr.Huang @file:异常捕获的练习.PY @ide:PyCharm @time:2018-07-24 08:54:21 """ #模板: # try: # # 捕获异常的代码 # except Exception as e:#捕获异常原因并传递给e # # else: # # # # # try: # #写要捕获的异常代码 # pass # except Exception as e: # # Exceeption :异常类,基本上能捕获常见的异常的情况,表示异常原因 # # e 用于接受错误的原因 # pass # # 出现异常时,需要设置的代码逻辑 # #当try 代码执行成功的时候,则不会执行except Exception as e里面的代码 # else : # pass # #如果try里面的代码执行成功,则紧接著会执行else中代码,try不成功执行则不会执行else里面代码 # finally: # pass # #不管try执行成功还是失败,最终都会执行finally语句里面的代码 # # example # list1=[1] # print(list1[0]) # try: # print(list1[0]) # except Exception as e : # print('try里面的代码没有执行成功,则会执行我') # else: # print('try里面代码执行成功,则会执行我') # finally: # print('无论怎样我都执行') # #能输出错误原因 # try: # print(list1[1]) # except IndexError as e: # print('try里面的代码出现异常没有执行成功,所以需要执行我!') # print('错误的原因error:',e) # else: # print('try里面的代码执行成功,则会接着执行我!try里面的代码没有执行成功,则不会执行我!') # finally: # print('不管try执行成功还是失败,都最终会执行我!') #在函数内部自定义一个一个异常:当调用该函数的时候,如果不符合函数内部定义的条件, # raise :抛出异常原因的关键字 def is_outrange(age): if age<16: raise Exception('小于16岁,不能谈恋爱') else: return True res=is_outrange(18) try: res=is_outrange(18) except Exception as e: print('错误原因error:',e) #面试常见问题 # IndexError:索引错误 # ImportError:导入错误 # NameError:尝试访问一个没有声明的变量 # SyntaxError:语法错误 # AttributeError:尝试访问位置的对象的属性 # KeyError:请求一个不存在的字典关键字 # ValueError:传给函数的参数类型不正确
false
e8ae6f207844162150dec23c6e2d8f2b11dce74c
1131057908/yuke
/7-23/·函数讲解.py
2,270
4.15625
4
""" 座右铭:吃饱不饿,努力学习 @project:预科 @author:Mr.Huang @file:·函数讲解.PY @ide:PyCharm @time:2018-07-23 19:13:18 """ #函数:为什么使用函数?因为没有函数的编程只是在单纯的写逻辑代码,只能够copyy一份但是使用函数可以提高代码重复使用效率,提升开发效率 #第一步:声明一个函数,在函数里面写逻辑代码 #第二步:调用函数,执行编写的逻辑代码 print('今天是周一') print('今天是周二') print('今天 是周三') #怎么声明一个函数,在函数里面写逻辑代码 #调用函数,执行编写的逻辑代码 #def 声明函数,的关键字,shuchu()函数可以自定义,()用于定义函数的参数,如果没有内容就表示该函数没有参数:下面的东西,要封装的代码逻 #声明一个无返回值,无参数的函数 def shuchu (): print('今天是周一') print('今天是周二') print('今天是周三') # 调用函数,函数名+括号 shuchu() shuchu() shuchu() #2.声明一个有返回值无参数的函数 #一个函数为什么要有返回值,因为一个函数最终的执行结果,后面的程序才能根据这个执行结果进行其他操作 # def huang(): # c=int(input('qingshuru :')) # d=int(input('请输入:')) # e=c*d # return e # res=huang() # print(res) # f=res*10 # print(f) #3.声明一个无返回值,有参数的函数 #a,b 形参 def chufa(a,b): c=a/b print(c) # return c #20,10为实际参数,实参是给a,b这两个形参赋值 a=10,b=2.5 chufa(20,10) #有返回值有参数的函数 def jian(a,b): c=a-b return c res=jian(8,5) print(res) res1=res+10 print(res1) #return关键字作用 #1用于返回函数的执行结果 #2. 用于结束当前代码的执行,使用return关键字结束代码执行的时候,return必须位于函数内部,区别于break def test(): for x in range (1,11): if x%4==0: return else: print('============',x) test() def func2(): for i in range(1,11): if i %2==0: break #到第一个符合条件的情况截至。不输出符合条件的语句,并停止 print(i) func2()
false
4fc2bc90874ec716e8093d057051205308967d38
jbm950/personal_projects
/General Python/Guessing game.py
2,561
4.375
4
#------------------------------------------------------------------------------- # Name: Guessing game.py # Purpose: This module will be a text based numeric guessing game. The player # will get 10 guesses to guess a number between 1 and 100. After each guess # the system will let the player know if their guess was too high or too low. # # Author: James # # Created: 13/01/2014 # Copyright: (c) James 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python # # Definiton of Varibles: # guess = this will be the guess by the player # n = this is the number of guess the player gets to make # correct = this is the integer that will be created at random from 1 to 100 # that the player has to guess # win = this will turn to a 1 if the player correctly guesses the number in # order to let the system know that the win condition has been met. # Import the random module so that a random integer can be created which the # player has to guess. import random # Initialize the guess count and create the random number that the player will # have to guess. Also set the win condition to 0. n = 0 correct = random.randint(1,100) win = 0 # Print to the screen the rules of the game. print('''Dear contestant, You will have a total of 10 guesses to determine the magic number. Good luck! (Hint the number lies between 1 and 100)''' ) # Start the while loop that will run the game. The loop will start by asking # for input from the player and then compare that value to the randomly created # value. If the value is not the randomly created value the system will let the # player know if the guess was high or low. If the number of guesses reaches 10 # the loop will exit and the player will have lost. while True: guess = int(input('What is your guess as to the magic number?')) if guess == correct: win = 1 break elif n == 10: break elif guess > correct: print('Your guess of %d was too high' % guess) elif guess < correct: print('Your guess of %d was too low' % guess) n = n + 1 # Now check the win condition. If it has been met display the congratulations # and if now display the loss message. if win == 1: print('Congratulations you guessed the magic number %d' % correct) elif win == 0: print("I'm sorry you have ran out of guesses. The magic number was %d" % correct)
true
e78700dd4d02eb9788498aebb1258dba7d47b02e
DSAL0630/ALL
/practice2.py
273
4.21875
4
Num = input("Number 1: ") Num2 = input("Number 2: ") Num = int(Num) Num2 = int(Num2) print(Num + "+" + Num2 + "=" str(Num + Num2) print(Num - "-" - Num2 - "=" str(Num - Num2) print(Num * "*" * Num2 * "=" str(Num * Num2) print(Num / "/" / Num2 / "=" str(Num / Num2)
false
004f9745290cd4a3955e704525823cbf7e7fbe18
Swathygsb/DataStructuresandAlgorithmsInPython
/DataStructuresandAlgorithmsInPython/com/kranthi/Algorithms/challenges/jumpingOnTheClounds.py
2,042
4.3125
4
""" Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud. It is always possible to win the game. For each game, Emma will get an array of clouds numbered if they are safe or if they must be avoided. For example, indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes and . She could follow the following two paths: or . The first path takes jumps while the second takes . Function Description Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer. jumpingOnClouds has the following parameter(s): c: an array of binary integers Input Format The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds where . Constraints Output Format Print the minimum number of jumps needed to win the game. Sample Input 0 7 0 0 1 0 0 1 0 Sample Output 0 4 Explanation 0: Emma must avoid and . She can win the game with a minimum of jumps: Sample Input 1 6 0 0 0 0 1 0 Sample Output 1 3 """ # !/bin/python3 import os # Complete the jumpingOnClouds function below. def jumpingOnClouds(count): min_jumps = 0 i = 0 while i + 2 < len(count): if count[i + 2] == 1: i += 1 min_jumps += 1 else: i += 2 min_jumps += 1 if i < len(count) - 1: min_jumps += 1 return min_jumps if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c) fptr.write(str(result) + '\n') fptr.close()
true
059c4216429ddce5de7256291ba2c7a372225fb0
Swathygsb/DataStructuresandAlgorithmsInPython
/DataStructuresandAlgorithmsInPython/com/kranthi/Algorithms/challenges/medium/findElemInSortedAndRotated.py
2,009
4.1875
4
""" There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3: Input: nums = [1], target = 0 Output: -1 """ # Search an element in sorted and rotated array using # single pass of Binary Search def simpleBinarySearch(arr, l, r, key): if l > r: return -1 mid = (l + r) // 2 if arr[mid] == key: return mid if arr[mid] < key: return search(arr, mid + 1, r, key) return search(arr, l, mid - 1, key) def search(arr, l, r, key): if l > r: return -1 mid = (l + r) // 2 if arr[mid] == key: return mid # if arr[l,,mid] is sorted if arr[l] <= arr[mid]: # As this subarray is sorted, we can quickly # check if key lies in half or other half if arr[l] <= key <= arr[mid]: return search(arr, l, mid - 1, key) return search(arr, mid + 1, r, key) # If arr[l..mid] is not sorted, then arr[mid... r] # must be sorted if arr[mid] <= key <= arr[r]: return search(arr, mid + 1, r, key) return search(arr, l, mid - 1, key) # Driver program arr = [4, 5, 6, 7, 8, 9, 1, 2, 3] key = 1 i = search(arr, 0, len(arr) - 1, key) if i != -1: print("Index: % d" % i) else: print("Key not found") arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(f"Index: {simpleBinarySearch(arr, 0, len(arr) - 1, 6)}")
true
d916f7bb1d5a713befd25a4d78c487c19c746abf
Bingohong/Data_Structure_Pyhon
/算法刷题/20171212-面试题刷题/二叉树镜像.py
912
4.15625
4
'''问题描述:二叉树的镜像''' '''问题分析: 1)先序遍历 2)如果二叉树为空,返回节点 3)如果二叉树非空,交换左右子树节点 4)递归左子树、右子树 ''' class binaryTree(object): """docstring for binaryTree""" def __init__(self, value, left, right): self.value = value self.left = left self.right = right def mirrorTree(root): if root == None: return root root.left, root.right = root.right, root.left mirrorTree(root.left) mirrorTree(root.right) return root # 测试用例 root = binaryTree(1, None, None) left = binaryTree(2, None, None) right = binaryTree(3, None, None) root.left = left root.right = right lleft = binaryTree(4, None, None) lright = binaryTree(5, None, None) rleft = binaryTree(6, None, None) rright = binaryTree(7, None, None) left.left = lleft left.right = lright right.left = rleft right.right = rright mirrorTree(root)
false
d69939cf8ed5c1fe49f73b41f5e26fcebfb2d1e5
AndrePina/Python-Course-Work
/list of filenames 2.py
1,680
4.5
4
# Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension. # return [x for x in range(0, n + 1) if x % 2 != 0] # words = sentence.split(".") # x = "ain" in txt # print(x) # txt = "The rain in Spain" # x = re.search("^The.*Spain$", txt) # if x: # print("YES! We have a match!") # else: # print("No match") import re filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] def reName(filenames): newNames = [] words2 = "" words3 = "" for x in range(len(filenames)-1): words = filenames #words = str(filenames) #words = words.split(".") #words = str(words).split(",") #words = str(words).strip("[") #print("stripped: " + words[x]) #print(len(words)) #print("This is words[x] value: " +str(words[x])) if words[x].endswith(".hpp"): #words = str(words).split(",") #words = str(words).split(",") words2 = str(words).replace(".hpp", ".h") #print(words2) #print("-------This is the hpp word: " +str(words[x])) #newNames.append(words) else: #newNames.append(words) #print("newNames = " + str(newNames)) words3 = str(words) #print(words3) #x = x + 1 newNames = words2 return newNames# Generate newfilenames as a list containing the new filenames # using as many lines of code as your chosen method requires. #___ # Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"] print(reName(filenames))
true
d67e2c2f6e9488a93de5523178884333db604c69
AndrePina/Python-Course-Work
/convert decimal.py
262
4.4375
4
# Python program to convert decimal into other number systems dec = 5 print("The decimal value of", dec, "is:") # print(bin(dec), "in binary.") print(oct(dec), "in octal.") # print(hex(dec), "in hexadecimal.") print(int('5', 8), "in interger --> octal.") # 42
true
a73a33fae2796d3a28a65c857b5980a599b3448d
LuannMateus/python-exercises
/python-files/first_world-exercises/3-condições-if_and_else/exer033-qual_maior_menor.py.py
716
4.15625
4
print('=' * 55) print('<-- Which is the biggest and which is the smallest -->') print('=' * 55) n1 = float(input('Enter with ter first number: ')) n2 = float(input('Enter with ter second number: ')) n3 = float(input('Enter with ter third number: ')) # Initialization of variables; big = n1 small = n1 # Calculation the biggest number; if n2 > big and n2 > n3: big = n2 if n3 > big and n3 > n2: big = n3 # Calculation the smallest number; if n2 < small and n2 < n3: small = n2 if n3 < small and n3 < n2: small = n3 print('-' * 30) print(' Analysing....') print('-' * 30) print('- The biggest number is {:.1f}'.format(big)) print('- The smallest number is {:.1f}'.format(small)) print('-' * 30)
true
31e73d66e17a270bfca7066247d88ddbce9234ac
LuannMateus/python-exercises
/python-files/third_world-exercises/10-listas_part_2/exer88-MEGASENA.py
944
4.28125
4
'''Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.''' from typing import List from random import randint from time import sleep c = { 'white': '\033[1;37m', 'red': '\033[1;31m' } print(f'{c["white"]}-{c["red"]}==' * 15) print(f'{c["white"]} {"MEGA SENA":^40}') print(f'{c["white"]}-{c["red"]}=={c["white"]}' * 15) gues = list() # type: List n = x = 0 chose = int(input('How many games do you want me to draw: ')) print(f'{" SORTING":=>15} {chose} {"GAMES ":=<15}') for count in range(0, chose): while x < 6: n = randint(1, 60) if n not in gues: gues.append(n) x += 1 x = 0 sleep(1) print(f'Game {count + 1}: {gues}') gues.clear() print(f'{c["white"]}{" < GOOD LUCK! > ":=^30}')
false
f9700220140ae6d208c4df668c1d9f0e9ce6619f
LuannMateus/python-exercises
/python-files/third_world-exercises/14-modulos_e_pacotes/exer107/exer107-exercitando_modulos.py
648
4.34375
4
'''Exercício Python 107: Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessas funções.''' import coin print('\033[1;31m~' * 40) print(' PLAYING WITH MÓDULO'.center(40)) print('~' * 40) v = float(input('Enter with a value: ')) print(f'Value R$: {v}$') print(f'The increase value 10% will be R$: {coin.increase(v)}$') print(f'The decrease value 15% will be R$: {coin.decrease(v)}$') print(f'The double value will be R$: {coin.double(v)}$') print(f'The half value will be R$: {coin.half(v)}$') print('-=' * 20)
false
cc2a9364e28c6193e86ec12fc143f92e958294cd
LuannMateus/python-exercises
/python-files/third_world-exercises/12-functions/exer97-print_special.py
501
4.28125
4
'''Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.''' # Title; def title(): print('\033[1;37m~' * 20) print(f'{"Adjunting Texts".center(20)}') print('~' * 20) # Function - Center; def writh(msg): tam = int(len(msg) + 4) print('~' * tam) print(f'{msg.center(tam)}') print('~' * tam) # Main Code; title() writh(str(input('Type a mensage: ')))
false
6d7150976b3112a7c3fdb7e9ad3a7b0fbabb1c8a
RishiVaya/Sudoku-Solver
/base.py
2,008
4.21875
4
# Sudoku solver which uses backtracking algorithm. def find_empty(board): for row in range(len(board)): for col in range(len(board[0])): if board[row][col] == 0: return [row, col] return None def printer(board): for row in range(len(board)): if row % 3 == 0: print("-------------------------------------") for col in range(len(board[0])): if col % 3 == 0: print("| ", end = " ") print (board[row][col], end = " ") print("|") print("-------------------------------------") def is_valid(board, value, position): for i in board[position[0]]: if i == value: return False for i in board: if i[position[1]] == value: return False for i in range((position[0] // 3) * 3, ((position[0] // 3) * 3) + 3 ): for x in range((position[1] // 3) * 3, ((position[1] // 3) * 3) + 3 ): if board[i][x] == value: return False return True def backtrack_solver(board): new_empty = find_empty(board) if new_empty == None: return True for i in range(1, 10): if is_valid(board, i, new_empty): board[new_empty[0]][new_empty[1]] = i if backtrack_solver(board): return True board[new_empty[0]][new_empty[1]] = 0 return False puzzle = [[0, 7, 0, 0, 0, 2, 0, 0, 0], [0, 9, 0, 3, 7, 0, 0, 0, 0], [0, 0, 5, 0, 8, 0, 0, 0, 1], [0, 0, 4, 7, 0, 0, 0, 0, 9], [0, 0, 0, 0, 9, 6, 0, 0, 0], [0, 0, 0, 0, 0, 8, 6, 5, 4], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 4, 3], [4, 0, 7, 9, 5, 0, 2, 6, 0], ] print("TO SOLVE") printer(puzzle) print(is_valid(puzzle, 7, [0, 0])) print("SOLVED") backtrack_solver(puzzle) printer(puzzle)
false
9941625a4217be281d14bbb0dd447ea52eb1a4f5
tleahy1996/TSE003
/speech-recognition.py
1,094
4.125
4
#speech recognition #use 'pip install SpeechRecognition' and 'pip install pyaudio' to allow use of microphone with python def voice(): import speech_recognition as speech robot = speech.Recognizer() microphone = speech.Microphone() with microphone as source: print("Please speak.") audio = robot.listen(source) #recieves voice input from microphone try: print("The sentence was: " + robot.recognize_google(audio)) #outputs voice input as text s = robot.recognize_google(audio) #currently using google speech recognition return s except speech.UnknownValueError: print("Not understood, sorry.") except speech.RequestError: print("Something went wrong, error {0}".format(error)) except speech.UnboundLocalError: print("Something went wrong, error {0}".format(error)) sentence = voice() #basic inputs and outputs to test but replace these with library Q&A #allow multiple inputs/use language detection while True: if sentence == "hello": #input print("hi") #output if sentence == "bye": print("goodbye") break sentence = voice()
true
b3515cb94e8269f9a4ca4c2a4f1a01e7f4d54147
jamesaduke/toy-problems-new
/codewars/python-problems/7-kyu/sum_digits.py
461
4.21875
4
# Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: # sum_digits(10) # Returns 1 # sum_digits(99) # Returns 18 # sum_digits(-32) # Returns 5 def sumDigits(number): number = abs(number) return_number = 0 while number > 0: return_number += number % 10 number = int(number / 10) return return_number
true
ca883e2ba92cfbe18e27c4bba2386dfcd1c18e9f
Vishesh-Sharma221/School-Projects
/read_uplow.py
544
4.15625
4
# Input File Name print("\n\nEnter the name of the file : ") file_name=str(input()) with open(file_name,"r") as file: file.seek(0) lines=file.read() count_upper=0 count_lower=0 # Checking For Uppercase and Lowercase Letters for items in lines: if items.isupper(): count_upper+=1 elif items.islower(): count_lower+=1 # Displaying Output print("\n\nThe number of uppercase letters in your sentence is : " + str(count_upper)) print("The number of lowercase letters in your sentence is : " + str(count_lower))
true
98d83cdb88ab5e41bbd2c78c46fea4c5ca9de1a5
Vishesh-Sharma221/School-Projects
/check_odd_even.py
1,487
4.40625
4
# Write A Program To Pass List To A Function # To Double The Odd Values & Half The Even Values def main(): # Taking Input Values From User To Put In List input_values=input("\n\nEnter the numeric values of the list separated by an empty space : ").split() l1=list(input_values) # Converting String Inside List To Integer for items in range(0,len(l1)): l1[items] = int(l1[items]) def func(list): odd=[] even=[] # Doubling The Odd Values And Halving The Even Values for x in list: if x%2==0: x//=2 even.append(x) elif x%2!=0: x*=2 odd.append(x) else: continue # If Input Doesn't Contain Odd Or Even Values if odd==[]: odd.append("No Odd Value Present") elif even==[]: even.append("No Even Values Present") # Displaying Output print("\n\nThe odd values in the list doubled are : ", odd) print("The even values in the list halved are : ", even) # Again Or Exit exet=input("\n\nDo you want to count the number of times a character is present in another string? (Yes/No) : ") if exet.lower()=="yes": main() elif exet.lower()=="no": print("\n\n") exit() else: print("\n\n") exit() func(l1) main()
true
59d99ef462a40dfd15d20d49ae3e5c1bc8d6e7a1
MrBroma/PY4E-Exercises
/Chapter-1_Introduction/Chapter-1_exercises.py
1,456
4.125
4
# Exercise 1: What is the function of the secondary memory in a computer? # a) Execute all of the computation and logic of the program # b) Retrieve web pages over the Internet # c) Store information for the long term, even beyond a power cycle # d) Take input from the user # Exercise 2: What is a program? # Exercise 3: What is the difference between a compiler and an interpreter? # Exercise 4: Which of the following contains “machine code”? # a) The Python interpreter # b) The keyboard # c) Python source file # d) A word processing document # Exercise 5: What is wrong with the following code: # >>> primt 'Hello world!' # File "<stdin>", line 1 # primt 'Hello world!' # SyntaxError: invalid syntax # >>> # Exercise 6: Where in the computer is a variable such as “x” stored after the following Python line finishes? x = 123 # a) Central processing unit # b) Main Memory # c) Secondary Memory # d) Input Devices # e) Output Devices # Exercise 7: What will the following program print out: x = 43 x = x + 1 print(x) # a) 43 # b) 44 # c) x + 1 # d) Error because x = x + 1 is not possible mathematically # Exercise 8: Explain each of the following using an example of a human capability: # (1) Central processing unit, (2) Main Memory, (3) Secondary Memory, (4) Input Device, and (5) Output Device. # For example, “What is the human equivalent to a Central Processing Unit”? # Exercise 9: How do you fix a “Syntax Error”?
true
d3c88894092fcc134a08985e5716896f224a58ee
ArtisanGray/personal-projects-2018
/python-projects/solution1.py
559
4.21875
4
init_ = int(input("Enter the starting number to look for palindromes in: ")) end = int(input("Enter the end number to look for palindromes in: ")) def findLP(a,b): palindromes = []; x = a; y = a; countLoop = 0 for z in range(a,b): for i in range(a,b): xstr = str(x*y); y+=1; if xstr[0::] == xstr[::-1]: palindromes.append(int(xstr)) y = a; x += 1; countLoop += 1 pOrder = sorted(palindromes) print("\n The largest palindrome made from two products in the range of ",a," through ",b," is ",pOrder[len(pOrder)-1]) findLP(init_, end)
true
3a802dbc25b24c91f793cef82697f172c70c9a5c
NeerajaLanka/100daysofcode
/100daysDay4finalRockPaper.py
994
4.125
4
#rock paper scissors game against computer. #rock wins against scissors #scissors wins against paper #paper wins against rock. import random rock =''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' game_images =[rock,paper,scissors] user_choose = int(input ("What do you choose type 0 for rock, 1 for paper,2 for scissors ")) print(game_images[user_choose]) computer_choose = random.randint(0,2) print(game_images[computer_choose]) if user_choose == 0 and computer_choose == 2: print("you won") elif user_choose == 2 and computer_choose == 1: print("you won") elif user_choose == 1 and computer_choose == 0: print("you won") elif user_choose == computer_choose: print("it's draw") else: print("you loose")
false
2295b9f31746420d1c443b8340f03839d99b8dd9
NeerajaLanka/100daysofcode
/100daysDay4Treasure.py
589
4.28125
4
position = 12 #this variable position we never used. row1 =["x1","x2","x3"] row2 =["y1","y2","y3"]#usually matrix count by 3*3...so 1st row,2nd row,3rd row and 1st column,2nd column,3rd column. row3 =["z1","z2","z3"]#but for counting by index it start from 0 and 1 and 2 matrix = [] matrix.append(row1) matrix.append(row2) matrix.append(row3) print(matrix) print(f"{row1}\n{row2}\n{row3}\n") print(matrix[1][2]) matrix[1].pop(2) #this method removes element in nested list matrix[1].insert(2,"t") #this method inserts element in nested list print(f"{row1}\n{row2}\n{row3}\n")
true
6dd4dce296dd019f5bc58bfc7e0b73fdf800e079
NeerajaLanka/100daysofcode
/100daysDay1-2.py
524
4.125
4
#fix the errors or debugging print("Day 1 - String Manipulation") print('String Concatenation is done with the "+" sign.') print('e.g. print("Hello " + "world")') print(("New lines can be created with a backslash and n.")) #input function #this is commenting #print(input("what is your name?")) #input function with string print("hello " + input("what is your name?")) #nested inside the other. #thonny.org Thonny python IDE for beginners it shows how code run inside.it is in 009 python inputfunction video
true
407f9d53ec6beaa58972c0762ba1774ebce3674c
Stashy12399/Schoolwork
/unitconverter.py
1,230
4.375
4
# my first full project in python - its very basic and i made it in less than an hour print("Unit Converter by Stan (its rather basic)") #just the title of the project i guess def unit_converterthebest(): number_2 = 1000 choice = int(input("Type 1 for litre to ml , Type 2 for ml to litre : ")) if choice >= 3: print("Please enter either 1 or 2") unit_converterthebest() if choice == 1: print("You have chosen the Litre to Mililitre converter") number_1 = int(input("Enter a litre that you want to convert to ml: ")) result= number_1*number_2 print(result) elif choice == 2: print("You have chosen the Mililitre to Litre Converter") number_12 = int(input("Enter a mililitre that you want to convert to litre: ")) result2= number_12/number_2 print(result2) #entire function of the unit converter, you can change the units if you want to change it to kg to g etc try: unit_converterthebest() except ValueError as e: print("you entered a letter , not a number") #error catcher :) (im a fkn god) # this was my first proper project , super basic since its only multiplying stuff but oh well here it is
true
bf05fb7d6ad85bc26c94d88bfb37671b98cc7be0
upperlinecode/budget-buddy-python-functions
/budget.py
2,333
4.4375
4
# Define your functions here # Here's a function that's already been defined, but it's just a skeleton. It takes one argument (total) that we will pass to the function as an integer when we call it. # 1. Replace "return" with code such that this function RETURNS the message "WARNING: Budget exceeded" if the total is over 100 dollars. def simple_budget_checker(total): return # 2. Define a function called budget_checker that checks to make sure the total is less than 100 dollars. # If the total is over 100 dollars, return the message "WARNING: Budget exceeded" # If the total is under 100 dollars, return the message "You're under budget!" # 3. Define a function called precise_budget_checker that checks to make sure the total is less than 100 dollars. # It should do exactly what the budget checker does, but it should ALSO return the message "STOP! Maximum reached" if the total is EXACTLY 100 dollars # 4. Write a function called ultimate_budget_checker that checks to make sure the total is less than 100 dollars. # If the total is under that amount, let the user know how many dollars they have left to spend. # If the total is over that amount, let the user know how many dollars worth of items they need to put back. # 5. Below is a function called flexible_budget_checker. It hasn't been fully defined yet, but you can see it takes two arguments. # It should be exactly like the ultimate_budget_checker, except it will check your total against a budget YOU enter into the function. # For example, the code flexible_budget_checker(40, 50) should return the message "WARNING: budget exceeded by 10 dollars." def flexible_budget_checker(budget, total): return # 6. CHALLENGE: The trouble with the first four functions is that they only work for a budget of 100 dollars. # The trouble with the fifth function is that it makes the test provide the budget every time. # The best solution to this would be to have a global variable called budget before you start defining functions, and then use that variable in place of the number 100. # GOAL: Refactor (rewrite) the first four functions, but change the literal 100 to a global variable. # Then test out the functions to see if they still work if the budget (stored in the global variable) is cut down to 40 dollars.
true
c25b50c0ffb180a71ec163f44afc9fc9afaf4bd8
lovgager/finals
/base_pizza.py
1,062
4.125
4
class Pizza: """ Базовый класс для пиццы. Можно задать рецепт виде словаря с названием ингредиентов и их количеством, а также размер пиццы. Рецепт можно вывести через dict(). Можно сравнить две пиццы через магический метод __eq__(). """ def __init__(self, size='L'): if size == 'L': self.receipt = { 'tomato sauce': 111, 'mozzarella': 123, } elif size == 'XL': self. receipt = { 'tomato sauce': 222, 'mozzarella': 321, } else: raise ValueError('Size must be L or XL') self.size = size def dict(self): return self.receipt def __eq__(self, other): if not isinstance(other, Pizza): return False return self.__dict__ == other.__dict__
false
d9625c1385be5371c2c56e07ec25435e7e7ec142
yashwanthguguloth24/DataStructures
/Stack/postfix_evaluate.py
1,320
4.46875
4
''' Given a postfix expression, the task is to evaluate the expression and print the final value. Operators will only include the basic arithmetic operators like *,/,+ and - . Input: The first line of input will contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an postfix expression. Output: For each test case, in a new line, evaluate the postfix expression and print the value. Constraints: 1 <= T <= 100 1 <= length of expression <= 100 Example: Input: 2 231*+9- 123+*8- Output: -4 -3 ''' def postfix(arr): stack = [] for item in arr: if item == '*': n1 = stack.pop() n2 = stack.pop() stack.append(n1*n2) elif item == '/': n1 = stack.pop() n2 = stack.pop() stack.append(n2//n1) elif item == '-': n1 = stack.pop() n2 = stack.pop() stack.append(n2-n1) elif item == '+': n1 = stack.pop() n2 = stack.pop() stack.append(n1+n2) else: stack.append(int(item)) print(stack.pop()) for _ in range(int(input())): arr = list(map(str, input())) postfix(arr)
true
216408d1f2d8e59c4dc4964c9e2620eff16b6aba
thohidu/google-algorithms
/lesson_3/binary_search_quiz.py
1,399
4.25
4
"""You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated values, and elements are in a strictly increasing order. Return the index of value, or -1 if the value doesn't exist in the list.""" def binary_search(input_array, value): """Your code goes here.""" n = len(input_array) start_idx = 0 end_idx = n - 1 while start_idx <= end_idx: mid_dist = (end_idx - start_idx + 1)//2 mid_idx = start_idx + mid_dist # for even, right end value if value == input_array[mid_idx]: return mid_idx elif value > input_array[mid_idx]: start_idx = mid_idx + 1 elif value < input_array[mid_idx]: end_idx = mid_idx - 1 return -1 if __name__ == "__main__": # list with elements in increasing order test_list = [1,3,9,11,15,19,29] test_val1 = 25 test_val2 = 15 print(binary_search(test_list, test_val1)) print(binary_search(test_list, test_val2)) print(binary_search(test_list, 29)) print(binary_search(test_list, 9)) print(binary_search(test_list, 1)) print(binary_search(test_list, 100)) print(binary_search(test_list, -1))
true
8a825275d8cf389cc79fa9bf2c41280423a45f63
UncleStifler/LearnPython
/lesson2/cycle_for.py
1,537
4.40625
4
for number in range(3): # range - количество раз с указанием print(f'Привет мир {number}!') # перебор строки побуквенно for letter in 'python': print(letter.upper()) # разобъем на пробелы example_string = 'I\'m learn Python' for word in example_string.split(): print(f'Длина слова "{word}": {len(word)}') # пример цикла по списку и его обход. Вычисление среднего арифместического students_scores = [1, 21, 19, 6, 5] print(f'Средняя оценка: {sum(students_scores)/len(students_scores)}') for score in students_scores: print(f'Оценка: {score}') # второй вариант оформления students_scores = [1, 21, 19, 6, 5] scores_sum = 0 for score in students_scores: scores_sum += score print(scores_sum) print(f'Средняя оценка: {sum(students_scores)/len(students_scores)}') # работа со списком словарей from cycle_for_cycle_FOR import discounted stock = [ {'name': 'iPhone Xs Plus', 'stock': 24, 'price': 65432.1, 'discount': 25}, # {'name': 'Samsung Galaxy S10', 'stock': 8, 'price': 50000.0, # 'discount': 10}, # {'name': '', 'stock': 18, 'price': 10000.0, 'discount': 10} ] for phone in stock: phone['final_price'] = discounted(phone['price'], phone['discount'], name = phone['name']) print(stock)
false
59383793df0b98cdef48a0276689d1ed93a1def1
digant0705/python-code
/day5.py
453
4.15625
4
""" This problem was asked by Jane Street. cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: """ def cons(a,b): def pair(f): return f(a, b) return pair def car(x): return x(lambda a,b:a) def cdr(x): return x(lambda a,b:b) print(car(cons(3,4))) print(cdr(cons(3,4)))
true
9a266982cdec3bc93e412d298932bdfa03cd6a85
Arefka/Search_and_sort_algorithms
/factorial_with_and_without_recursion.py
611
4.34375
4
''' =============================================================== The main idea of factorials algorithm with recursion is about splitting task to the base and recursion parts. =============================================================== ''' def factorial_with_recursion(input_value: int) -> int: if input_value == 1: return 1 else: return input_value * factorial_with_recursion(input_value - 1) def factorial_without_recursion(input_value: int) -> int: output_value = 1 for counter in range(2, input_value+1): output_value *= counter return output_value
true
1a2939d0deab23054ceda2d30a93e737e0fcab68
yzzjohn/python_learning
/strip()_by_regex_chapter_7.py
735
4.59375
5
#! Python3 # a regex version of ".strip()" for test in Chapter 7 import re def re_strip(string, char): if char == '': # remove blanket at beginning/end remove_blank = re.compile(r'(^\s*)(\w+[A-Za-z0-9\s]*\w+)(\s*$)') mo = remove_blank.search(string) output = mo.group(2) return output else: # remove select characters remove_character = re.compile(r'%s'%character) output = remove_character.sub('', string) return output # ask for string to modify print('Please enter a string:') string = input() # ask for character to remove print('Please enter the charter you want to remove') character = input() # print result print(re_strip(string, character))
true
64756052963baa6617e01a87575848c4d3a87892
duilee/workspace
/Algorithms/Dynamic_Programming/01_sugar.py
1,013
4.28125
4
# Mirko works in a sugar factory as a delivery boy. # He has just received an order: he has to deliver exactly N kilograms of sugar # to a candy store on the Adriatic coast. Mirko can use two types of packages, # the ones that contain 3 kilograms, and the ones with 5 kilograms of sugar. # Mirko would like to take as few packages as possible. # For example, if he has to deliver 18 kilograms of sugar, he could use six 3-kilogram packages. # But, it would be better to use three 5-kilogram packages, and one 3-kilogram package, # resulting in the total of four packages. # Help Mirko by finding the minimum number of packages required to transport exactly N kilograms of sugar. N = int(input()) remainder = N % 5 count = N // 5 ans = -1 if N == 3: ans = 1 elif N >= 5: if remainder == 0: ans = count elif remainder == 1 or remainder == 3: ans = count + 1 elif remainder == 4: ans = count + 2 elif N > 7 and remainder == 2: ans = count + 2 print(ans)
true
ae3110db33ff75717a0d525ff170f4aa000a0e11
Rishi05051997/Python-Notes
/6-CHAPTER/01-if-else.py
424
4.125
4
# 1. if -->> elif # age = int(input('enter a your age \n')) # if(age>18): # print('Congartulations you are eligible:)') # elif(age<18): # print('You are not adult') # else : # print('Sorry you are not eligible:(') # 2. multiple if statements a = 18 if(a > 3): print('a is more than 3') if(a > 10): print('a is more than 10') if(a > 15): print('a is more than 15') else : print('noting')
false
30c4a2f6c7052439f92d019987716513727af1b7
Rishi05051997/Python-Notes
/8-CHAPTER/PRACTICE/1-greatest-of-3.py
613
4.125
4
def greatest(num1, num2, num3): # if num1 > num3: # f1 = num1 # else: # f1 = num3 # if num1 > num2: # f1 = num1 # else: # f2 = num2 # if f1 > f2 : # return print(f1) # else: # return print(f2) if(num1 > num2): if(num1>num3): return num1 else: return num3 else: if(num2>num3): return num2 else: return num3 a = greatest(1,2,3) print("The value of the maximum is " + str(a)) b = greatest(56, 99, 55) print("The value of the maximum is " + str(b))
true
f224e1243e9e1e3aaef0831bfef73323dc20aa3b
OlehPalka/First_semester_labs
/Lab work 6/sieve_flavius.py
1,127
4.125
4
""" Sorts numbers """ def sieve_flavius(your_num: int) -> list: """ This function completes sorting of numbers (n) by finding lucky numbers in the list. >>> sieve_flavius(100) [1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99] >>> sieve_flavius(10) [1, 3, 7, 9] """ lucky_num = 3 list_of_nums = list() for i in range(your_num): #delet even numbers for first check if (i + 1) % 2 != 0: list_of_nums.append(i + 1) lucky_num_index = 1 while True: del_index = 0 # del_index - index for deleting numbers from list while True: compared_list = list_of_nums #creat new list for comarison if function is done del_index += lucky_num - 1 if del_index > len(compared_list) - 1: break del list_of_nums[del_index] # encrease lucky number index lucky_num_index += 1 try: lucky_num = list_of_nums[lucky_num_index] except IndexError: break return list_of_nums
true
fe5ef3983c09fd75f89f2b8de39594aca9c3c9bb
OlehPalka/First_semester_labs
/Lab work 7/one_month_calendar_prakt.py
972
4.3125
4
def weekday_name(number: int) -> str: """ int -> str Return a string representing a weekday (one of "mon", "tue", "wed", "thu", "fri", "sat", "sun") number : an integer in range [0, 6] >>> weekday_name(3) 'thu' >>> weekday_name(8) """ if number < 0 or number > 6: return None else: Week_days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] x = Week_days[number] return x import doctest print(doctest.testmod()) def weekday(date): """ str -> int Return an integer representing a weekday (0 represents monday and so on) Read about algorithm as Zeller's Congruence date : a string of form "day.month.year if the date is invalid raises AssertionError with corresponding message >>> weekday("12.08.2015") 2 >>> weekday("28.02.2016") 6 """ pass
true
01f2941c78efa07384d32289cbbe0449b60240e9
mevinngugi/learningPython
/MITx6.00.1/problem_set_1/problem3.py
484
4.375
4
# Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. # For example, if s = 'azcbobobegghakl', then your program should print # Longest substring in alphabetical order is: beggh # In the case of ties, print the first substring. # For example, if s = 'abcbcd', then your program should print # Longest substring in alphabetical order is: abc def longest_substring(s): pass
true
3db0a0045051c51ae455c75e38aeb724ca2acfd7
StanislavBubnov/Python
/Lesson1/Hometask 1.4.py
538
4.15625
4
#4) Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. i=int(input('Введите число n: ')) a=0 if i>10: while i>10: b = i % 10 i //= 10 if a < b: a = b if a < i: a = i else: a=i print(f'Самая большая цифра в Вашем числе {a}')
false
e86e3e5014c3330482fee48ef5ae10c943a96065
shreyaspadhye3011/MIT6.0
/test2.py
252
4.28125
4
# Program to distinguish even & odd numbers without using '%' operator userInput = int(raw_input('Enter a number: ')); # print type(userInput); if((userInput / 2) * 2 == userInput): print userInput, ' IS even'; else: print str(userInput) + ' is odd';
true
bf74d0ca90f5d3e0cebd4a348459a65d3ff97f3b
renamez4/project-1
/lecture 2/EX1.py
296
4.125
4
score1 = int(input('Enter the score for test 1:')) score2 = int(input('Enter the score for test 2:')) score3 = int(input('Enter the score for test 3:')) score_all = ( score1 + score2 + score3 ) / 3 print("\n Average",score_all) if score_all > 95 : print("Congratulation!\n Congrat Guy Lucky")
false
e958111db3a4c6e7df7d9b34eb2ae7b35ded3477
renamez4/project-1
/lecture5/PassingArguments.py
321
4.25
4
#This program demostrates an argument being #passed to a function. def main(): value = int(input('number: ')) show_double(value) #The show_double function accepts an argument #and displays double its value. def show_double(number): result = number * 2 print(result) #call the main function. main()
true
5d13e1a58166553bfdc69b9828e285e29d695e14
nuclearenergyant/PythonTestDemo
/favorite_language.py
367
4.1875
4
# 来自python的标准库 from collections import OrderedDict favorite_language = OrderedDict() favorite_language['jen'] = 'python' favorite_language['sarah'] = 'c' favorite_language['edward'] = 'ruby' favorite_language['phil'] = 'python' for name, language in favorite_language.items(): print(name.title() + " : my favorite language is " + language.title())
false
64dc5f42655dc52769758fe3f96508b81aaea4b9
RobinDeHerdt/HackerRank
/Python/Date and Time/calendar-module.py
503
4.3125
4
# https://www.hackerrank.com/challenges/calendar-module/problem import calendar # Format: "MM DD YYYY" input_date = input() # Make sure all input values are converted to int month, day, year = map(int, input_date.split()) # Create a list of day names - monday will be at index 0! week_name_list = list(calendar.day_name) # Calculate day number for the given date. By default 0 = monday. day_number = calendar.weekday(year, month, day) day_name = week_name_list[day_number] print(day_name.upper())
true
1450aeebcbd1700428b02fee129467eb8cfcfa58
RobinDeHerdt/HackerRank
/Algorithms/Sorting/bubble-sort.py
768
4.125
4
# https://www.hackerrank.com/challenges/ctci-bubble-sort/problem from Testing import assertions def bubble_sort(arr): arr_len = len(arr) swap_count = 0 for i in range(arr_len): for j in range(arr_len - 1): current_element = arr[j] if current_element > arr[j+1]: arr[j] = arr[j+1] arr[j+1] = current_element swap_count += 1 # Required test output on hackerrank. # print("Array is sorted in {0} swaps.".format(swap_count)) # print("First Element: {0}".format(arr[0])) # print("Last Element: {0}".format(arr[-1])) return arr assertions.assert_equals([1, 2, 3], bubble_sort([3, 2, 1])) assertions.assert_equals([1, 2, 3, 4], bubble_sort([4, 2, 3, 1]))
true
af2ef62418996ac02b0b1b0fc61ea7511b7edfaf
gordonwu66/timer
/timer.py
722
4.15625
4
import time def count(): print('Enter anything to start timer: ') input() startTime = time.time() print('Enter anything to stop timer: ') input() endTime = time.time() timeElapsed = endTime - startTime minutes = int(timeElapsed / 60) seconds = int(timeElapsed % 60) print(str(minutes) +' minute(s) and ' +str(seconds) +' second(s) have passed.') def setTime(): print('Enter number of seconds to count down from: ') timeStr = input() timeInt = int(timeStr) while timeInt > 0: print(timeInt) time.sleep(1) timeInt -= 1 print('Done!') def main(): print('Start counting time (1) or set a time to count (2)?: ') answer = input() if(answer == '1'): count() elif(answer == '2'): setTime() main()
true
6bf96ff644f1231bba8eff6113844538d1f70837
MohdMazher23/PythonAssingment
/Day2/PowerConsuption.py
713
4.28125
4
print("POWER CONSUPTION APP") units=float(input("ENTER THE NO OF units CONSUMED ")) if units<1 and units<0: print("INVALID units ENTERED") else: if units>1.0 and units<=50.0: bill_amount=units*3 elif units>51.0 and units<=100.0: bill_amount=units*6 elif units>101.0 and units<=150.0: bill_amount=units*9 elif units>151.0 and units<=200.0: bill_amount=units*12 else: bill_amount=units*15 print("THE TOTAL units CONSUMED IS: ",units) print("TOTAL BILL AMOUNT",round(bill_amount,4)) #output """ POWER CONSUPTION APP ENTER THE NO OF units CONSUMED 151.9 THE TOTAL units CONSUMED IS: 151.9 TOTAL BILL AMOUNT 1822.8 """
true
db57be3d4dbc43e4088f48c5687440ce31318ad2
Said-Akbar/exercises
/Python_by_Zelle/chapter_4_ex/chapter_4_barplot.py
1,276
4.21875
4
# Chapter 4 examples and exercises from the python book by John Zelle from graphics import * def main(): print("Plotting a 10 year investment") # get inputs principal = float(input("Enter the principal: ")) apr = float(input("Enter the interest rate: ")) win = GraphWin("10 year investment barplot", 640, 480) # instantiates a window object win.setBackground("white") # sets the window background win.setCoords(-1.75, -200, 11.5, 10400) # coordinate transformation # These lines display x axis ticks Text(Point(-1, 0), "0.0K").draw(win) # Text object accepts a coordinate and string literal Text(Point(-1, 2500), "0.0K").draw(win) Text(Point(-1, 5000), "2.5K").draw(win) Text(Point(-1, 7500), "5.0K").draw(win) Text(Point(-1, 10000), "7.5K").draw(win) # Initial bar plot bar = Rectangle(Point(0, 0), Point(1, principal)) # draws a rectangle, requires two points bar.setFill("green") bar.setWidth(2) bar.draw(win) # draw bars for each subsequent years for year in range(1, 11): principal = principal * (1+apr) bar = Rectangle(Point(year, 0), Point(year+1, principal)) bar.setFill("green") bar.setWidth(2) bar.draw(win) input("") win.close() main()
true
895fe2aa57d23564ca86bf46baeea8396c200750
Said-Akbar/exercises
/Python_by_Zelle/chapter_9/exercise3.py
1,731
4.1875
4
# exercise 3, chapter 9. 01/01/2020 by SaidakbarP # recquetball from random import random def printIntro(): print("Racquetball game") def getInputs(): a = float(input("Enter the prob of A player winning when serving: ")) b = float(input("Enter the prob of B player winning when serving: ")) n = int(input("Enter the number of simulations: ")) return a, b, n def simNGames(n, probA, probB): winsA = 0 winsB = 0 shout = 0 for i in range(n): scoreA, scoreB = simOneGame(probA, probB) if scoreA>scoreB: winsA += 1 else: winsB += 1 return winsA, winsB def simOneGame(probA, probB): serving = "A" scoreA = 0 scoreB = 0 while not (gameOver(scoreA, scoreB) or scoreA>15 or scoreB>15): if serving == "A": # when A is serving if random() < probA: # by random chance if randomness is smaller than the winning probability of A then A wins scoreA = scoreA + 1 else: serving = "B" else: if random() < probB: scoreB = scoreB + 1 else: serving = "A" #print(scoreA, scoreB) return scoreA, scoreB def gameOver(a, b): return (a==15 and abs(a-b)>=2) or (b==15 and abs(b-a)>=2) def printSummary(winsA, winsB): n = winsA + winsB print("Simulated games: ", n) print("Wins for A: {} {:0.1%}".format(winsA, winsA/n)) print("Wins for B: {} {:0.1%}".format(winsB, winsB/n)) def main(): printIntro() probA, probB, n = getInputs() #print(simOneGame(0.6,0.65)) winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB) if __name__ == '__main__': main()
true
3b8bc3eb48f13220a41766b89582eeeb185421a7
nursin/Python-Fundamentals
/Weeks1-2/builtin_functions.py
352
4.1875
4
print("Math Functions") # declaring a variable named abs_int that will return a value from abs function #absolute value abs_int = abs(-1) print(abs_int) int_to_float = float(100) print(int_to_float) float_to_int = int(1.23) print(float_to_int) print(int(1.23)) print(max(1,2,3,-5,10,0)) print(min(1,2,3,-5,10,0)) print(pow(2,3)) print(round(51.6))
true
30d3da1ba30eadb48126f60fef1af8c400b4f582
michael-mck-doyle/Python
/unit_tests/test_calc_function.py
1,172
4.28125
4
''' 1. import the function that you need e.g. import unittest 2. create a test case Class in the test file 3. define the test case (which is a method) - the test case is written in the method 4. the test case name (method) must begin with "test_" ''' import unittest from unit_tests import calc_Function class test_calc_function(unittest.TestCase): def test_calc_add(self): #result = calc_function.add(10, 5) self.assertEqual(calc_Function.add(10, 5), 15) print("1") self.assertEqual(calc_Function.add(-1, -2), -3) print("2") self.assertEqual(calc_Function.add(1, 2), 3) print("3") def test_calc_subtract(self): result = calc_Function.subtract(10, 2) self.assertEqual(result, 8) print("4") def test_calc_multiply(self): result = calc_Function.multiply(3, 15) self.assertEqual(result, 45) print("5") def test_calc_divide(self): #result = calc_function.divide() self.assertEqual(calc_Function.divide(9, 3)) with self.assertRaises(ValueError): calc_Function if __name__ == '__main__': unittest.main()
true
5346d621d848f17bed0a39b0e56db86af58db849
michael-mck-doyle/Python
/09_exceptions/09_02_calculator.py
711
4.3125
4
''' Write a script that takes in two numbers from the user and calculates the quotient. Using a try/except, the script should handle: - if the user enters a string instead of a number - if the user enters a zero as the divisor Test it and make sure it does not crash when you enter incorrect values. ''' try: x = input("Enter a number: ") y = input("Enter a second number: ") x = int(x) y = int(y) quotient = x // y print(quotient) except ValueError as e: print("Please enter an int '", e) except TypeError as e: print("unsupported operand type(s) for //: 'str' and 'str'", e) except ZeroDivisionError as e: print("integer division or modulo by zero is not allowed", e)
true
79abf1f6601c61271f8e1ed786d790974c392bb3
michael-mck-doyle/Python
/06_functions/three_functions_06_03.py
1,188
4.375
4
''' Write a program with 3 functions. Each function must call at least one other function and use the return value to do something. """ Reference for how to nest functions - https://stackoverflow.com/questions/6289646/python-function-as-a-function-argument Yes. By including the function call in your input argument/s, you can call two (or more) functions at once. For example: def anotherfunc(inputarg1, inputarg2): pass def myfunc(func = anotherfunc): print func When you call myfunc, you do this: myfunc(anotherfunc(inputarg1, inputarg2)) This will print the return value of anotherfunc. Hope this helps! """ ''' # Solution 1 # a calls b def a_func(b_func): return b_func + 1 # b calls c def b_func(c_func): return c_func + 1 # c def c_func(x): return x + 1 print(a_func(b_func(c_func(2)))) def house_sales(houses_sold, house_cost): return houses_sold * house_cost def houses_sold(jan, feb, march): return jan + feb + march def house_cost(cost): return cost print("$ value of houses sold: $", house_sales(houses_sold(100, 200, 300), house_cost(5000))) #example of type hinting #def my_add(a: int, b: int) -> int: # return a + b
true
201298d5335feb76f931614b0b3014e4e6c777b9
michael-mck-doyle/Python
/13_aggregate_functions/13_03_my_enumerate.py
851
4.5625
5
''' Reproduce the functionality of python's .enumerate() Define a function my_enumerate() that takes an iterable as input and yields the element and its index More details on enumerate function: https://docs.python.org/3.8/library/functions.html#enumerate Using enumerate function is equivalent to writing: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ''' def my_enumerate(x, start = 1): n = start for i in x: # where x is the sequence, list.. yield n, i n += 1 names = ["John", "Grace", "Zac", "Chrissy", "Reynaldo", "Gemima"] enum = my_enumerate(names, start=1) for i in enum: print(i) my_list = ["apple", "banana", "orange"] new_list = [] obj1 = enumerate(my_list) print(obj1) for i in (obj1): new_list.append(i) print(new_list)
true
8868b2997cccc8e8ce3c7cf7e988a49b15ad6f3b
michael-mck-doyle/Python
/19_Practice_Folder/24_python_gui/gui_1.py
586
4.28125
4
import tkinter as tk # Tkinter wraps Tcl/tk so that it can be used it in Python from tkinter import ttk # ttk has advanced widgets, it is an extension of tkinter win = tk.Tk() win.title("Python GUI") #this line adds a label to the gui aLabel = ttk.Label(win, text="A label") aLabel.grid(column=0, row=0) # setting this to (0, 0) means that the window can't be resized #win.resizable(0,0) # modified button click function def ClickMe(): action.configure(text='Hello ' + name.get()) # changing our label ttk.Label(win, text="Enter a name:").grid(column=0, row=0) win.mainloop()
true
dbeddcf922fbc50173ab63a01d610a615f624090
michael-mck-doyle/Python
/different-solutions/solution_05.py
874
4.3125
4
''' Write a script that sorts a list of tuples based on the number value in the tuple. For example: unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)] sorted_list = [('second_element', 2), ('first_element', 4), ('third_element', 6)] ''' # this solution has a lot less steps than the other four solutions. # this solution only has 13 steps whereas the other solutions have 30+ steps # compared to some other solutions this one executed almost twice as fast import time start_time = time.time() # your code unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)] sorted_list = [] sorted_list = sorted(unsorted_list, key=lambda x: x[1]) print(sorted_list) # use to measure time of code execution end_time = time.time() print() print() print("Total execution time: {} seconds".format(end_time - start_time))
true
4eed4f69f3cb26d45d5e0f8a931495692cbd1e2d
michael-mck-doyle/Python
/06_functions/stats_06_02.py
809
4.1875
4
''' Write a function stats() that takes in a list of numbers and finds the max, min, average and sum. Print these values to the console when calling the function. ''' from random import randrange def ran_list(): x = 0 my_num_list = [] while x < 20: y = (randrange(1, 100)) my_num_list.append(y) x += 1 return my_num_list r = ran_list() # print(r) def stats(r): a = max(r) b = min(r) c = sum(r)/len(r) d = sum(r) return a, b, c, d print(r) val_returned = list(stats(r)) print(type(val_returned)) print(val_returned) max_val = val_returned[0] print("max value: ", max_val) min_val = val_returned[1] print("min value: ", min_val) avge_val = val_returned[2] print("average value: ", avge_val) sum_val = val_returned[3] print("sum: ", sum_val)
true
98be7cb61cd51a29a647ea9f732908b3d79342c0
michael-mck-doyle/Python
/01_python_fundamentals/01_04_formula.py
385
4.21875
4
''' Write the necessary code to print the result of the following formula: (15.7 * 3.6 - 34.9 * 0.9) / (68.9 - 2.1) ''' print() print("assign the result of the calculation to a variable and then print the variable ") x = (15.7 * 3.6 - 34.9 * 0.9) / (68.9 - 2.1) print("x = " + str(x)) print() print("or print calculation directly") print((15.7 * 3.6 - 34.9 * 0.9) / (68.9 - 2.1))
true
b1df0b04ff718bce2997e4c80b34014acacd9a88
starstan/python_assesment
/ceaser/ceaser.py
1,023
4.28125
4
# Using the Python, # have the function CaesarCipher(str, num) take the str parameter and perform a Caesar Cipher num on it using the num parameter as the numing number. # A Caesar Cipher works by numing all letters in the string N places down in the alphabetical order (in this case N will be num). # Punctuation, spaces, and capitalization should remain intact. # For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt". # more on cipher visit http://practicalcryptography.com/ciphers/caesar-cipher/ # happy coding :-) import re import unittest class CaesarCipher(object): """ cipher method checks through each letter, to """ def __init__(self, caeser): self.caeser = caeser def cipher(self, num): string = self.caeser out = [] for word in string: for x in word: out.append(chr(ord(x) + num)) print(out) return " ".join(out) c = CaesarCipher("A Crazy fool Z") print(c.cipher(1))
true
d98545b5b878f542a7e31bf771362b75f506aee4
cfowles27293/leetcode
/venv/binary_tree.py
1,714
4.1875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def printTree(self): if self.left: self.left.printTree() print(self.data) if self.right: self.right.printTree() def insertNode(self, data): if self.data: if self.data < data: if not self.left: self.left = Node(data) else: self.left.insertNode(data) else: if not self.right: self.right = Node(data) else: self.right.insertNode(data) else: self.data = data def invertTree(self): if self.data: if self.left and self.right: self.left.invertTree() self.right.invertTree() swap(self.left, self.right) elif self.left and not self.right: self.right = self.left self.left = None self.right.invertTree() elif self.right and not self.left: self.left = self.right self.right = None self.left.invertTree() def swap(n1:Node, n2:Node): temp = n1.data n1.data = n2.data n2.data = temp if __name__ == "__main__": root = Node(5) root.insertNode(7) root.insertNode(2) root.insertNode(4) root.insertNode(9) root.insertNode(13) root.insertNode(3) root.insertNode(12) root.insertNode(15) root.insertNode(8) root.insertNode(1) root.printTree() root.invertTree() print("Inverted") root.printTree()
false
d20df7ba3a6233fdbbe1d9e1953f5c66c4101837
SahilChoudhary22/SimpleAppsRepo
/DSA-Files/DFS.py
1,489
4.21875
4
""" In BFS, we use queue because it's based on FIFO structure, on the other hand in DFS, we use stacks because it's based on LIFO structure. In python, when we use recursion, it automatically uses stacks in the background. """ # making a node class class Node: def __init__(self, name): # the name of node self.name = name # boolean whether the node is visited or not self.visited = False # will store the children nodes self.adjacencyList = [] self.predecessor = None # creating a class DepthFirstSearch class DepthFirstSearch: def dfs(self, startNode): ## stack = [] or we just use recursion and in the background ## it'll be automatically using stacks for storage startNode.visited = True # print each visited node name print("{}".format(startNode.name)) # for each node n in adjacencyList for n in startNode.adjacencyList: # if the node is not visited if not n.visited: # call the function recursively self.dfs(n) # TESTING, same nodes as in BFS.py node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") node5 = Node("E") node6 = Node("F") node7 = Node("G") node1.adjacencyList.append(node2) node1.adjacencyList.append(node3) node2.adjacencyList.append(node4) node4.adjacencyList.append(node5) node4.adjacencyList.append(node6) node4.adjacencyList.append(node7) dfs = DepthFirstSearch() dfs.dfs(node1) # output should be # A # B # D # E # F # G # C
true
026e0e45fb5393423031adf2e139605c385ac645
Johanstab/INF200-2019-Exercises
/src/johan_stabekk_ex/ex03_project/test_sorting.py
2,801
4.28125
4
# -*- coding: utf-8 -*- __author__ = 'Johan Stabekk' __email__ = 'johan.stabekk@nmbu.no' def bubble_sort(data_): """ Sorts the data after the bubble_sort algorithm. Parameters ---------- data_ - The data that is going to be sorted. Returns ------- data_sorted - Returns the input data sorted in a new list. """ data_sorted = list(data_) for i in range(len(data_sorted) - 1): for j in range(len(data_sorted) - 1 - i): if data_sorted[j] > data_sorted[j + 1]: data_sorted[j], data_sorted[j+1] = \ data_sorted[j+1], data_sorted[j] return data_sorted def test_empty(): """Test that the sorting function works for empty list""" assert bubble_sort([]) == [] def test_single(): """Test that the sorting function works for single-element list""" assert bubble_sort([1]) == [1] def test_sorted_is_not_original(): """ Test that the sorting function returns a new object. Consider data = [3, 2, 1] sorted_data = bubble_sort(data) Now sorted_data shall be a different object than data, not just another name for the same object. """ data = [3, 2, 1] sorted_data = bubble_sort(data) assert sorted_data is not data def test_original_unchanged(): """ Test that sorting leaves the original data unchanged. Consider data = [3, 2, 1] sorted_data = bubble_sort(data) Now data shall still contain [3, 2, 1]. """ data = [3, 2, 1] bubble_sort(data) assert data == [3, 2, 1] def test_sort_sorted(): """Test that sorting works on sorted data.""" data = sorted([3, 2, 1, 6, 10]) assert bubble_sort(data) == [1, 2, 3, 6, 10] def test_sort_reversed(): """Test that sorting works on reverse-sorted data.""" data = [5, 4, 3, 2, 1] sorted_data = sorted(data) assert bubble_sort(data) == sorted_data def test_sort_all_equal(): """Test that sorting handles data with identical elements.""" data = [1]*5 assert bubble_sort(data) == [1]*5 def test_sorting(): """ Test sorting for various test cases. This test case should test sorting of a range of data sets and ensure that they are sorted correctly. These could be lists of numbers of different length or lists of strings. """ sorted_numbers_int = [3, 4, 5, 6, 7] assert bubble_sort(sorted_numbers_int) == sorted(sorted_numbers_int) sorted_string = ['abehasdfavehhe'] assert bubble_sort(sorted_string) == sorted(sorted_string) sorted_string_list = ['aaa', 'bnbabbb', 'jfqgqefsjfjff'] assert bubble_sort(sorted_string_list) == sorted(sorted_string_list) sorted_numbers_float = [0.0000, 0.89898, 0.9999] assert bubble_sort(sorted_numbers_float) == sorted(sorted_numbers_float)
true
d442c3428a8edffef801e45ebf701d07f243a563
EthanVV/p4p
/class_01/Untitled-1.py
606
4.21875
4
# An armstrong number is an integer which has the same value as the sum of the # Nth power of each of its individual digits where N is the armstrong # number's length # E.g: 1634 = 1^4 + 6^4 + 3^4 + 4^4 # does not have input validation def is_armstrong_number(number): number_str = str(number) armstrong_power = len(number_str) armstrong_sum = 0 for digit_str in number_str: digit = int(digit_str) armstrong_sum += digit ** armstrong_power if armstrong_sum > number: return False return armstrong_sum == number print(is_armstrong_number(1634))
true
62f82ad32410da897cfa0112a931cd94e8f53099
MPuzio15/Python
/syntax/homework_area_circumference_for_chosen_figure.py
1,321
4.1875
4
import math ''' Napisać program który policzy pole powierzchni oraz obwód, bazując na zmiennych jakie poda użytkownik: Koła Kwadratu Prostokąta Trójkąta ''' print("This program will calculate the area and circumference of the figure chosen by you.") print("a length: \n") a = int(input()) print("b length: \n") b = int(input()) print("Choose the figure by writing the corresponding number" + " 1 - square" + " 2 - rectangle" + " 3 - circle" + " 4 -triangle" ) choice = int(input()) if (choice == 1): circumference = 4 * a area = a ** 2 print("Square area is: ", area, " Square circumference is: ", circumference) elif (choice == 2): circumference = 2 * a + 2 * b area = a * b print("Rectangle area is: ", area, " Rectangle circumference is: ", circumference) elif (choice == 3): diagonal = a / 2 area = math.pi * diagonal ** 2 circumference = 2 * math.pi * diagonal print("Circle area is: ", area, "Circle circumference is: ", circumference) elif (choice == 4): area = (a * b) / 2 c = a ** 2 + b ** 2 c = math.sqrt(c) circumference = a + b + c print("Triangle area is: ", area, "Triangle circumference is: ", circumference) else: print("Your choice doesn't correspond with any of the above figures")
false