blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
eb36a1165915101c5c3c7fc07f0e8c6339827e29
Jeevankv/LearnPython
/zComprehension.py
795
4.15625
4
# Normal method # ls=[] # for i in range(100): # if i%3==0: # ls.append(i) # print(ls) # List Comprehension ls = [i for i in range(100) if i%3==0 ] print(ls) # Dictionary Comprehension dic = { i:f"item{i}" for i in range(10) if i%2==0 } print(dic) # Reversing Key value Pair dic1 = {value:key for key,value in dic.items()} print(dic1) # set comprehension set1 ={ car for car in ["BMW","Royce Rolls","Lamborghini","BMW","BMW"]+ ["BMW","ferrarri","Audi"]} # Set items does not repeat print(set1) # Generator Comprehension my_sqr = (sqr*sqr for sqr in [1,2,3,4,5] ) # print(my_sqr.__next__()) # print(my_sqr.__next__()) # print(my_sqr.__next__()) # print(my_sqr.__next__()) # print(my_sqr.__next__()) for i in my_sqr: print(i)
false
140948186b164ef8db9149326cff5cd101be0e8c
CoderBleu/study_python
/class/函数属性 property.py
1,664
4.25
4
import random ''' 函数属性: 1、通过property方法直接访问私有属性 - 本来__weight是类私有属性,然后通过property后可以直接访问,但是还是会经过定义的get_weight和set_weight方法 2、通过装饰器修饰[注解] - @property 装饰器修饰,提供一个get方法 - @age.setter 提供age字段的set方法 - @age注解的字段名和函数名需要匹配 ''' class Person: # 初始化类的属性,在实例化时被执行,可以理解为构造器 def __init__(self, weight): # 实例属性 self.username = 'hello world' self.__age = 20 # 加 __ 表示此为私有化属性 self.__weight = weight def set_weight(self, weight): self.__weight = weight def get_weight(self): return self.__weight # 装饰器修饰,提供一个get方法 @property def age(self): return self.__age # 标识age的set方法, 注意函数名为age,别错了 @age.setter def age(self, age): self.__age = age # 这种方式就不能被set,只提供访问__weight方法 # weight = property(get_weight) # 定义一个类属性,可以直接通过访问属性的形式去访问私有的属性 weight = property(get_weight, set_weight) obj = Person(110) # 110 print(obj.get_weight()) # 本来__weight是类私有属性,然后通过property后可以直接访问,但是还是会经过定义的get_weight和set_weight方法 obj.weight = 10 # 10 print(obj.get_weight()) obj.set_weight(23) # 23 print(obj.weight) # 装饰器================= print(obj.age) obj.age = 18 print(obj.age)
false
23c585f29a21fc65ae1fb7076652126aaa16241f
MohammedHijazi/personalwebsite
/exercise3.py
581
4.21875
4
def creat_dict(): country_capital = { "Palestine":"Jerusalem", "Egypt":"Cairo", "USA":"DC", "Germany":"Berlin"} return country_capital def main (): dectionary = creat_dict() country= raw_input ("Enter Your Country or enter to quit :") while (country != "" ): if country in dectionary: out_put(dectionary,country) else: print "No country is found" country= raw_input ("Enter Your Country or enter to quit :") def out_put(dectionary,country): print "The capital of " + country + " is " + dectionary[country] if __name__ == "__main__": main()
false
2ace2896fbc1dd80daca1885a1a91c32a65c50dc
Mat24/stop_game
/jugador.py
1,011
4.1875
4
""" Clase de un jugador Define el "molde" de un judador, es decir las propiedades que identifican a un jugador. es decir: - nombre: cada jugador se identifica por un nombre - puntos: cada jugador lleva la "contabilizacion" de sus puntos (por defecto son cero) - respuestas: diccionario que contiene todas las respuestas que da un determinado jugador en cada categoria """ class Jugador: __nombre__ = "" __puntos__ = 0 __respuestas__ = {} def __init__(self, nombre, puntos): self.__nombre__ = nombre self.__puntos__ = puntos self.__respuestas__ = {} def get_nombre(self): return self.__nombre__ def get_puntos(self): return self.__puntos__ def get_respuestas(self): return self.__respuestas__ def agregar_respuesta(self, categoria, respuesta): self.__respuestas__[categoria] = respuesta def agregar_puntos(self, cantidad_puntos): self.__puntos__ = self.__puntos__ + cantidad_puntos
false
2e2192d69a9f9c1fc0c50d750dbe39b389b3d9b0
ilyaSerebrennikov/ilyaSerebrennikov
/Module_7_ Algo 7_2.py
1,286
4.125
4
''' 2.Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. ''' import random def merge_sort(arr): def merge(frst, snd): res = [] x, z = 0, 0 while x < len(frst) and z < len(snd): if frst[x] < snd[z]: res.append(frst[x]) x += 1 else: res.append(snd[z]) z += 1 res.extend(frst[x:] if x < len(frst) else snd[z:]) return res def div_half(lst): if len(lst) == 1: return lst elif len(lst) == 2: return lst if lst[0] <= lst[1] else lst[::-1] else: return merge(div_half(lst[:len(lst)//2]), div_half(lst[len(lst)//2:])) return div_half(arr) SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 50 array = [random.uniform(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print('Массив:', array, sep='\n') print('Он же, но после сортировки:', merge_sort(array), sep='\n')
false
0b1460d5dab91ae25b1ea9ff6e2ab587bee6f259
giraffesyo/School-Assignments
/Intoduction to Computer Programming - CSYS 1203/Assignment 3/average.py
359
4.21875
4
# This simple program will average the numbers entered by a user. # By Michael McQuade CSYS1203 def main(): print("This program will average comma separated numbers you enter.") n = eval(input("How many numbers are to be averaged? ")) avg = eval(input("Please enter the numbers you would like averaged: ")) avg = sum(avg) / n print(avg) main()
true
ff7db4aee1d82ca246adcc2cf2e065e08adef553
Harsh5751/Python-Challenges-with-CodeWars
/Binary Addition.py
533
4.34375
4
''' Binary Addition Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. ''' def add_binary(a,b): binary = str(bin(a + b)) return binary[2: ] #Sample Tests Test.assert_equals(add_binary(1,1),"10") Test.assert_equals(add_binary(0,1),"1") Test.assert_equals(add_binary(1,0),"1") Test.assert_equals(add_binary(2,2),"100") Test.assert_equals(add_binary(51,12),"111111")
true
06681e8dbe843cdcdab6b5bbccef4c17042f9a5c
Harsh5751/Python-Challenges-with-CodeWars
/sum of odd numbers.py
510
4.125
4
''' Sum of odd numbers Given the triangle of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: rowSumOddNumbers(1); // 1 rowSumOddNumbers(2); // 3 + 5 = 8 ''' def row_sum_odd_numbers(n): return n**3 #Sample Tests: Test.assertEquals(rowSumOddNumbers(1), 1); Test.assertEquals(rowSumOddNumbers(42), 74088);
true
f8f70eaf3830c19b5d91ba2b25e34e667e2c337e
Greycampus/python
/datatypes/array.py
546
4.46875
4
''' Python program to take input a sequence of numbers from user and store it in a list or array Input 3 11 12 13 Output [11, 12, 13] ''' msg = 'enter the number of elements:' #printing message for user input print(msg) # taking length of list to be inputted a = raw_input() #stripping extra spaces in input a = int(a.strip()) #empty list num = [] print('Enter the elements:') for i in range(0,a): #using append function of lists and appending the data into empty list num.append(int(input())) print('Elements of list are:') print(num)
true
c1c87e66aa1e0677343f57612e69493660e18f23
Greycampus/python
/variables/local.py
915
4.15625
4
''' python program to use local variable by taking user input and print nearest power of 3 Input 4 Output 3 ''' #import math library for log functions from math import log,floor,ceil msg = 'enter the number:' #printing message for user input print(msg) #taking input and casting it into integer n = raw_input() #stripping excess space in input n = int(n.strip()) #log(x[,base]) gives the natural algorithm of log(x)/log(base) #helpful in getting the nearest power to 3 as follows #3^n = x+c where c is minimum for nearest power #3^n = x+c => log(3^n) = log(x+c) => n*log(3) = log(x+c) #let x+c = X #=> n = log(X)/log(3) where n is the nearest nth power of 3 # similar in our case 3^n < x < 3^n+1 we calculate the minimum by #n<log(x)/log(3)<n+1 and find the nearest power minn = floor(log(n,3)) maxn = ceil(log(n,3)) if abs(n - 3**minn) <= abs(3**maxn - n): print(int(3**minn)) else: print(int(3**maxn))
true
c735202659fff96ffa73d2b0a1379343d90618b0
Greycampus/python
/regex/repla.py
478
4.5
4
''' Python program to replace all the patterns like '[!*]' using loops Input enter the string: [![![!*][!*]*]*]abc Output string before modification:[![![!*][!*]*]*]abc abc ''' import re msg = 'enter the string:' print(msg) k = str(raw_input()) print('string before modification:'+k) #replacing the pattern in string #checking if there is any occurance of pattern while(len(re.findall(r"\[!\*\]+",k))!=0): #replacing the pattern k = re.sub(r"\[!\*\]+",'',k) print(k)
true
b40c1ecde281f3021e79e19a2b5fa25dcfb239fc
Greycampus/python
/regex/occur.py
728
4.21875
4
''' python program to find the total occurences of a symbol in string using reqular expressions Input enter the main string: 1qaz!@#$!@#$zxswedc@#$% enter the symbol you wish find occurences: @ Output @ occured 3 times in 1qaz!@#$!@#$zxswedc@#$% ''' import re msg= 'enter the main string:' print(msg) #getting main string from user k = raw_input() msg = 'enter the symbol you wish find occurences:' print(msg) l = len(k) #getting symbol from user s = raw_input() #replacing input symbol in the string and find the decrease in lenth to find the occurences #re's replaces all the matching patterns from given input and returns a replaced string copy = re.sub(r''+s+'','',k) print(s+' occured '+str(l-len(copy))+' times in '+k)
true
367e24a60d82ca14411c927ba4a66a402eb90eeb
Greycampus/python
/oops/over.py
514
4.5
4
''' Python program to Use Function Overridingin a class. Output B's hello A's GoodBye ''' class A(): #constructor of A def __init__(self): self.__x = 1 #m1 function of parent def m1(self,Ab): print('A\'s '+str(Ab)) class B(A): #constructor of B def __init__(self): self.__y = 1 #m1 function of child # print("m1 from B") def m1(self,Ab): print('B\'s '+str(Ab)) b = A() c = B() #c.m1() prints hello from B c.m1('hello') b.m1('GoodBye')
false
ba2082fbbcf8ddf40333a4c3e6930584416991d0
Greycampus/python
/file_handling/filenopen.py
583
4.125
4
''' Python program to open a text file and print the nth line in text file if nth line does not exist print 'no data' Input enter the line number: 4 Ouput 4th line:hello python programmer ''' #opeing the text file f = open('text1.txt','r') #getting nth line number from user msg = 'enter the line number:' print msg n = int(raw_input().strip()) #split the file based on lines using \n escape code as \n indcates new line dd = list(f.read().split('\n')) if(len(dd)>=n+1):#checking if nth line exists in file or not print('%dth line:'%n+str(dd[n-1])) else: print('no data')
true
669c1c377f6336ac8bde5baa2a43cfb28f4fdfcf
haddow64/CodeEval
/Easy/01 - Fizz Buzz.py
2,470
4.25
4
#Players generally sit in a circle. The player designated to go first says the number "1", #and each player thenceforth counts one number in turn. However, any number divisible by 'A' e.g. #three is replaced by the word fizz and any divisible by 'B' e.g. five by the word buzz. Numbers #divisible by both become fizz buzz. A player who hesitates or makes a mistake is either eliminated. #Write a program that prints out the the pattern generated by such a scenario given the values of 'A'/'B' #and 'N' which are read from an input text file. The input text file contains three space delimited numbers #i.e. A, B, N. The program should then print out the final series of numbers using 'F' for fizz, 'B' for 'buzz' and 'FB' for fizz buzz. #INPUT SAMPLE: #Your program should read an input file (provided on the command line) which contains multiple newline separated lines. #Each line will contain 3 numbers which are space delimited. The first number is first number to divide by ('A' in this example), #the second number is the second number to divide by ('B' in this example) and the third number is where you should count till ('N' in this example). #You may assume that the input file is formatted correctly and is the numbers are valid positive integers. E.g. #1 #2 #3 5 10 #2 7 15 #OUTPUT SAMPLE: #Print out the series 1 through N replacing numbers divisible by 'A' by F, numbers divisible by 'B' by B and numbers #divisible by both as 'FB'. Since the input file contains multiple sets of values, your output will print out one line per set. #Ensure that there are no trailing empty spaces on each line you print. E.g. #1 #2 #1 2 F 4 B F 7 8 F B #1 F 3 F 5 F B F 9 F 11 F 13 FB 15 #Constraints: #The number of test cases <= 20 #"A" is in range [1, 20] #"B" is in range [1, 20] #"N" is in range [21, 100] # -*- coding: utf-8 -*- #!/usr/bin/env python """Usage: ./fizzbuzz.py <filename>""" def fizzbuzz(f, b, l): return [(i % f == 0 and 1 or 0) * 'F' \ + (i % b == 0 and 1 or 0) * 'B' \ or '%d' % i \ for i in range(1, l + 1)] if __name__ == '__main__': import sys if len(sys.argv) <= 1: sys.exit(__doc__) dat = None try: dat = open(sys.argv[1]) for l in dat.readlines(): f, b, l = l.split(' ') print ' '.join(fizzbuzz(int(f), int(b), int(l))) except Exception, e: sys.exit(e) finally: if dat: dat.close()
true
e3b7a1ddd339af3646ba2b60d0da043bd1fe8d05
Piwero/bootcamp_projects
/find_py.py
333
4.21875
4
''' Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. ''' #import the math import math def find_pi(n): print(format(math.pi,'.{}f'.format(n))) #---------------------TEST------------------- find_pi(6) find_pi(4) find_pi(2)
true
4b506d5b5e52cd352177df56e39a5cb77009e4de
kamilloads/prog1ads
/lista3-9.py
1,132
4.1875
4
#9 - Faça um Programa que leia três números e mostre-os em ordem decrescente. print("9 - Faça um Programa que leia três números e mostre-os em ordem decrescente.") num1 = int (input("Digite o primeiro numero: ")) num2 = int (input("Digite o segundo numero: ")) num3 = int (input("Digite o terceiro numero: ")) if num1 > num2 and num1 > num3 and num2 > num3: print(f"{num1}, {num2}, {num3} é a ordem decrescente dos numeros.") elif num1 > num2 and num1 > num3 and num3 > num2: print(f"{num1}, {num3}, {num2} é a ordem decrescente dos numeros.") elif num2 > num1 and num2 > num3 and num3 > num1: print(f"{num2}, {num3}, {num1} é a ordem decrescente dos numeros.") elif num2 > num1 and num2 > num3 and num1 > num3: print(f"{num2}, {num1}, {num3} é a ordem decrescente dos numeros.") elif num3 > num1 and num3 > num2 and num2 > num1: print(f"{num3}, {num2}, {num1} é a ordem decrescente dos numeros.") elif num3 > num1 and num3 > num2 and num1 > num2: print(f"{num3}, {num1}, {num2} é a ordem decrescente dos numeros.") else: print("Voce digitou todos os numeros iguais ou dois3 numeros iguais.")
false
bd29c7dc82dcbedb74384ad3a10f9e84ec7290bb
kamilloads/prog1ads
/lista3-2.py
283
4.21875
4
#2 - Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. num = float (input("digite um numero: ")) if num > 0: print(f"{num} é um numero positivo.") elif num < 0: print(f"{num} é um numero negativo.") else: print(f"{num} é nulo")
false
e1044cb36bdfb2180af54f435d5cb202f5213501
Anna1027/CaesarCipherEncryption
/caesarCipher.py
485
4.125
4
#c = (x - n)%26 def encrypted(string, shift): cipher= ' ' for char in string: if char==' ': cipher = cipher+char elif char.isupper(): cipher= cipher+chr((ord(char)+shift-65)%26+65) else: cipher=cipher+chr((ord(char)+shift-97)%26+97) return cipher text=input("Enter the text: ") s = int(input("Enter the shift key: " )) print("The original string is: ",text) print("The encrypted msg is: ",encrypted(text,s) )
true
be76d86c066d19f1eb3c787f3cf54c26292b71de
mtthwgrvn/Python-Resources
/operators.py
2,052
4.6875
5
#Python Operators #Operators are used to perform operations on variables and values. #Python divides the operators in the following groups: #Arithmetic operators #Assignment operators #Comparison operators #Logical operators #Identity operators #Membership operators #Bitwise operators #Python Arithmetic Operators #Arithmetic operators are used with numeric values to perform common mathematical operations: #Operator Name Example # + Addition x + y # - Subtraction x - y # * Multiplication x * y # / Division x / y # % Modulus x % y # ** Exponentiation x ** y # // Floor division x // y #Python Assignment Operators #Assignment operators are used to assign values to variables: #Operator Example Same As # = x = 5 x = 5 # += x += 3 x = x + 3 # -= x -= 3 x = x - 3 # *= x *= 3 x = x * 3 # /= x /= 3 x = x / 3 # %= x %= 3 x = x % 3 # //= x //= 3 x = x // 3 # **= x **= 3 x = x ** 3 # &= x &= 3 x = x & 3 # |= x |= 3 x = x | 3 # ^= x ^= 3 x = x ^ 3 # >>= x >>= 3 x = x >> 3 # <<= x <<= 3 x = x << 3 #Python Comparison Operators #Comparison operators are used to compare two values: #Operator Name Example # == Equal x == y # != Not equal x != y # > Greater than x > y # < Less than x < y # >= Greater than or equal to x >= y # <= Less than or equal to x <= y #Python Logical Operators #Logical operators are used to combine conditional statements: #Operator Description Example # and Returns True if both statements are true x < 5 and x < 10 # or Returns True if one of the statements is true x < 5 or x < 4 # not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
true
a32f351dcbec0cb4051e4afaf172d7742ba36836
GiftofHermes/Practice
/Odd or Even.py
996
4.21875
4
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. #Hint: how does an even / odd number react differently when divided by 2? #If the number is a multiple of 4, print out a different message. #Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). #If check divides evenly into num, tell that to the user. If not, print a different appropriate message. first_number = input("Give me a number: ") first_number = int(first_number) second_number = input("Give me a second number: ") second_number = int(second_number) mod_check = first_number % second_number mod4 = first_number % 4 first_word = "" if mod_check == 0: print(first_number, "is divisible by", second_number) first_word = "Also" elif mod_check != 0: print(first_number, "is not divisible by", second_number) first_word = "But" if mod4 == 0: print(first_word, first_number, "is divisible by 4")
true
afb9a0cdb6ab48ef53d67deeeab070acdca2548b
GiftofHermes/Practice
/Birthday JSON.py
940
4.5
4
#load the birthday dictionary from a JSON file on disk, # rather than having the dictionary defined in the program. #Ask the user for another scientist’s name and birthday # to add to the dictionary, and update the JSON file # you have on disk with the scientist’s name. import json with open('Writings/info.json', 'r') as f: info = json.load(f) print('We have birthdate data of') for key in info: print('-{}'.format(key)) person = input("Who's birthday you want to look up?\n") if person in info: print('Birthday of {person} is {bday}'.format(bday= info[person], person= person)) else: print('person you entered is not valid') add = input('Do you want to add another birthdate to our database?\n') if(add == 'Yes'): new_person, new_birthday = input('Enter: as Xxxxx Xxxx,DD/MM/YYYY\n').split(',') info[new_person] == new_birthday with open('Writings/info.json', 'w') as f: json.dump(info,f)
true
02e70f100addb87527434118fb24357083b08b8f
bryanalves/euler-py
/src/001.py
351
4.21875
4
#!/usr/bin/env python """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def euler_1(n): return sum(a for a in range(n) if a % 3 == 0 or a % 5 ==0) if __name__ == "__main__": print(euler_1(1000))
true
112d62993b58f994ff2c9bf977c357b903990a49
AslanDevbrat/Programs-vs-Algorithms
/Problem 1 Square Root of an Integer/Problem 1 Square Root of an Integer.py
1,260
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ def find_floor_sqrt(number,start,stop): #print(start,stop) if number<0: return None if start>stop: # Base case: Since we want floor value we returned stop return stop mid = (start+stop)//2 mid_square = mid**2 if mid_square == number : return mid elif mid_square <number: return find_floor_sqrt(number,mid+1,stop) else: #print('grater') return find_floor_sqrt(number,start,mid-1) temp =find_floor_sqrt(number,0,number) #print(temp) return temp print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") # Edge cases print('Edge Cases:') print("Pass" if (None == sqrt(-1)) else "Fail") print("Pass" if (99380 == sqrt(9876543210)) else "Fail") # In[ ]:
true
30403759ba6885955b176dba5d27d19c1b2b8e93
MaoningGuan/Python-100-Days
/Day01-15/07_exercise_7.py
647
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 列表的相关函数操作 """ list1 = [1, 3, 5, 7, 100] # 添加元素 list1.append(200) print(list1) list1.insert(1, 400) print(list1) # 合并两个列表 # list1.extend([1000, 2000]) list1 += [1000, 2000] print(list1) print(len(list1)) # 获取列表长度 print(list1) # 先通过成员运算判断元素是否在列表中,如果存在就删除该元素 if 3 in list1: list1.remove(3) if 1234 in list1: list1.remove(1234) print(list1) # 从指定的位置删除元素 list1.pop(0) print(list1) list1.pop(len(list1)-1) print(list1) # 清空列表元素 list1.clear() print(list1)
false
f0b07aea5b1d1ab99a53c6024858e4fc6a53f89b
jdevadkar/Python
/Basic Python/calculator.py
1,078
4.21875
4
# this method implement addintion of two number def add(x,y): return x + y # this method implement subtraction of two number def subtract(x,y): return x -y # this method implement multiplication of two number def multiply(x,y): return x * y # this method implement Division of two number def divide(x, y): # handled divide by zero exception try: return x/y except Exception: print("can't divide by zero") # take input from the user print("select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") # take choice as user input choice =input("Enter choice (1/2/3/4): ") # take first number num1 =int(input("Enter first Number:")) # take second number num2 =int(input("Enter Second Number:")) # calling method according to chooice if choice ==1: print(num1,"+",num2, add(num1,num2)) elif choice ==2: print(num1,"-",num2,subtract(num1,num2)) elif choice ==3: print(num1,"*",num2,multiply(num1,num2)) elif choice ==4: print(num1,"/",num2,divide(num1,num2)) else: print("Invalid Input")
true
a4a23f40a60dbdb11f967fa7e636997ec005bb48
99YuraniPalacios/Trigometria
/trigonometry.py
1,208
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 26 13:07:28 2019 @author: jzuluaga """ from enum import Enum import numpy as np PI=3.14159265359 class Unit(Enum): DEG=1 RAD=2 class Angle(object): #Atributos: value, unit #Métodos def __init__(self,value,unit): self.value=value self.unit=unit def convertToDeg(self): if self.unit==Unit.DEG: return self.value else: return self.value*180/PI def convertToRad(self): if self.unit==Unit.RAD: return self.value else: return self.value*PI/180 def FactorialInteger(n): if n<0: raise ValueError("Factorial of a negative number") elif n<=1: return 1 else: return n*FactorialInteger(n-1) def Sin(angle,N=10): """ angle is an object of the class Angle """ sumSeries=0 x=angle.convertToRad() for n in range(N): sumSeries+=(-1)**n*x**(2*n+1)/FactorialInteger(2*n+1) return sumSeries if __name__=="__main__": theta=Angle(15000,Unit.DEG) y=Sin(theta) print(np.sin(theta.convertToRad()))
true
7617a7d2233c7dcaa3e2db5a3b4a20c2703003b8
atkell/learn-python
/exercises/ex31.py
1,873
4.40625
4
# making decisions: now that we have if, else and elif we may start to create scrpipts that decide things! # in this exercise, we'll explore asking a user questions nd then make decisions based on the answer(s) provided print("""You enter a dark room with two doors. Do you go through the door #1 or door #2?""") door = input("If it helps, one door is red and the other is not. > ") # we're saying that the value of the input will be a string and not an integer if door == "1": print("There's a giant bear here eating cheese cake and churros...") print("What will you do about it?") print("1. Take the cake and possibly the churros too.") print("2. Run like hell.") bear = input("What'll it be, boss? > ") # checkout how we're nesting an if-statement inside another if-statement if bear == "1": print("The bear takes one look at you and proceeds to eat your face...") elif bear == "2": print("The bear takes one look at you and chomps down on your leg...") else: print(f"Well, {bear} is possibly the best choice between the two.") print("You run far and away from the bear.") print("The bear continues to enjoy cake and churros...burp!") elif door == "2": print("You stare into the endless abyss at Cthulu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("All your choices are insane, but choose one all the same > ") if insanity == "1" or insanity == "2": print("Your body survives powered by a mind of jello.") print("Good job!") else: print("The insanity rots your eyes into a pool of root bear.") print("Good job!") else: print("You stumble around, tripping over a box of warm donuts and hot chocolate. Good job!")
true
9a5f9d8b5920456ffe5e9a3e1d5c07a5d9262536
atkell/learn-python
/exercises/ex24.py
1,790
4.3125
4
# this exercise is intentionally long and all about building up stamina # the next exericse will be the same. do them both, get them exactly right and do your checks print("Let's practice everything we know thus far...") print('You\'d need to know \'bout escapes with \\ that do:') print('\n newlines and \t tabs') poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print("----------") print(poem) print("----------") five = 10 - 2 + 3 - 6 print(f"This should be five: {five}") def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 # print out the three variables assigned within this function return jelly_beans, jars, crates start_point = 10000 # unpacking the output of the function secret_formula into 3 new variables: beans, jars and crates. remember that the variable names within the fucntion are just that, within the function and not globally available (scope) beans, jars, crates = secret_formula(start_point) # remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) # it's just like an f"" string print(f"We'd have {beans} beans, {jars} jars and {crates} crates.") # remember that the variable is interpreted from the top down, so while the value above this assignment was different, it is about to change start_point = start_point / 10 print("We can also do that this way:") # we're assigning the output of calling the secret_formula, argument of start formula = secret_formula(start_point) # this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
true
3b0e57fb2b13652513fb9d080fb24eaab5a09ad5
atkell/learn-python
/exercises/ex19.py
1,811
4.21875
4
# functions and variables # the takeaway here is scope, mostly that the variable we use in our functions are not connected to variables in our script def cheese_and_crackers(cheese_count, boxes_of_crackers): # here we define our function for ex19 called cheese_and_crackers. it takes 2 arguments, cheese_count and boxes_of_crackers. we could also call these "a" and "b" print(f"You have {cheese_count} cheeses, oh my!") # print format string to include the value assigned to cheese_count print(f"You have {boxes_of_crackers} boxes of crackers.") # print format string to include the value assigned to boxes_of_crackers print("Man, that's enough to party!") # print a string print("Get a blanket and some wine.\n") # print a string print("We may give a function the numbers directly:") # print a string cheese_and_crackers(20, 30) # call the function cheese_and_crackers, passing along 20 and 30 as the values for the two arguments that the function accepts print("Or we may use variables from our script:") # print a string amount_of_cheese = 10 # assign a value of 10 to the variable named amount_of_cheese amount_of_crackers = 50 # assign a value of 50 to the variable named amount_of_crackers cheese_and_crackers(amount_of_cheese, amount_of_crackers) # call the function cheese_and_crackers, passing along the variables amount_of_cheese and amount_of_cracers for the two arguments the function accepts print("We can even do some math (as if you would want that):") # print a string cheese_and_crackers(10 + 20, 5 + 6) # do some math print("And we may combine the two, variables AND math...cue the Keanue woooooaaaaaah:") # print a string cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # call the function cheese_and_crackers, passing along a mix of variables and basic math
true
a9f51c70c1a4979e1fa49a7030c3aeeab59d4b00
atkell/learn-python
/exercises/ex8.py
702
4.3125
4
formatter = "{} {} {} {}" # huzzah! we are introducing the concept of a function # we're just working with integers here print(formatter.format(1, 2, 3, 4)) # now we're working with strings print(formatter.format("one","two","three","four")) # now we're workign with booleans print(formatter.format(True, False, False, True)) # now we're calling a our variable 'formatter' four times (should print out 16 pairs of curly braces) print(formatter.format(formatter, formatter, formatter, formatter)) # now we're printing out a series of strings, using a comma to separate...just like the second line above print(formatter.format( "Try your", "Own Text Here", "Maybe a poem", "About hotdogs and beer" ))
true
4a809d9f88da2db4541509cb254d492d407ac6f1
atkell/learn-python
/exercises/ex3.py
968
4.53125
5
# numbers and math, joy! # + is addition (plus) # - is subtraction (minus) # / is division (slash) # * is multiplication (asterisk) # & is remainder after division (modulous) # < is less than and > is greatter than # <= is less than or equal to and >= is greater than or equal to # remember the order of operations "PEMDAS" or Please Excuse My Dear Aunt Sally or Parenthesis Exponents Multiplication Division Addition and Subtraction print("I will now count my chickens:") print("Hens", 25 + 30 / 6) print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs (before they hatch):") print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("Is it true that 3 + 2 < 5 - 7?") print(3 + 2 < 5 - 7) print("What is 3 + 2?", 3 + 2) print("What is 5 - 7?", 5 - 7) print("Oh, that's why it's False!") print("How about some more?") # true print("Is it greater?", 5 > -2) # true print("Is it greater or equal?", 5 >= -2) # false print("Is it less or equal to?", 5 <= -2)
true
f9f4914364541aafeb58b593b7117926b73e24d8
xuwei0455/design_patterns
/FactoryMethod.py
2,357
4.125
4
# -*- coding: utf-8 -*- """ Factory Method pattern The distinction of Simple Factory and Factory Method is, Simple Factory pattern only offer one factory to produce, otherwise, Factory Method can horizontal scaling by add new Factory. And, when there just one factory, pattern fall back to Simple Factory. When just one concrete product is perhaps returned, factory patterns will lose the existence, you can just create the object directly. """ class AbstractDecoder(object): """ Abstract Product """ pass class UTF8Decoder(AbstractDecoder): """ Concrete Product """ @staticmethod def decode(message): return repr(message.decode('utf-8')) class GBKDecoder(AbstractDecoder): """ Concrete Product """ @staticmethod def decode(message): return repr(message.decode('gbk')) class AbstractEncoder(object): """ Abstract Encoder """ pass class UTF8Encoder(AbstractEncoder): """ Concrete Product """ @staticmethod def encode(message): return repr(message.encode('utf-8')) class GBKEncoder(AbstractEncoder): """ Concrete Product """ @staticmethod def encode(message): return repr(message.encode('gbk')) class AbstractFactory(object): """ Abstract Factory """ pass class DecoderFactory(AbstractFactory): """ Concrete Factory """ def __init__(self, encoding='utf-8'): self.encoding = encoding def decode(self, message): encodings = {"utf-8": UTF8Decoder, "gbk": GBKDecoder} return encodings[self.encoding]().decode(message) class EncoderFactory(AbstractFactory): """ Concrete Factory """ def __init__(self, encoding='utf-8'): self.encoding = encoding def encode(self, message): encodings = {"utf-8": UTF8Encoder, "gbk": GBKEncoder} return encodings[self.encoding]().encode(message) if __name__ == '__main__': utf8_encoder = EncoderFactory("utf-8") print utf8_encoder.encode(u"工厂方法") utf8_decoder = DecoderFactory("utf-8") print utf8_decoder.decode("工厂方法") gbk_encoder = EncoderFactory("gbk") print gbk_encoder.encode(u"工厂方法") gbk_decoder = DecoderFactory("gbk") print gbk_decoder.decode("工厂方法".decode("utf-8").encode("gbk"))
true
24c755ce860af891b453f245740705eb406206e5
gunveen-bindra/OOP
/single_inheritance.py
684
4.21875
4
# Defining base class "Shape". class Shape: # Function to initialize data members. def _getdata(self, length, breadth): self._length = int(input("Enter the Length: ")) self._breadth = int(input("Enter the Breadth: ")) # Defining derived class "Rectangle". class Rectangle(Shape): # Function to calculate area of rectangle. def Calculate_area(self): self.area = self._length * self._breadth print("Area of a rectangle is ", self.area) # Creating object. obj = Rectangle() # Calling function to get the input. obj._getdata(10, 20) # Calling function to get the area of a rectangle. obj.Calculate_area()
true
e25de8b07e2449f5be7cc2df8284cf8815bbd99a
TheFutureJholler/TheFutureJholler.github.io
/module 6-Tuples/tuple_delete.py
321
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 31 20:38:37 2017 @author: zeba """ tup = ('physics', 'chemistry', 1997, 2000); print(tup) del tup print ("After deleting tup : ") print(tup) '''This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more '''
true
7e282a9e3b589c4e641054900b47a060146e07e4
dhanrajsr/hackerrank-practice-exercise
/if_else_ex.py
583
4.5
4
#https://www.hackerrank.com/challenges/py-if-else/problem def find_odd_even(input_number): """ If a number divided by 2 leaves a remainder 1, then the number is odd, if a number divided by 2 leaves a remainder 0, then the number is even. The % helps to calculate the remainder. eg: number % 2 == 1 >> odd number % 2 == 0 >> even """ if input_number % 2 == 1: print(input_number, "is an odd number") elif input_number % 2 == 0: print(input_number, "is an even number") number = int(input()) find_odd_even(number)
true
e9895212e0dbc87a4adc3b412c8635b22877c7b7
lyqtiffany/learngit
/pythonChapter/03_ifElse.py
2,194
4.125
4
#分支语句 #input读取用户的输入,返回字符串类型 # score = int(input('please input score, then press Enter')) # # #分支语句在任何情况下,只会执行其中一个分支 # if score >= 90: # print('优秀') # elif score >= 80: # print('良好') # elif score >= 60: # print('及格') # else: # print('不及格') # if-if-if 与if-elif-elif的区别,多个if之间没有互斥性,所以使用分支语句时,要用if-elif # if True and True: # print('hello') # if 1: #0不打印,''不打印,None不打印,[]不打印,False不打印 # print('hi') #if语句中的语句,必须要缩进,默认缩进4个空格,至少1个空格 #分支语句的嵌套 #如果一个人的年龄大于等于60,并且为男性,称他老先生 # age = 60 # gender = 'male' # if age >=60 and gender == 'male': # print('old gentleman') # if age >= 60: # if gender == 'male': # print('old gentleman') #需求,用户输入手机号,移动(130-150),联通(151-170),电信(171-199) #输入位数不对,提示用户位数错误 #输入非数字,提示有非法字符, #isdigit()方法只有string字符串方法可以用 #变量名的命名尽量规范,文件名的命名也尽量规范 #可以考虑灵活的定义变量 #注意Str和int的区别,input函数默认返回str, isdigit这个方法是字符串的方法,只有str型的对象可以用 #学会自己排查代码问题,在代码中最好加上详细的注释 #代码的顺序也应该考虑清楚,尽量做到先判断大类别,再判断小类别 phoneNumber = input('please input a phone number') if phoneNumber.isdigit(): if len(phoneNumber) == 11: num = int(phoneNumber[0:3]) if 130 <= num <= 150: print('移动号码:', phoneNumber) elif 151 <= num <= 170: print('联通号码:', phoneNumber) elif 171 <= num <= 199: print('电信号码:', phoneNumber) else: print('电话号码不属于三大运营商: ', phoneNumber) else: print('please input the phone number for 11 digits') else: print('only numeric character allowed')
false
8d9b15cf0add58beed7dca83ebbd5f84a0f248b8
joedeller/pymine
/mandel.py
2,074
4.21875
4
#!/usr/bin/python # Joe Deller 2014 # A very simplified version of the Mandelbrot set # Level : Intermediate # Uses : Libraries, variables, lists # I have taken some example code for how to draw the Mandelbrot set from Wikipedia # and made it compatible with the Pi. # This isn't a true fractal program as we can't zoom in # This is another example of where it isn't necessary to understand the code completely # to be able to use it. # If you know that fractals draw patterns in different colors, then # it's just a question of converting the fractal code to draw blocks instead. import mcpi.minecraft as minecraft import mcpi.block as block blockList = [block.STONE, block.DIRT, block.GRASS, block.SAND, block.WOOD, block.WOOD_PLANKS, block.LAPIS_LAZULI_BLOCK, block.COAL_ORE, block.IRON_ORE, block.WOOL, block.GLASS, block.WATER] def chooseBlock(iterations): if (iterations > 10 ): return block.WATER else: return (blockList[iterations]) def drawMandelbrot(xPos, yPos, zPos, imgx, imgy, maxIt, xa, ya, xb, yb): for y in range(imgy): zy = y * (yb - ya) / (imgy - 1) + ya for x in range(imgx): zx = x * (xb - xa) / (imgx - 1) + xa # The next line uses something called a complex, or imaginary number # This is from a fairly advanced set of mathematics z = zx + zy * 1j c = z for i in range(maxIt): if abs(z) > 2.0: break z = z * z + c mc.setBlock(xPos + x, yPos, zPos + y, chooseBlock(i)) mc = minecraft.Minecraft.create() x, y, z = mc.player.getTilePos() mc.setBlocks(x -10, y, z, x + 40, y + 40, z + 50, block.AIR.id) mc.setBlocks(x -10, y - 2, z, x + 40, y + -1, z + 50, block.GRASS.id) # You can try different numbers and see what happens to the shape that is drawn # Try changing by small amounts first. # It's never going to be super detailed in Minecraft, but it does work, sort of drawMandelbrot(x - 10, y - 1, z - 10, 60, 60, 554, -2.0, -1.5, 1.0, 1.5)
true
68677dfb9e403db0d499fbea60a29fb69e3a7bb2
zchq88/mylearning
/设计模式/创建类模式/建造者模式.py
2,715
4.125
4
# 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。(注重构建过程的解耦分离) # 抽象产品 class Car: # 顺序队列 sequence = [] def run(self): for todo in self.sequence: if hasattr(self, todo): _attr = getattr(self, todo) _attr() print("------------------") # 产品1 class BMW(Car): def start(self): print("BMW" + "发动") def stop(self): print("BMW" + "停止") def alarm(self): print("BMW" + "鸣笛") def engineBoom(self): print("BMW" + "引擎") # 产品2 class Benz(Car): isAlarm = False def start(self): print("Benz" + "发动") def stop(self): print("Benz" + "停止") def alarm(self): if self.isAlarm: print("Benz" + "鸣笛") def engineBoom(self): print("Benz" + "引擎") # 抽象建造者 class CarBulider(Car): def set_sequence(self, _set_sequence): self.sequence = _set_sequence def BuliderCar(self): pass # 具体建造者1 class BMWBulider(CarBulider): def BuliderCar(self): Product = BMW() Product.sequence = self.sequence return Product # 具体建造者2 class BenzBulider(CarBulider): def BuliderCar(self): Product = Benz() Product.sequence = self.sequence return Product # 导演类 class Director: _BMWBulider = BMWBulider() _BenzBulider = BenzBulider() _sequence1 = ["start", "alarm", "engineBoom", "stop"] _sequence2 = ["start", "stop"] def getBMW1(self): self._BMWBulider.set_sequence(self._sequence1) return self._BMWBulider.BuliderCar() def getBMW2(self): self._BMWBulider.set_sequence(self._sequence2) return self._BMWBulider.BuliderCar() def getBenz1(self): self._BenzBulider.set_sequence(self._sequence1) return self._BenzBulider.BuliderCar() def getBenz2(self): self._BenzBulider.set_sequence(self._sequence2) return self._BenzBulider.BuliderCar() if __name__ == "__main__": director = Director() BMW1 = director.getBMW1() BMW1.run() BMW2 = director.getBMW2() BMW2.run() Benz1 = director.getBenz1() # Benz.isAlarm = True Benz1.run() Benz2 = director.getBenz2() Benz2.run() # 要点1:建造者模式使场景类不关心组成过程。 # 要点2:扩展建造过程不对模块产生影响(建造过程封装解耦) # 要点3:适用于相同方法不同执行顺序效能不同的场景。 # 要点4:多品类合成方法不同效能不同的场景
false
36761b573cf0907ef8fff401966de660a6671975
zhchwolf/pylearn
/python_code/frist.py
401
4.59375
5
#!/usr/bin/env python # -*- coding: utf-8 -*- # calculate the area and circumference of a circle from its radius # Step 1: prompt for a radius # Step 2: apply the area formula # Step 3: print out the results import math radiusString = input('Enter radius of circle:') radiusInt = int(radiusString) circumference = 2*math.pi*radiusInt print (circumference) area = math.pi*radiusInt ** 2 print (area)
true
2c98e141be2c7fbebaf03d61928af8ce8c7a659e
zhchwolf/pylearn
/python_code/solution01.py
1,020
4.28125
4
#!/usr/bin/python # -*- coding:UTF-8 -*- # python 入门经典以解决计算问题为导向的python编程实践 # a1 = input('input a number:') a1 = 88 a2 = (( int(a1) + 2 )*3 -6 )/3 print ("((number+2)*3 -6)/3 The result is ",a2) ''' 我要去圣艾夫斯,我碰到一个男人,他有7个妻子, 每个妻子有7个麻袋,每个麻袋有7只猫,每只猫有7只小猫, 一共有多少人和物要去圣艾夫斯。 ''' all_object = 1 + 7 + 7*7 +7*7*7 + 7*7*7*7 print ('一共有',all_object,'人和物要去圣艾夫斯') # Draw a 6-pointed star import turtle turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.right(120) turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.right(120) turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.right(120) turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.right(120) turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.right(120) turtle.forward(50) turtle.right(-60) turtle.forward(50) turtle.done()
false
2b14e9c509c5d2e3f6cae1dd81eac27d8313d61c
GriffGeorgiadis/python_files
/decode.py
2,128
4.21875
4
#Griffin Georgiadis #Write a program that uses a dictionary to assign “codes” to each letter of the alphabet #set global variables ENCRYPT = 1 DECRYPT = 2 #start main function def main(): try: #print menu print('Welcome to my encryption program, You can choose to encrypt a file or decrypt an encrypted file') print('Would you like to: \n 1 - Encrypt a file \n 2 - Decrypt a file ') user = input('Your choice?') #validate user input while user != str(ENCRYPT) and user != str(DECRYPT): print('Pick 1 or 2') user = input('Your choice?') #get input file one_user = input('Enter the name of the input file: ') #open file to read infile = open(one_user, 'r') #open codes file code_file = open('Codes.txt', 'r') #start dictionary code = {} #put file in dictionary for line in code_file: line = line.rstrip('\n') data = line.split() key = data[0] value = data[1] code[key] = value #call other functions if user == str(ENCRYPT): encrypt(code, infile) print("Wrinting encrypted data to file") else: decrypt(code, infile) print("Writing decryption to file") infile.close() #get excption error except IOError: print("Can't find file") #start encrypt file def encrypt(code, infile): user = input("Enter file name: ") outfile = open(user, 'w') for line in infile: for ch in line: if ch in code: outfile.write(code[ch]) else: outfile.write(ch) outfile.close() #start decrypt file def decrypt(code, infile): for line in infile: for ch in line: if ch in code: print(code[ch], end = '') else: print(ch, end = '') #close main main()
true
2f3e73af97ec226ddb0da068830b2de7b072facb
dandenseven/week1
/day2/Day2_exercises/exercises/1-core-functions/define_functions.py
433
4.34375
4
#print allows you to output to your console what you want to print. print("this is my string") print(" 2 + 2 equals 4 this is the answer.") a = 9 * 9 relax = ("meditating is good for your mind") print( a ) print("meditating", a, "times is good for your mind") #input lets you ask a use for some text to input, it tells you stop #and wait for the user to key in data name = input("Enter your name" + " ") print("My name is", name)
true
6e2a7e74c4ef4859eb18fd571044e12bde07a115
jesse-bro/Data_Structure_Problems
/Compress_String.py
715
4.25
4
### Method to perform basic string compression using the ### counts of repeated characters. String only contains ### uppercase and lowercase letters (a-z). def stringCompress(string): compressed = "" count = 0 for i, ch in enumerate(string[:-1]): if ch != string[i+1] or i+1 >= len(string): compressed += "" + ch + str(count) count = 0 count+=1 # Last letter compressed += "" + string[-1] + str(count) if len(compressed) < len(string) : return compressed else: return string sentence = "aabbbbccceeeefffgggh" test = "aaeeegggdgjkloi" print(stringCompress(sentence)) print(stringCompress(test))
true
f792c60fca40895c5b85f7b35db15d79e2a5ae8a
PacktPublishing/Python-3-Project-based-Python-Algorithms-Data-Structures
/Section 03/4_strings_2_notes.py
1,446
4.6875
5
# We can use string concatenation and add strings # together message = "Welcome to the course" name = "Mashrur" print(message + name) # We can add an empty space in there too print(message + " " + name) # Strings are sequences of characters which are indexed # We can index into a string by using square bracket notation movie_name = "Interstellar" print(movie_name[0]) # This will print 'I' which is at index 0 print(movie_name[1]) # This will print 'n' which is at index 1 print(movie_name[11]) # This will print 'r' which is the last character print(movie_name[-1]) # This will print 'r', last character print(movie_name[-2]) # This will print 'a', second to last character # We can use slicing to select portions of the string print(movie_name[0:5]) # This will print 'Inter' print(movie_name[:5]) # We can leave the starting 0 out if we start at # at the beginning to get 'Inter' as well print(movie_name[5:]) # This will print 'stellar', begin index to end print(movie_name[:]) # This will print "Interstellar", begin to end print(movie_name[5:9]) # This will print 'stel' # You can specify step size as optional third argument print(movie_name[5:9:2]) # This will print 'se', moving forward by # 2 steps instead of the default 1 print(movie_name[::2]) # This will print "Itrtla" print(movie_name[::-1]) # This will reverse the string and print # 'ralletsretnI'
true
2670d9d8d6c53b26330b4983790bef744c24e8c9
PacktPublishing/Python-3-Project-based-Python-Algorithms-Data-Structures
/Section 04/12_merge_sort_demo_starter.py
454
4.125
4
def merge_sorted(arr1,arr2): print("Merge function called with lists below:") print(f"left: {arr1} and right: {arr2}") sorted_arr = [] i, j = 0, 0 print(f"Left list index i is {i} and has value: {arr1[i]}") print(f"Right list index j is {j} and has value: {arr2[j]}") return sorted_arr # xxxxxxxxxxxxxxxx Program Execution xxxxxxxxxxxxxxxx l1 = [1,4,6,8,10] l2 = [2,3,5,7,8,9] print(f"Un-merged list: {merge_sorted(l1,l2)}")
true
578df8e4753a6be6252f68cead393522cd4d1559
ramonsolis159/csc1010
/csc1010_Pycharm_Projects_Python/hmwk_4.py
849
4.34375
4
# Ramon Montoya # 10/08/2018 # This program is for an assignment. movie = "I am currently watching a movie!" print(movie) type = "It is a action and scifi movie." print(type) type = "It is pretty good!" print(type) name = "eric" message = "Hello " + name.title() + ", would you like to learn Python today?" print(message) print(name.upper()) print(name.lower()) print(name.title()) print('Cristiano Ronaldo once said, "Im living a dream I never want to wake up from."') famous_person = "Cristiano Ronaldo" message = famous_person + ' once said, "Im living a dream I never want to wake up from."' print(message) person = "\n\t nick " print(person) print(person.lstrip()) print(person.rstrip()) print(person.strip()) print(5 + 3) print(12 - 4) print(4 * 2) print(16 / 2) fav_number = 18 message = "My favorite number is " + str(fav_number) print(message) import this
true
ec895f5c728871d691c3816cb53cc16f633818d3
priyankapiya23/BasicPython
/String/reverse_string.py
788
4.1875
4
#reverse string string=input("enter any string") print('reverse of string is using methhod') print(string[::-1]) # extended slice syntax '''Explanation : Extended slice offers to put a “step” field as [start,stop,step], and giving no field as start and stop indicates default to 0 and string length respectively and “-1” denotes starting from end and stop at the start, hence reversing string.''' # find in reverse a=str(input("enter your string")) l=len(a) for i in range(l-1,-1,-1):#it returns the no. of elements based on test condition minus starting position print(a[i],end="") #print string b=str(input("enter your string")) l=len(b) for i in range(0,l,1):#it returns the no. of elements based on test condition minus starting position print(a[i],end="")
true
24601bddd6d86b6233380e3b65011276164373ac
ahmadabdullah407/python-basics
/stringlisttupleindexcountconcatinaterepeat.py
1,460
4.1875
4
# # Concatination(Addition of lists)(+): # fruit = ["apple","orange","banana","cherry"] # print([1,2] + [3,4]) #Concatination # print(fruit+[6,7,8,9]) #Concatination # # Repitition(Multiplication of lists)(*): # print((fruit + [0,1])*4) #Repitition (Use parenthisis) # # a = ['first'] + ("second","green") # Error List and string/tuple cannot be concatinated together # # Count method: # a = "I have had an apple on my desk before!" # print(a.count("e")) #Counts characters # print(a.count("ha")) #Counts substrings too # z = ['atoms', 4, 'neutron', 6, 'proton', 4, 'electron', 4, 'electron', 'atoms'] # print(z.count("4")) # count also works on list but counts items not characters # print(z.count(4)) # print(z.count("a")) # print(z.count("electron")) # Index: music = "Pull out your music and dancing can begin" #Index works on strings as well as lists bio = ["Metatarsal", "Metatarsal", "Fibula", [], "Tibia", "Tibia", 43, "Femur", "Occipital", "Metatarsal"] print(music.index("m")) # tells the index where m is present starts from 0 print(music.index("your")) # tells index at 1st character of substring print(bio.index("Metatarsal")) # index always gives 1st/left most item it does not tell location of same item coming after print(bio.index([])) # also searches for empty list print(bio.index(43)) # also searches integer items # print(bio.index('great')) # gives error if item not present # print(music.index("z")) # also gives error for character
true
d929cfc88e59978e8add9795e5513ce6c73e11c6
danielnwankwo/control_flow
/control_flow.py
1,149
4.34375
4
# control flow # if statements # syntax: if then conditions age = 15 # will run because conditions have been met. without the = then it will not run as 15 does not satisfy either statement # by itself if age > 15: print("Thank You. You may watch this movie ") elif age <= 15: print("sorry you are not the required age to watch this movie ") else: print("oops something has gone wrong, please try again later ") # create program using control flow with if, elif and else # using operators == >= # check age restrictions before selling tickets # U, PG, 12, 15, 18 # else block should ensure to display message if other conditions do not match age = 21 if age >= 4: print("Thank you, you may watch U rated movie") elif age >= 10: print(" Thank you, you watch the PG movie but you will need a guardian") elif age >= 12: print("thank you, you may watch this 12 rated movie") elif age >= 15: print("thank you, you may watch this 15 rated movie") elif age >= 18: print("Thank you, you may watch this 18 rated movie") else: print("oops something has gone wrong, please try again") # too messy, shorted later
true
ae06fa14c956784541cffec401aa4d56817782e3
jimjshields/interview_prep
/interview_cake/19.py
601
4.15625
4
class StackQueue(object): """A queue implemented with two stacks.""" def __init__(self): self.enqueue_stack = [] self.dequeue_stack = [] def enqueue(self, item): self.enqueue_stack.append(item) def dequeue(self): if self.dequeue_stack == []: while len(self.enqueue_stack) > 0: self.dequeue_stack.append(self.enqueue_stack.pop()) return self.dequeue_stack.pop() q = StackQueue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) q.enqueue(5) print q.enqueue_stack print q.dequeue_stack print q.dequeue() print q.dequeue() print q.dequeue() print q.dequeue() print q.dequeue()
false
7494a5d939e68da759c450b3eeda9c80db3382d3
jimjshields/interview_prep
/hashing/map_class.py
2,508
4.1875
4
class Map(object): """Represents a map/assoc. array/dictionary ADT.""" def __init__(self): """Initializes w/ an empty list of keys and empty list of values.""" self.dict = {} def add_key_val_pair(self, key, val): """Adds a key/value pair to the map. Replaces value if key already present.""" self.dict[key] = val def get_val(self, key): """Returns a value for a given key if available. Raises KeyError if not.""" return self.dict[key] def remove_key(self, key): """Deletes a key/value pair for a given key if available. Raises KeyError if not.""" del self.dict[key] # my_map.add_key_val_pair(1, 2) # my_map.add_key_val_pair(1, 3) # my_map.add_key_val_pair(1, 4) # my_map.add_key_val_pair(3, 2) # print my_map.dict # print my_map.get_val(1) # my_map.remove_key(3) # print my_map.dict class Map_2(object): """Represents a map/assoc. array/dictionary ADT.""" def __init__(self): """Initializes w/ an empty list of keys and empty list of values.""" self.keys = [] self.values = [] def add_key_val_pair(self, key, val): """Adds a key/value pair to the map. Replaces value if key already present.""" if key in self.keys: self.values[self.keys.index(key)] = val else: self.keys.append(key) self.values.append(val) def get_val(self, key): """Returns a value for a given key if available. Raises KeyError if not.""" return self.values[self.keys.index(key)] def remove_key(self, key): """Deletes a key/value pair for a given key if available. Raises KeyError if not.""" index = self.keys.index(key) del self.keys[index] del self.values[index] # my_map_2.add_key_val_pair(1, 2) # my_map_2.add_key_val_pair(1, 3) # my_map_2.add_key_val_pair(1, 4) # my_map_2.add_key_val_pair(3, 2) # print zip(my_map_2.keys, my_map_2.values) # print my_map_2.get_val(1) # my_map_2.remove_key(3) # print zip(my_map_2.keys, my_map_2.values) from timeit import timeit import random my_map = Map() for _ in xrange(10000): my_map.add_key_val_pair(''.join([chr(random.choice(list(xrange(97, 123)))) for _ in xrange(6)]), 1) my_map_2 = Map_2() for _ in xrange(10000): my_map_2.add_key_val_pair(''.join([chr(random.choice(list(xrange(97, 123)))) for _ in xrange(6)]), 1) # print my_map.dict # print zip(my_map_2.keys, my_map_2.values) print timeit('for key in my_map.dict.keys(): my_map.get_val(key)', 'from __main__ import my_map', number=10) print timeit('for key in my_map_2.keys: my_map_2.get_val(key)', 'from __main__ import my_map_2', number=10)
true
1b5a0da81fab26681c9cab11fa45d5586d06cee2
jimjshields/interview_prep
/practice/19_shell_sort.py
959
4.125
4
# Shell sort - aka diminishing increment sort # Improves on insertion sort - breaks original list into smaller sublists # Each of which is sorted using insertion sort # Big O: # Worst case: O(n^2) # Avg. case: Depends on gap selection # Best case: O(nlog(n)) # Aux. space: O(1) def shell_sort(a_list): sub_list_count = len(a_list) // 2 while sub_list_count > 0: for start_position in xrange(sub_list_count): gap_insertion_sort(a_list, start_position, sub_list_count) print 'After increments of size {0}, the list is {1}.'.format(sub_list_count, a_list) sub_list_count //= 2 def gap_insertion_sort(a_list, start, gap): for i in xrange(start + gap, len(a_list), gap): current_value = a_list[i] position = i while position >= gap and a_list[position - gap] > current_value: a_list[position] = a_list[position - gap] position -= gap a_list[position] = current_value a_list = list(range(100)[::-1]) shell_sort(a_list) print a_list
true
a629d6a370a39826e03748b571c263ff43c12d84
code-in-public/leetcode
/best-time-to-buy-and-sell-stock/test.py
812
4.28125
4
#!/usr/bin/env python3 import unittest import solution """ Example 1: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0. """ class TestMethods(unittest.TestCase): def test_profitable(self): sol = solution.Solution(); prices = [7,1,5,3,6,4] self.assertEqual(sol.maxProfit(prices), 5) def test_no_profit(self): sol = solution.Solution(); prices = [7,6,4,3,1] self.assertEqual(sol.maxProfit(prices), 0) if __name__ == '__main__': unittest.main()
true
92f058ec4f9d59f583e42839a757d604ba961bb7
Techwrekfix/Starting-out-with-python
/chapter-3/4. Roman_numerals.py
773
4.21875
4
#This program displays the roman numeral version #of a number entered by a user #Assigning the numeric numbers to a variable one = 1 two = 2 three = 3 four = 4 five = 5 six = 6 seven = 7 eight = 8 nine = 9 ten = 10 #Prompting the user to enter a numeric number number = int(input("Enter a numeric number: ")) #Displaying the roman numeral version of the #numeric number entered if number == one: print("I") elif number == two: print("II") elif number == three: print("III") elif number == four: print("IV") elif number == five: print("V") elif number == six: print("VI") elif number == seven: print("VII") elif number == eight: print("VII") elif number == nine: print("IX") elif number == ten: print("X") else: print("ERROR")
true
9d76d0b71433637d8e740f45faa894bc5c96c32c
Techwrekfix/Starting-out-with-python
/chapter-8/Sum_of_digits_in_a_string.py
560
4.34375
4
#This program displays the sum of digits in a string #ALGORITHM in pseudocode #1. get a series of single-digit number from the user # set total accumulator to zero #2. for every digit in user input: # convert digit to integer # add the digit to the accumulator #3. Display total #CODE def main(): user_input = input('Enter a series of single-digit number: ') total = 0 #accumulator for digits in user_input: digits = int(digits) total += digits print('The total of',user_input,'is:',total) main()
true
1f55026aa62f17b9449bfa7315dba35209d5a220
Techwrekfix/Starting-out-with-python
/chapter-2/3. land_calculation.py
385
4.125
4
#This program calculates the number of acres in a tract total_square_feet = float(input('Please enter the total ' \ 'square feet of the tract' \ 'of land: ')) number_of_acres = total_square_feet / 43560 #Displaying results print('The number of acres in the tract of land is:' \ ,format(number_of_acres, '.1f'))
true
f3d2f5fc63aa813d13150d89f80d71947b478863
Techwrekfix/Starting-out-with-python
/chapter-2/8. tip_tax_total.py
541
4.15625
4
#This program displays the total #cost of a meal purchased at a restaurant meal_charge = float(input('Enter the cost of the meal: ')) tip = 0.18 * meal_charge #calculating 18% tip of the meal sales_tax = 0.07 * meal_charge #calculating 7% sales tax of the meal total = meal_charge + tip+sales_tax #calculating total cost of the meal #Displaying results print('The 18% tip = $',format(tip, '.2f'),sep='') print('The 7% sales tax = $',format(sales_tax, '.2f'),sep='') print('The total cost of the meal = $',format(total,'.2f'),sep='')
true
147900a7dba4bcf3dcf61da7595d1b8dee7a7612
Techwrekfix/Starting-out-with-python
/chapter-6/2. File_head_display.py
618
4.28125
4
#File head display program def main(): #creating variables for max lines and number of line in the file max_line = 5 count_lines = 0 #ask user for file name file_name = input('Enter the name of your file: ') #open the file user_file = open(file_name,'r') #read the first line in the file line = user_file.readline() count_lines += 1 #using a while loop to read the lines in the file while line != '' and count_lines <= max_line: count_lines += 1 print(line.rstrip('\n')) line = user_file.readline() user_file.close() main()
true
c70c9318953230c1f0816dff97a67a720fa960a4
Techwrekfix/Starting-out-with-python
/chapter-5/6. Calories_from_fat_and_carbohydrates.py
724
4.28125
4
#This program calculates calories from a fat def main(): fat_grams = float(input('Enter the number of fat grams: ')) carb_grams = float(input('Etner the number of carb_grams: ')) fat_calories = calculate_fat_calories(fat_grams) carb_calories = calculate_carb_calories(carb_grams) #Displaying fats calories from fat and carbohydrates print('\nThe calories from fat is: ',fat_calories,'calories \nThe '\ 'calories from carbohydrate is: ',carb_calories,'calories') def calculate_fat_calories(fat_grams): calories_from_fat = fat_grams * 9 return calories_from_fat def calculate_carb_calories(carb_grams): calories_from_carb = carb_grams * 4 return calories_from_carb main()
true
f84509cdcded11e6a1b53af3bbf930437dd0f3e3
Techwrekfix/Starting-out-with-python
/chapter-9/1. course_Information.py
1,419
4.40625
4
#This proram is about course information #Algorithm in pseudocode #1.The create_dictionary function creates three different # dictionaries(Room_number,Instructor and Meeting_time) and # returns a refrence to the dictionaries # #2. Inside the main fucntion: # 1.ask user enter a course number # 2.if user input is in room_number and instructor and meeting_time: # displays their values in the dictionary #CODE def create_dictionary(): room_number = {'CS101':3004,'CS102':4501,'CS103':6755,'NT110':1244, 'CM241':1411} instructor = {'CS101':'Haynes','CS102':'Alvarado','CS103':'Rich', 'NT110':'Burke','CM241':'Lee'} meeting_time = {'CS101':'8:00 a.m.','CS102':'9:00 a.m.', 'CS103':'10:00 a.m.','NT110':'11:00 a.m.', 'CM241':'1:00 p.m.'} return room_number,instructor,meeting_time def main(): room_number,instructor,meeting_time = create_dictionary() course_number = input('Please enter a course number: ') #determine if course number is in dictionary if course_number in room_number and instructor and meeting_time: print('Room Number:',room_number[course_number]) print('Instructor:',instructor[course_number]) print('Meeting Time:',meeting_time[course_number]) else: print('Entry not found') main()
true
57f08ee56cff62dd8570f2460253461bc550d4ae
Techwrekfix/Starting-out-with-python
/chapter-4/4. Distance_traveled.py
396
4.53125
5
#This program displays distance travelled in miles speed = int(input('Enter the speed of the vehicle in mph: ')) time = int(input('Enter the hours traveled by the vehicle: ')) #Creating a table print('Hour \t Distance Traveled') print('--------------------------') #Using a loop to display the table for hours in range(time): distance = speed *(hours+1) print(hours+1,'\t',distance)
true
661837cd7886c47de2847f854b1a86cd6ab8dadb
Techwrekfix/Starting-out-with-python
/chapter-3/5. Mass_and_weight.py
447
4.4375
4
#This program measure the weight of objects #Getting the mass of an object from user mass_of_object = float(input("Enter the mass of the" \ " mass of the object: ")) #Calculating the weight: weight = mass_of_object * 9.8 print("\nThe weight of the object is N", format(weight,'.2f'),sep='') if weight > 500: print("\nThis object is too heavy") elif weight < 100: print("\nThis object is too light")
true
9452fa853c8b47b7493a9c76c1aa5c851b0b7d06
Latinaheadshot/DevF
/semana1-3/semana2/lesson1/sets.py
1,858
4.65625
5
# set de enteros set_enteros = {1, 2, 3} # print(set_enteros) # set de diferentes tipos de datos set_diferentes_tipos = {1.0, "Hello", (1, 2, 3)} # print(set_diferentes_tipos) # set no pueden tener elementos repetidos set_numeros_repetidos = {1, 2, 3, 4, 3, 2} # print(set_numeros_repetidos) # set no pueden tener numeros mutables como listas o diccionarios como elementos # mutable_set = {1, 2, [3, 4]} # operaciones con sets # initialize my_set # print(my_set) # you will get an error # TypeError: 'set' object does not support indexing # my_set[0] my_set = {1, 3} def add_element_to_set(): # add an element # my_set.add(2) # print "element added", my_set # add multiple elements # my_set.update([2, 3, 4]) # print "set updated with several elements at once", my_set # # # add list and set my_set.update([4, 5], {1, 6, 8}) print "set updated using a list", my_set # add_element_to_set() def delete_set_element(): # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element my_set.discard(4) print(my_set) # remove an element my_set.remove(16) print(my_set) # discard an element # not present in my_set my_set.discard(2) print(my_set) # remove an element # not present in my_set # you will get an error. # Output: KeyError: 2 # my_set.remove(2) # delete_set_element() def pop_element_from_set(): # initialize my_set # Output: set of unique elements my_set = set("HelloWorld") print(my_set) # pop an element # Output: random element print(my_set.pop()) # clear my_set # Output: set() my_set.clear() print(my_set) # pop_element_from_set() # pop_element_from_set() setA = {1, 2, 3, 4, 5} setB = {4, 5, 6, 7, 8} inter = setA.intersection(setB) print inter
false
6c11ae57279bbbaa47daa26e5e56ea85830c3aea
Rohit-iitr/pythonBasics
/PythonProblems/G4G/RotateString.py
1,078
4.125
4
#User function Template for python3 #Function to check if a string can be obtained by rotating #another string by exactly 2 places. def isRotated(str1,str2): flagAntiCloclwise = False flagCloclwise = False if (len(str1)>1 and len(str2)>1): count =0 index =2 y='' while count< len(str1): if index+count<len(str1): y=y+str1[index+count] else: y=y+str1[index+count-len(str1)] count+=1 #index+=1 if y==str2: flagCloclwise=True count =0 index =-2 y='' while count< len(str1): if index+count<len(str1): y=y+str1[index+count] else: y=y+str1[index+count-len(str1)] count+=1 #index+=1 if y==str2: flagAntiCloclwise=True return int(flagAntiCloclwise or flagCloclwise) print(isRotated('AB','AB'))
true
46bae5b3aa0c1bb55b3cbaf6c9685a61c1b8d4a2
AustinPenner/ProjectEuler
/Problems 26-50/euler046.py
1,065
4.1875
4
def is_prime(n): if n < 2: return False # if integer is 2 or 3, then True elif n == 2: return True elif n == 3: return True # if integer is even, then False elif n % 2 == 0: return False # only check integers 3 through sqrt(n) + 1, skipping even numbers for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False return True def golbach_other(num): # check if number is sum of prime and twice a square for i in range(2, num): for j in range(1, num): numcheck = i + 2*(j**2) if numcheck > num: break elif not is_prime(i): pass elif numcheck == num: return True return False # Loop through odd composite numbers. Try writing this as the sum of # a prime and two times a square. If no valid sum, return the value. this_num = 9 while True: if ((this_num - 1) % 100 == 0): print this_num if is_prime(this_num): this_num += 2 elif golbach_other(this_num): this_num += 2 else: print("The first odd composite that violates Golbachs other conjecture is " + str(this_num)) break # Answer is 5777
true
8a33ecebf55c86cc08bcfbf5e080c6f8fdf1952a
matheuss3/rpg
/src/phases/aventura.py
2,132
4.1875
4
def aventura(): acao = '' grito = '' nome = '' print('Você esta de olhos fechados. Não sente sua cama, todas as sensações que seu corpo lhe devolve é a sensação de estar deitado na areia molhada.') print('Não esta no conforto da sua cama. Não sente seu travesseiro.') print('"Aonde estou?" - Você se pergunta. Mas é impossível saber sem abrir os olhos. O que você fará?') acao = input('Digite a ação "abrir os olhos".\n') while acao != 'abrir os olhos': acao = input('Você não abriu os olhos ainda. Digite a ação abrir os olhos para continuar.') print('Você abre os olhos e começa a observar o que esta a sua volta. Tudo o que vê é um bosque.') print('"Uma floresta... Tropical?" - Você se pergunta. Mas nunca foi muito bom em reconhecer os biomas.') print('Tenta pensar no que fazer, mas nada lhe passa pela sua mente. Contudo, sem que percebesse, começa a andar pela floresta.') print('Não se passa muito tempo até que percebe que esta andando sozinho. Sem querer. Como se algo lhe puxasse.') print('"Que diabos? Como paro?" - Você gritava, em desespero completo.') print('Tudo que se lembrava do dia anterior, era de ter ido dormir. Então por que estava ali? O pânico toma conta de ti, então começa a gritar mais alto.') grito = input('O que você esta gritando?\n') print('%s não muda nada.' %(grito)) grito = input('O que você esta gritando?\n') print('Mas gritar %s não trás ninguém para te salvar.' %(grito)) print('Você esta tremendo e suando muito. Mas nada muda. Até que um precipicio aparece em sua frente.') print('Quando você avista o precipicio, suas pernas começam a correr. Você se debate, mas nada muda. Até que para, a três passos do precipicio.') print('Uma risada aterrorizante ecoa do fundo do precipicio. E você assustado, grita de volta, em pânico.') nome = input('"Qual o seu nome, meu caro?" - Pergunta a voz. Curiosa sobre quem estaria ali.\n') print('Entendo, caro %s') return True if __name__ == '__main__': import sys sys.exit(aventura())
false
ad7efabdd3d075a7c1f7c50d7dab560792dc02be
johnmaster/Leetcode
/206.翻转链表/reverseList.py
780
4.125
4
""" 执行用时 :28 ms, 在所有 python3 提交中击败了99.85%的用户 内存消耗 :13.8 MB, 在所有 python3 提交中击败了99.62%的用户 双指针迭代 申请两个指针,第一个指针叫pre,最初指向None。 第二个指针叫cur,最初指向head,然后不断遍历cur。 每次迭代到cur,都将cur的next指向pre,然后pre和cur前进一位 都迭代完了(cur变成None),pre就是最后一个节点。 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): pre, cur = None, head while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
false
20293522be0563364f8568d5dc9973f8a0a7afec
ljdutton2/karma_coin
/fanquiz.py
2,716
4.3125
4
score = 0 def multiple_choice(): global score answer=input("1. THIS country was formerly known as Yugoslavia: a) Romania b) Russia c) The Netherlands d) Montenegro ") if answer == ("d"): score += 1 print(" :) ") print(f"Current Score: {score}") else: print(" :( the correct answer is d) Montenegro") def multiple_choice_2(): global score answer_2=input("2. Which is the only sea without any coasts? a) Adriatic Sea b) Red Sea c) Sargasso Sea d) Mediterranean sea ") if answer_2 == ("c"): score += 1 print(" :) ") print(f"Current Score: {score}") else: print(" :( the correct answer is c) The Sargasso Sea") print(f"Current Score: {score}") def bool_question(): global score answer_3=input("3. Voted the World's 'most dissapointing landmark' Plymouth Rock is located in Maine. Enter 1 for True and 0 for False. ") if answer_3 == "1": print(" :( the correct answer was False, Plymouth Rock is in Massachussets ") print(f"Current Score: {score}") elif answer_3 == "0": score += 1 print(" :) ") print(f"Current Score: {score}") else: print("Please enter a proper response") def bool_question_2(): global score answer_4=input("4. The 'A' in UAE stands for Arab. Please enter 1 for True and 0 for False. ") if answer_4 == "1": score += 1 print(" :) ") print(f"Current Score: {score}") else: print(" :( the correct answer was True") print(f"Current Score: {score}") def num_question(): global score answer_5=input("5. What is the furthest western country in Europe? Please enter your response here: ") if answer_5 == ("portugal"): score += 1 print(" :) ") print(f"Current Score: {score}") else: print(" :( the correct answer was portugal") print(f"Current Score: {score}") def num_question2(): global score answer_5=input("5. Which mountain range means 'House of Snow' in Sanskrit? Please enter your response here: ") if answer_5 == ("himalaya"): score += 1 print(" :) ") print(f"Current Score: {score}") else: print(" :( the correct answer was himalaya") print(f"TOTAL SCORE: {score}") def again(): repeat= input("Would you like to play again? y/n") if repeat == ('y'): run_quiz() else: print("Thank you for playing!!") def run_quiz(): multiple_choice() multiple_choice_2() bool_question() bool_question_2() num_question() num_question2() again() run_quiz()
false
93d61b297e961a37a9b97043825b0219e9516f40
HeapOfPackrats/AoC2017
/day3.py
2,556
4.34375
4
#http://adventofcode.com/2017/day/3 import sys def main(argv): #get input, otherwise prompt for input if (len(argv) == 2): inputSquare = int(argv[1]) else: print("Please specify an input argument (day3.py [input])") return #find Manhattan Distance from square # specified by input to square 1 at the center #refer to url at top for diagram #check which layer box the input square resides in n = int(0.5*((inputSquare-1)**0.5 + 1)) #calc box geometry #note: minVal doesn't actually appear on any given layer and is just for calculating geometry #note: maxVal overlaps lowerRight minVal = (2*n-1)**2 maxVal = (2*n+1)**2 lowerRight = minVal upperRight = minVal + 2*n upperLeft = minVal + 4*n lowerLeft = minVal + 6*n midRight = lowerRight + n midTop = upperRight + n midLeft = upperLeft + n midBottom = lowerLeft + n #check which side of the box the square is on, find distance to middle of side if lowerRight < inputSquare <= upperRight: toCenter = "left" distance = midRight - inputSquare if distance < 0: initialMove = "down" distance *= -1 elif distance > 0: initialMove = "up" else: initialMove = "none" elif upperRight < inputSquare <= upperLeft: toCenter = "down" distance = midTop - inputSquare if distance < 0: initialMove = "right" distance *= -1 elif distance > 0: initialMove = "left" else: initialMove = "none" elif upperLeft < inputSquare <= lowerLeft: toCenter = "right" distance = midLeft - inputSquare if distance < 0: initialMove = "up" distance *= -1 elif distance > 0: initialMove = "down" else: initialMove = "none" elif lowerLeft < inputSquare <= maxVal: toCenter = "up" distance = midBottom - inputSquare if distance < 0: initialMove = "left" distance *= -1 elif distance > 0: initialMove = "right" else: initialMove = "none" #print total steps if initialMove == "none": print("{} step(s) {}. Total of {} steps".format(n, toCenter, distance+n)) else: print("{} step(s) {}, then {} step(s) {}. Total of {} steps".format(distance, initialMove, n, toCenter, distance+n)) if __name__ == "__main__": main(sys.argv)
true
0d82e7f58d632c077b461b22b5bfddaa0aa5e592
Gamesu/MisionTIC_Python
/Scripts Sin Terminar/ventas.py
1,707
4.125
4
""" Modulo Module ventas Funciones para el manejo de ventas mensuales con matrices Oscar Estrada Suazo Junio 10-2021 """ # Definición de Funciones #====================================================================== # E S P A C I O D E T R A B A J O A L U M N O # ==================================================================== def leer_numero_empleados(): codigosEmpleados = input("\n --- Ingrese los codigos de los empleados separadados por comas:") codigosEmpleados = codigosEmpleados.split(",") return codigosEmpleados def leer_ventas_empleados_mes(plantilla, lista_empleados): for x in range(0, len(lista_empleados)): print("--- Ingrese las ventas del empleado", lista_empleados[x]) ventasEmpleados = input("\n --- Ingrese las ventas de cada mes separadados por comas:") ventasEmpleados = ventasEmpleados.split(",") for y in range(0, 12): plantilla[x][y] = ventasEmpleados[y] return plantilla def ordenar_vendedores_por_ventas(plantilla, lista_empleados): ventasVendedor = [] for x in range(len(plantilla)): totalVentas = 0 for y in range(len(plantilla[x])): totalVentas = totalVentas + int(plantilla[x][y]) ventasVendedor.insert(x, totalVentas) return ventasVendedor def calcular_cinco_vendedores(): #TODO Comentar código #TODO Implementar la función return "No implementada aún" def calcula_mes_mas_ventas(): #TODO Comentar código #TODO Implementar la función return "No implementada aún" def greficar_ventas_por_mes(): #TODO Comentar código #TODO Implementar la función return "No implementada aún"
false
b293cad2d6dc421ac1abfb1fff941c540bda314e
Bashorun97/python-trainings
/sorting in tuples.py
506
4.375
4
text = 'the university of lagos is loacated in Akoka lagos-mainland lga' words = text.split() #split text into words t = list() # create empty list for word in words: t.append((len(word), word))#append length of the word and the word to the list t.sort(reverse = True) #reverse the list from biggest to smallest #create an empty list and append the value of the key in # the t list into the res from biggest to smallest res = list() for length, word in t: res.append(word) print(res)
true
4925a9d09381548678a15f1bd56e22dba28c578b
apnwong/driving
/driving.py
417
4.125
4
country = input('Your country: ') age = input('How old are you? ') age = int(age) if country == 'Taiwan': if age >= 18: print('You can drive') else: print('You cannot drive') elif country == 'Japan': if age >= 20: print('You can drive') else: print('You cannot drive') elif country == 'Ameria': if age >= 16: print('You can drive') else: print('You cannot drive') else: print('Taiwan/Japan/Ameria')
false
fd609104207f10e1a9bf4e326af8169fae25b90b
xbh/Home-Work-of-MLES
/exercise/U2_Conditionals/test_paper.py
875
4.125
4
num_people = int(input("How many people to get takeout?")) price_total = float(input("How much in total?")) price_people = price_total / num_people print("Each people needs to pay", price_people, "yuan.") # -------------------------- num_students = int(input("How many students?")) num_perGroup = int(input("How many students per group?")) num_groups = num_students // num_perGroup num_left = num_students - num_groups * num_perGroup print("There will have", num_groups, "groups, and", num_left, "students will left over.") # -------------------------- a = input("First string") b = input("Second string") c = input("Third string") d = input("Fourth string") print("{3},{2},{1},{0}".format(a, b, c, d)) # -------------------------- num = int(input("numerator")) deno = int(input("denominator")) print("{:.2%}".format(num / deno))
false
5ea4a953459510df36805ba84636f8426246f344
himanshishrish/python_practice
/convertor.py
405
4.4375
4
'''to convert temperatures to and from celsius, fahrenheit. Go to the editor [ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ] Expected Output : 60°C is 140 in Fahrenheit 45°F is 7 in Celsius''' def convertor(c,f): if f==0: f=((9*c)/5)+32 else: c=((f-32)/9)*5 print(str(c)+"°C is "+str(f)+" in Fahrenheit") convertor(0,140)
true
b785fdb11138333a4273e0c09ca81e98091397fa
SpencerMcFadden/Learn-Python-the-Hard-Way-Files
/ex33.py
1,391
4.3125
4
i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num # recreating the while loop in a function print "\nCoverting while-loop to function. drill_1" # defining the function def drill_1(n): # setting i to 0 and creating a new list to use i = 0 numbers1 = [] # the while loop, n is whatever number you put into the function while i < n: print "Item: %d" % i numbers1.append(i) i += 1 print numbers1 # calling the function with n being 3 print "\nusing drill_1 with n = 3" drill_1(3) # calling the function with n being 8 print "\nusing drill_1 with n = 8" drill_1(8) print "\nCreating function drill_3 to allow variable step size" def drill_3(n, s): i = 0 numbers3 = [] while i < n: print "Item: %d" % i numbers3.append(i) i += s print numbers3 print "\nusing drill_3 with n = 12 and s = 3" drill_3(12, 3) print "\ndrill_5 uses a for-loop and range instead" def drill_5(n, s): # need to specify starting point of 0 so Python reads the other elements correctly numbers5 = range(0, n, s) for i in numbers5: print "Item: %d" % i print numbers5 drill_5(14, 4)
true
d398fade4929ed636bb4a78c7515eb376147e0ab
ferreret/python-bootcamp-udemy
/36-challenges/ex130.py
636
4.375
4
''' three_odd_numbers([1,2,3,4,5]) # True three_odd_numbers([0,-2,4,1,9,12,4,1,0]) # True three_odd_numbers([5,2,1]) # False three_odd_numbers([1,2,3,3,2]) # False ''' def three_odd_numbers(numbers): len_numbers = len(numbers) for cursor in range(2, len_numbers): sum_test = numbers[cursor - 2] + numbers[cursor - 1] + numbers[cursor] if sum_test % 2 == 1: return True return False print(three_odd_numbers([1, 2, 3, 4, 5])) # True print(three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0])) # True print(three_odd_numbers([5, 2, 1])) # False print(three_odd_numbers([1, 2, 3, 3, 2])) # False
false
be641cd670af0e38686c2af44fcf34faee8eb5b7
shukhrat121995/coding-interview-preparation
/hashmap/redistribute_characters_to_make_all_strings_equal.py
1,083
4.125
4
""" You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise. Input: words = ["abc","aabc","bc"] Output: true Explanation: Move the first 'a' in words[1] to the front of words[2], to make words[1] = "abc" and words[2] = "abc". All the strings are now equal to "abc", so return true. Input: words = ["ab","a"] Output: false Explanation: It is impossible to make all the strings equal using the operation. Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consists of lowercase English letters. """ from collections import defaultdict class Solution: def makeEqual(self, words: list[str]) -> bool: hash_map = defaultdict(int) for word in words: for c in word: hash_map[c] += 1 return all(i % len(words) == 0 for i in hash_map.values())
true
c03d348ecf3284995b5bb35b5820c75224915a48
shukhrat121995/coding-interview-preparation
/dynamic_programming/frog_jump.py
1,588
4.25
4
""" A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Input: stones = [0,1,2,3,4,8,9,11] Output: false Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. """ class Solution: def canCross(self, stones: list[int]) -> bool: set_stones, fail = set(stones), set() stack = [(0, 0)] while stack: stone, jump = stack.pop() for i in (jump - 1, jump, jump + 1): next_stone = stone + i if i > 0 and next_stone in set_stones and (next_stone, i) not in fail: if next_stone == stones[-1]: return True stack.append((next_stone, i)) fail.add((stone, jump)) return False
true
7c030872f5e26eb2051c1a8f99e8f946ab2b64d0
Shuhuipapa/Codeacademy_projects
/AreaCalculator.py
1,548
4.4375
4
''' Area calcaulator which computes the area of a given shape as selected by user. the calculator will be able to determine the area of Circle and Triangle ''' # Creator: Shuhui Ding 9/21/2017 # Codeacademy project import time from math import pi # import pi value from time import sleep from datetime import datetime hint = "Don't forget to include the correct units! \nExiting..." def dete_input(input_c): if input_c == "C": radius = float(raw_input ("Please enter the radius of the circle")) # get input from user and store it as a float number area = pi*radius**2 # calculate the area print ("The pie is baking") time.sleep(1) # sleep for 1 second print ("%.2f \n" % area) + hint # print area along with the hint elif input_c == "T": base = float(raw_input ("Please enter the base of the triangle")) # get input from user and store it as a float number\ height = float(raw_input ("Please enter the height of the triangle")) # get input from user and store it as a float number area = 0.5 * base * height # calculate the area print "Uni Bi Tri..." time.sleep(1) print ("%.2f \n" % area) + hint # print area along with the hint else: print "invalid input, the program will exist" now = datetime.now() print "The area calculator is on" print '%s/%s/%s %s:%s' % ( now.month, now.day, now.year, now.hour, now.minute) time.sleep(1) # sleep for 1 second option = raw_input ("Enter C for Circle or T for Triangle \n:") option = option.upper() dete_input(option)
true
4aec1214db3c07ffb5fae0eac3daa1161f045051
cristianomeul/randomnumbergenerator
/main.py
597
4.21875
4
import random def randomnumber(): #Making function print('Give me 2 numbers, a minimum and a max to generate a random number') #Intro message x = int(input("Enter a minimum: ")) #User inputs a minimum y = int(input("Enter a maximum: ")) #User inputs a maximum z = int(input("How many numbers do you want to generate? ")) #User chooses how much numbers have to be generated b = 0 #Starting value of b while b < z: #If 0 is less than z, keep generating numbers print(random.randint(x, y)) #Printing random number b +=1 #adding 1 to b randomnumber() #Using Function
true
6be9cfab8d0dc0cc0f111a56ad63c1d0c891dddc
snickersbarr/python
/python_2.7/LPTHW/exercise12.py
372
4.1875
4
#!/usr/bin/python ### Exercise 12 ### ### Prompting People ### y = raw_input("Name? ") print "Your name is", y # Rewriting previous exercise with asking within the prompt age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
true
167336accab3743d41b53598032b9c160026b334
snickersbarr/python
/python_2.7/other/classes_and_self.py
515
4.21875
4
#!/usr/bin/python class className: def createName(self,name): self.name=name def displayName(self): return self.name def saying(self): print "hello %s" % self.name # Create objects to refer to class first = className() second = className() # Use methods within objects to assign values first.createName('Kunal') second.createName('Pamani') # Calls displayName method on objects created print first.displayName() print second.displayName() # Saying method does it for you first.saying() second.saying()
true
7f7a774088406019df2eb28bf438b4c110468f00
snickersbarr/python
/python_2.7/udemy/dictionaries.py
1,934
4.59375
5
#!/usr/bin/python # creates a key with associated values # associates keys with values separated with colons # each set is separated with commas my_dict = {'key1':'value','key2':'value2'} print my_dict # just like lists can have different data types (numbers and strings) print my_dict['key1'] my_dict2 = {'k1':123,'k2':3.4,'k3':'string'} print my_dict2['k3'] # calling parts of the indexed string print my_dict2['k3'][0] # cannot name a dictionary 'dict' : saved for something else my_dict3 = {'test':'test1'} print my_dict3['test'] # can also call different methods on output print my_dict3['test'].upper() my_dict4 = {'k1':123,'k2':34,'k3':'string'} print my_dict4 # does not change value of my_dict4 permanently print my_dict4['k1'] - 120 # reassigning variable value will change permanently my_dict4['k1'] = my_dict4['k1'] - 120 print my_dict4['k1'] my_dict4['k1'] = my_dict4['k1'] + 400 print my_dict4['k1'] # shorter notation using operator before equal sign for same result my_dict4['k1'] += 100 print my_dict4['k1'] # creating an empty dictionary d = {} print d # assigning keys and values to dictionary after creating empty dictionary d['animal'] = 'Dog' print d # can also nest dictionaries the same way you can nest lists # this example shows 'nestkey' nested within 'k1' and 'subnestkey' nested within 'nestkey' with a value of 'value' d = {'k1': {'nestkey': {'subnestkey': 'value'}}} # calling the different values within the nested dictionaries until we finally get just 'value' print d print d['k1'] print d['k1']['nestkey'] print d['k1']['nestkey']['subnestkey'] # again assigning keys and values to dictionaries after declaring empty dictionary s = {} s['k1'] = 1 s['k2'] = 2 s['k3'] = 3 # note dictionaries are in no specific order due to referencing keys print s # print just the keys for the dictionary print s.keys() print s.values() # print both keys and values in a tuple print s.items()
true
8616b4e9e22a6849e1f1e5e3c01535a5d8ecb2bb
snickersbarr/python
/python_2.7/udemy/errors_and_exceptions.py
2,786
4.3125
4
#!/usr/bin/python # This module is about error handling. Specifically with try, except, finally blocks and try, except, else blocks as well as all four concepts put to gether ''' Example: try: 2 + 's' except typeError: print "There was a type error!" ''' ''' output: Traceback (most recent call last): File "errors_and_exceptions.py", line 5, in <module> except typeError: NameError: name 'typeError' is not defined ''' # Another Example: # This example will compile with no error because 'typeError' was not defined above try: 2 + 's' except: print "There was a type error" finally: print "Finally this was printed" ''' Open a file. If it does not exist, it will write the file because of the 'w'. ''' try: f = open('testfile1232', 'w') # When opening a file in python, it will just create the file if it does not exist # The 'w' tells python that we can write to the file f.write('Test write this') except: print 'Error in writing to the file!' # This is why this does not error out when trying to open the file else: print 'File write was a success' ''' This will cause an error but the program will keep running because we are trying to read a file that does not exist. ''' try: f = open('testfile1231', 'r') # When opening a file in python, it will just create the file if it does not exist # The 'r' tells python that we can read the file f.write('Test write this') # can also write except IOError: (this will only work because that is the error we are producing) except: print 'Error in writing to the file!' # This is why this does not error out when trying to open the file else: print 'File write was a success' finally: # Another example of finally. Again, this will always be run even if an error is hit print "Always execute finally code blocks" print "\n" # Example of using a try block with input from the user # This will only work for one failed attempt def askInt(): try: val = int(raw_input("Please enter an integer: ")) except: print "Looks like you did not enter an integer" val = int(raw_input("Try again. Please enter an integer: ")) finally: print "Finally block executed" print val # Better way of writing askInt to continue through until an integer is given # Example of using while True(basically forever). Use else statement to break from while loop def askIntBetter(): while True: try: val = int(raw_input("Please enter an integer: ")) except: print "Looks like you did not enter an integer" continue # They key to this while loop which allows it to go back to the top. else: print "Correct, that as an integer!" break finally: # No matter what this will execute over and over everytime. print "Finally block executed" print "Your integer is {0}".format(val) askIntBetter()
true
cb30dc5a7322d90a929a7b712a2bd86416558412
Vishal1003/python-five_Domain
/1_python/operator_overloading.py
1,153
4.40625
4
# python operators work for the built in classes. But the same operator behaves diffrently with different data types. # + operator is used for arithmatic addition of two num, merge two lists, concatinate two strings # This feature in python, that allows same operator to have different meaning according to the context is called operator overloading class A: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other.a obj1 = A(5) obj2 = A(2) print(obj1 + obj2) # add method is called automatically print("------------------------------") class Vector: def __init__(self, a, b): self.a = a self.b = b def __add__(self, other): return self.a + other.a, self.b + other.b vc1 = Vector(2, 4) vc2 = Vector(1, 5) print(vc1 + vc2) print("------------------------------") # Comparison Operator class Op: def __init__(self, a): self.a = a def __lt__(self, other): if(self.a < other.a): return "Obj1 is less than Obj2" else : return "Obj2 is less than Obj1" obj1 = Op(15) obj2 = Op(10) print(obj1 < obj2)
true
46c7c7117d1e9f673484fbe2cad1b077f84a14e4
squashgray/Hash-Tables
/hashtable/hashtable.py
2,193
4.1875
4
class HashTableEntry: """ Hash Table entry, as a linked list node. """ def __init__(self, key, value): self.key = key self.value = value self.next = None class HashTable: """ A hash table that with `capacity` buckets that accepts string keys Implement this. """ def fnv1(self, key): """ FNV-1 64-bit hash function Implement this, and/or DJB2. """ def djb2(self, key): """ DJB2 32-bit hash function Implement this, and/or FNV-1. """ def hash_index(self, key): """ Take an arbitrary key and return a valid integer index between within the storage capacity of the hash table. """ #return self.fnv1(key) % self.capacity return self.djb2(key) % self.capacity def put(self, key, value): """ Store the value with the given key. Hash collisions should be handled with Linked List Chaining. Implement this. """ def delete(self, key): """ Remove the value stored with the given key. Print a warning if the key is not found. Implement this. """ def get(self, key): """ Retrieve the value stored with the given key. Returns None if the key is not found. Implement this. """ def resize(self): """ Doubles the capacity of the hash table and rehash all key/value pairs. Implement this. """ if __name__ == "__main__": ht = HashTable(2) ht.put("line_1", "Tiny hash table") ht.put("line_2", "Filled beyond capacity") ht.put("line_3", "Linked list saves the day!") print("") # Test storing beyond capacity print(ht.get("line_1")) print(ht.get("line_2")) print(ht.get("line_3")) # Test resizing old_capacity = len(ht.storage) ht.resize() new_capacity = len(ht.storage) print(f"\nResized from {old_capacity} to {new_capacity}.\n") # Test if data intact after resizing print(ht.get("line_1")) print(ht.get("line_2")) print(ht.get("line_3")) print("")
true
6b9d5838c2d1c0b526a177fd229645f9f5de55f3
Data-Semi/DataStructure-Project3-ProblemsVSAlgorithms
/python_files_from_notes/4.py
2,773
4.21875
4
#!/usr/bin/env python # coding: utf-8 # Dutch National Flag Problem # Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. You're not allowed to use any sorting function that Python provides. # # Note: O(n) does not necessarily mean single-traversal. For e.g. if you traverse the array twice, that would still be an O(n) solution but it will not count as single traversal. # # Here is some boilerplate code and test cases to start with: # In[2]: def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ pos = 0 #index of current judgement position next_0 = 0 # index of next possible insert position of 0 next_2 = len(input_list)-1 # index of next possible insert position of 2 if next_2 == -1 or next_2 == 0: # empty list, or a list has only 1 element return input_list # return itself while pos <= next_2: if input_list[pos] == 0: input_list[next_0], input_list[pos] = input_list[pos], input_list[next_0] next_0 += 1 if pos < next_0: # pos and next_0 was in the same position pos += 1 elif input_list[pos] == 2: input_list[next_2], input_list[pos] = input_list[pos], input_list[next_2] next_2 -= 1 else: # it is 1, move to next pos += 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) # ## Program description # Dutch National Flag Problem Given an input array consisting on only 0, 1, and 2. # In this program, I have sort the array in a single traversal. # The idea is keep track of the index after the tail position(final index) of 0, the index infront of the head position of 2 and the current index of traverse. # Every time if the element in current index is 0, it will switch with the element right after the tail position of 0. # Every time if the element in current index is 2, it will switch with the element in front of head position of 2. # # ## Time compexity # Becaus of all operations takes constant time, and there is only one traverse. Therefore, the program's time complexity is O(n). # # ## Space complexity # Because there is no extra space uses other than the input array,the space complexity is O(1). # # In[ ]:
true
e4665cd88eba6423cdc5bad73ab4d0d566e3bf2e
Data-Semi/DataStructure-Project3-ProblemsVSAlgorithms
/problem_4.py
1,530
4.15625
4
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ pos = 0 #index of current judgement position next_0 = 0 # index of next possible insert position of 0 next_2 = len(input_list)-1 # index of next possible insert position of 2 if next_2 == -1 or next_2 == 0: # empty list, or a list has only 1 element return input_list # return itself while pos <= next_2: if input_list[pos] == 0: input_list[next_0], input_list[pos] = input_list[pos], input_list[next_0] next_0 += 1 if pos < next_0: # pos and next_0 was in the same position pos += 1 elif input_list[pos] == 2: input_list[next_2], input_list[pos] = input_list[pos], input_list[next_2] next_2 -= 1 else: # it is 1, move to next pos += 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([]) test_function([0, 0, 0]) test_function([1, 1, 1]) test_function([2, 2, 2]) test_function([1])
true
decb476d94340f5c504502c7f7871745e608a34d
PierreBeaujuge/holbertonschool-higher_level_programming
/0x06-python-classes/4-square.py
737
4.3125
4
#!/usr/bin/python3 """ Access and update private attribute """ class Square: """define variables and methods""" def __init__(self, size=0): """initialize attributes""" self.size = size @property def size(self): """getter for size""" return self.__size @size.setter def size(self, value): """setter for size""" if isinstance(value, int) and value >= 0: self.__size = value elif not isinstance(value, int): raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") def area(self): """define area method, evaluate square area""" return self.__size ** 2
true
3d0ea61d723388381aa90ccb1ad092fb074c6a42
iuliar/TrainingPython
/suma_int_4_2.py
585
4.34375
4
""" Create a program that computes the sum of all float and integer numbers from a list. The given list contains other data types as well: strings, tuples, list of lists, etc. (e.g: at least one list element from each data type + """ initial_list = [1, 2, "unu", (3,4,5), "word", ['a', 'b', 'c'], 3, 6, 7.8, 9.2 ] length_of_the_list = len(initial_list) suma = 0 for i in range(length_of_the_list): if type(initial_list[i]) == int or type(initial_list[i]) == float: suma = suma + initial_list[i] print("The sum of the integer and float values from the list is: ", suma)
true
1d65afac7624a2a620aab7be858b9993de958e3a
maxthemagician/BioInformatics3
/Assignment1/Assign1_suppl/AbstractNetwork.py
1,703
4.125
4
class AbstractNetwork: """Abstract network definition, can not be instantiated""" def __init__(self, amount_nodes, amount_links): """ Creates empty nodelist and call createNetwork of the extending class """ self.nodes = {} self.mdegree = 0 self.__createNetwork__(amount_nodes, amount_links) for node in self.nodes: degree = self.nodes[node].nodes.__len__() if(degree>self.mdegree): self.mdegree = degree def __createNetwork__(self, amount_nodes, amount_links): """ Method overwritten by subclasses, nothing to do here """ raise NotImplementedError def appendNode(self, node): """ Appends node to network """ self.nodes[node.id] = node if(self.mdegree < node.degree()): self.mdegree = node.degree() def maxDegree(self): """ Returns the maximum degree in this network """ return int(self.mdegree) def size(self): """ Returns network size (here: number of nodes) """ return self.nodes.__len__() def __str__(self): ''' Any string-representation of the network (something simply is enough) ''' s = " " ''' for node in self.nodes: s = s + "{ " + str(node) + " }" s = s + " -> { " for k in self.nodes[node].nodes: s = s + str(k) + " " s = s + "}\n" ''' return s def getNode(self, identifier): """ Returns node according to key """ return self.nodes[identifier]
true
10b7d7f0025a34e24826b8b83147f56a4824e4b7
wzqnls/AlgorithmsByPython
/BubbleSort/BubbleSort.py
347
4.1875
4
def bubble_sort(lists): length = len(lists) for i in range(0, length): for j in range(0, length - 1 - i): if lists[j] > lists[j + 1]: lists[j + 1], lists[j] = lists[j], lists[j + 1] return lists if __name__ == '__main__': lists = [1, 2, 3, 6, 8, 22, 11, 77, 66] print(bubble_sort(lists))
false
2e7269ad5cce7b27db13bbfc7ff9a328a7e8b7e7
vinceajcs/all-things-python
/algorithms/graph/dfs/connected_components.py
1,196
4.125
4
"""Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 Example 2: Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]] 0 4 | | 1 --- 2 --- 3 Output: 1 Assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. We can traverse the graph with DFS. Time: O(m+n) Space: O(n) """ def connected_components(n, edges): def dfs(node, graph, visited): if visited[node]: return visited[node] = 1 for neighbor in graph[node]: dfs(neighbor, graph, visited) visited = [0] * n graph = collections.defaultdict(list) # create graph for x, y in edges: graph[x].append(y) graph[y].append(x) count = 0 for node in range(n): if not visited[node]: dfs(node, graph, visited) count += 1 return count
true
0aee5478cf875541f6398a73c281b9deb116c939
vinceajcs/all-things-python
/algorithms/tree/binary_tree/diameter_of_binary_tree.py
843
4.4375
4
"""Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree: 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them. Time: O(n) Space: O(1) """ def diameter(root): self.longest_path = 0 # global max def depth(node): if not node: return 0 left, right = depth(node.left), depth(node.right) self.longest_path = max(self.longest_path, left + right) return 1 + max(left, right) depth(root) return self.longest_path
true
ea577a1ae1fa7a6e07a6c61d5fe75a302575957f
vinceajcs/all-things-python
/algorithms/graph/dfs/course_schedule.py
1,746
4.375
4
"""There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: 2, [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: 2, [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. We can use DFS to detect a cycle in a graph of courses (check for back edges). Time: O(m+n) Space: O(n) """ def can_finish(courses, prereqs): graph = [[] for _ in range(courses)] visited = [0 for _ in range(courses)] # same as [0] * courses # create graph for pair in prereqs: x, y, = pair # x is a node, y is its neighbor graph[x].append(y) # visit each node in graph for i in range(courses): if not dfs(graph, visited, i): return False return True def dfs(graph, visited, i): # check if there's a cycle if visited[i] == -1: return False # if it has already been visited in a current run, do not visit again if visited[i] == 1: return True visited[i] = -1 # mark as visited in a current run # visit neighbors for j in graph[i]: if not dfs(graph, visited, j): return False visited[i] = 1 # after visiting all neighbors, mark the finish of a current run return True
true
43dd06e1c5b0a2296bcb301a49af8ebb7eb9f0f4
vinceajcs/all-things-python
/algorithms/math/power.py
865
4.40625
4
"""Implement power(x, n), which calculates x raised to the power n (x**n).""" def power(x, n): if n == 0: return 1 if n < 0: n = -n x = 1 / x return power(x * x, n // 2) if (n % 2 == 0) else x * power(x * x, n // 2) """Using repeated squaring (both time and space complexity: O(logn)). power(x, n) = 1 if n = 0, x * (power(x, n//2))**2 if n > 0 is odd, (power(x, n//2))**2 if n > is even. """ def power(x, n): """Note: this assumes both x and n are nonnegative integers.""" if n == 0: return 1 else: partial = power(x, n // 2) result = partial * partial if n % 2 == 1: result *= x return result """Using simple recurison.""" def power(x, n): if n == 0: return 1 else: return x * power(x, n - 1)
true
42765374350606400390baea2f04538b56675fd6
vinceajcs/all-things-python
/algorithms/tree/binary_tree/bst/second_largest_element.py
894
4.125
4
"""Given a BST, find the second largest element. Time: O(h) Space: O(1) """ def find_largest(root): current = root while current: if not current.right: return current.value current = current.right def find_second_largest(root): if not root or not root.left or root.right: return current = root while current: # current is the rightmost node and has a left subtree # then, 2nd largest node is the largest in that left subtree if current.left and not current.right: return find_largest(current.left) # current is parent of the largest node, and largest has no children # then, current is 2nd largest if (current.right and not current.right.left and not current.right.right): return current.value current = current.right
true
6b996f29b51841109ee1d053d899869c1a6528b3
vinceajcs/all-things-python
/algorithms/tree/binary_tree/populating_next_right_pointers.py
1,364
4.125
4
"""Given a perfect binary tree, populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. We can traverse the binary tree level by level. Time: O(n) Space: O(n) """ def connect(root): if not root: return queue = collections.deque() queue.append(root) queue.append(None) while queue: node = queue.popleft() if node: node.next = queue[0] if node.left: queue.append(node.left) if node.right: queue.append(node.right) else: if len(queue) > 0: queue.append(None) """Another way, recursively.""" def connect(root): if not root: return if root.left: root.left.next = root.right if root.right and root.next: root.right.next = root.next.left connect(root.left) connect(root.right) """Another iterative solution.""" def connect(root): while root and root.left: next_node = root.left while root: root.left.next = root.right if root.next: root.right.next = root.next.left else: root.right.next = None root = root.next root = next_node
true
14bc4ded2259854c71e19103c9589e358d941867
vinceajcs/all-things-python
/algorithms/tree/binary_tree/flatten_binary_tree_to_linked_list.py
837
4.28125
4
"""Given a binary tree, flatten it to a linked list in-place. Idea: 1. Flatten left subtree 2. Find left subtree's tail (end) 3. Set root's left to None, root's right to root's left subtree, and tail's right to root's right subtree 4. Flatten original right subtree Time: O(n) Space: O(n) """ def flatten(root): if not root: return right = root.right if root.left: flatten(root.left) # flatten left subtree tail = root.left # get left subtree's tail while tail.right: tail = tail.right root.left, root.right, tail.right = None, root.left, right flatten(root.right) """Another way.""" pre = None def flatten(root): if not root: return flatten(root.right) flatten(root.left) root.right = pre root.left = None pre = root
true