blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6bd8e9904b1fc9a1573512dd73214bbf37f68ce0
pravinherester/LearnPython
/functions/calculator/Calculator6.py
1,147
4.15625
4
def add(n1,n2): return n1+n2 def subtract(n1,n2): return n1-n2 def multiply(n1,n2): return n1*n2 def divide(n1,n2): return n1/n2 from art import logo from replit import clear operations={ "+":add, "-":subtract, "*":multiply, "/":divide, } def calculator(): print (logo) num1= float (input("Enter the first number:\t")) for key in operations: print(f"{key}") to_continue=True while to_continue : operation_symbol=input("What is the operation you would like to perform?\n") num2= float (input(f"Enter another number to {operations[operation_symbol].__name__} with {num1}: \t")) calculation_function=operations[operation_symbol] answer=calculation_function(num1,num2) print(f"{num1} {operation_symbol} {num2} = {answer}\n") test=input (f"Type Y to continue operation with {answer} and N to start to a new operation \n") if(test=='Y'): to_continue=True num1=answer elif (test=='N'): to_continue=False clear() calculator() # recursive function call else: clear() exit() calculator()
true
fe4aaa884307c5b8b358e25b2bb2aa8dca01d1eb
PrabhatRoshan/Daily_Practice_Python
/Daily_practice_codes/if-elif-else/user_input.py
594
4.21875
4
# Write a python program to check the user input abbreviation.If the user enters "lol", # print "laughing out loud".If the user enters "rofl", print "rolling on the floor laughing". # If the user enters "lmk", print "let me know".If the user enters "smh", print "shaking my head". user_ip=input("Enter the user input--") if user_ip=="lol": print("laughing out loud") elif user_ip=="rofl": print("rolling on the floor laughing") elif user_ip=="lmk": print("let me know") elif user_ip=="smh": print("shaking my head") else: print("enter another i/p")
true
41dade8692d9fbc19de8226e9abe366225058ddb
ionblast25/css-225-homework
/problem_4.py
470
4.46875
4
#Justine Rosado #10/31/20 #this program is supports to iterates the integers from 1 to 50 def divisible_by_3(n): if n%3 == 0 or n%6 == 0: print("divisible by 3") if n%5 == 0 or n%20 == 0: print("divisible by 5") elif n%3 == 0 and n%5 == 0: print("divisible by both") else: print("non are divisible") divisible_by_3(3) divisible_by_3(2) divisible_by_3(5)
false
73a1084037267aa353163c663ce2c6ccf22b6d1b
Bamblehorse/Learn-Python-The-Hard-Way
/ex3.py
979
4.3125
4
#Simple print " " print "I will now count my chickens:" #print "string then comma", integer print "Hens", 25 + 30 / 6 #bidmas. Brackets, indices div, mult, #add, sub. PEMDAS. Mult first. #so div first 30 / 6 = 5 #then 25 + 5 = 30, simples print "Roosters", 100 - 25 * 3.0 % 4.0 #3 % 4 = 3?, 3 * 25 = 75, 100 - 75 = 25 #so actually, 75 % 4 = 3, 10 - 3 = 97 #print" " print "Now I will count the eggs:" #div, 1/4, 4%2. 3+2+1-5+0-0+6=7 print 3 + 2 + 1 - 5 + 4.0 % 2.0 - 1.0 / 4.0 + 6 print "Is it true that 3 + 2 < 5 - 7?" #5<-2 false print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 #of course print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5>= -2 print "Is it less or equal?", 5 <= -2 #true, true, false #extra sec = 1 min = 60*sec hour = 60*min print "A minute is ", min, " seconds" print "An hour is ", hour, "seconds"
true
af6dde0e1aaddafe38cab5a891fd6895207d2b7b
kent10636/Learn_Python
/set.py
1,755
4.28125
4
# set和dict类似,是一组key的集合,但不存储value s = set([1, 2, 3]) print(s) # 显示的{1, 2, 3}只表示set内部有1、2、3这3个元素,显示的顺序也不表示set是有序的 print() # 重复元素在set中自动被过滤 s = set([1, 1, 2, 2, 3, 3]) print(s) print() # 通过add(key)方法添加元素到set中,可以重复添加,但不会有效果 s.add(4) print(s) s.add(4) print(s) print() # 通过remove(key)方法删除元素 s.remove(4) print(s) print() # set可以看成数学意义上的有序和无重复元素的集合 # 因此,两个set可以做数学意义上的交集、并集等操作 s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) print(s1 & s2) # 交集符号是& print(s1 | s2) # 并集符号是| print() # set和dict的唯一区别仅在于没有存储对应的value # 对于可变对象list,对list进行操作,list内部的内容会变化 a = ['c', 'b', 'a'] a.sort() # sort()用于排序 print(a) print() # 对于不可变对象str,调用对象自身的任意方法,不会改变该对象自身的内容。 # 这些方法会创建新的对象并返回,这样保证了不可变对象本身永远是不可变的 a = 'abc' print(a) print(a.replace('a', 'A')) # 对str使用replace()方法,确实变出了'Abc',但变量a最后仍是'abc' print(a) print() # a本身是一个变量,它指向的对象的内容才是字符串对象'abc' # 当我们调用a.replace('a', 'A')时,实际上调用方法replace是作用在字符串对象'abc'上的, # 这个replace方法没有改变字符串'abc'的内容,而是创建了一个新字符串'Abc'并返回, # 变量b指向该新字符串'Abc',变量a仍指向原有的字符串'abc' a = 'abc' b = a.replace('a', 'A') print(b) print(a)
false
ccbd0b742eb6ccaf7095dcb23c79e3a9ab190048
kent10636/Learn_Python
/args.py
2,720
4.28125
4
# 必选参数在前,默认参数在后 # 函数有多个参数时,变化大的参数放前面,变化小的参数放后面 def power(x, n=2): # 可以把第二个参数n的默认值设定为2 s = 1 while n > 0: n = n - 1 s = s * x return s print(power(5)) print(power(5,3)) print() def enroll(name, gender, age=6, city='Beijing'): # 把年龄和城市设为默认参数 print('name:', name) print('gender:', gender) print('age:', age) print('city:', city) enroll('Sarah', 'F') enroll('Bob', 'M', 7) # 按顺序提供默认参数,除了name,gender外,最后1个参数用在参数age上,city参数由于没有提供,仍然使用默认值 enroll('Adam', 'M', city='Tianjin') # 不按顺序提供部分默认参数,需要把参数名写上 print() # Python函数在定义时,默认参数L的值就被计算出来了,即[], # 因为默认参数L也是一个变量,它指向对象[], # 每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。 # 定义默认参数要牢记一点:默认参数必须指向不变对象! def add_end(L=None): if L is None: L = [] L.append('END') return L print(add_end()) print(add_end()) print() # 定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号 # 在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进去 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum nums = [1, 2, 3] print(calc(*nums)) print() # **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数, # kw将获得一个dict,这个dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, **extra) print() # 限制关键字参数的名字,可以用命名关键字参数,例如只接收city和job作为关键字参数 # 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数 def person1(name, age, *, city='Beijing', job): # 命名关键字参数可以有缺省值 print(name, age, city, job) person('Jack', 24, city='Shanghai', job='Engineer') # 命名关键字参数必须传入参数名 person('Jack', 24, job='Engineer') # 由于命名关键字参数city具有默认值,调用时可不传入city参数 # *args是可变参数,args接收的是一个tuple; # **kw是关键字参数,kw接收的是一个dict。 # 命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。
false
3cba62c7a9bd0ef2b0a3ee2544f0296461590d11
Vindhesh/demopygit
/calc.py
1,111
4.125
4
class Calculator: def __init__(self): pass def calculate(self): answer = 0 memory = list() while True: input1, operator, input2 = input("Enter your first number, operator and second number with space: ").split() input1 = float(input1) input2 = float(input2) if operator == "+": answer = input1 + input2 elif operator == "-": answer = input1 - input2 elif operator == "*": answer = input1 * input2 elif operator == "/": answer = input1 / input2 memory.append(answer) memory.reverse() print("Your answer for current calculation is:", answer) check = input("Want to calculate?: y/n ") if check == "y": continue else: pass print("The memory of last five calculations is: ", memory[1 : 6]) break one = Calculator() one.calculate()
true
817849b00859f665a1ba1830469f7d29cbc177e4
chenfangstudy/data_analysis
/chapter_2/01-任务程序/code/任务2.2 认识NumPy矩阵与通用函数.py
2,932
4.15625
4
# -*- coding: utf-8 -*- ############################################################################### ####################### 正文代码 ####################### ############################################################################### # 代码 2-30 import numpy as np #导入NumPy库 matr1 = np.mat("1 2 3;4 5 6;7 8 9") #使用分号隔开数据 print('创建的矩阵为:',matr1) matr2 = np.matrix([[123],[456],[789]]) print('创建的矩阵为:',matr2) # 代码 2-31 arr1 = np.eye(3) print('创建的数组1为:',arr1) arr2 = 3*arr1 print('创建的数组2为:',arr2) print('创建的矩阵为:',np.bmat("arr1 arr2; arr1 arr2")) # 代码 2-32 matr1 = np.mat("1 2 3;4 5 6;7 8 9") #创建矩阵 print('创建的矩阵为:',matr1) matr2 = matr1*3 #矩阵与数相乘 print('创建的矩阵为:',matr2) print('矩阵相加结果为:',matr1+matr2) #矩阵相加 print('矩阵相减结果为:',matr1-matr2) #矩阵相减 print('矩阵相乘结果为:',matr1*matr2) #矩阵相乘 print('矩阵对应元素相乘结果为:',np.multiply(matr1,matr2)) # 代码 2-33 print('矩阵转置结果为:',matr1.T) #转置 print('矩阵共轭转置结果为:',matr1.H) #共轭转置(实数的共轭就是其本身) print('矩阵的逆矩阵结果为:',matr1.I) #逆矩阵 print('矩阵的二维数组结果为:',matr1.A) #返回二维数组的视图 # 代码 2-34 x = np.array([1,2,3]) y = np.array([4,5,6]) print('数组相加结果为:',x + y) #数组相加 print('数组相减结果为:',x - y) #数组相减 print('数组相乘结果为:',x * y) #数组相乘 print('数组相除结果为:',x / y) #数组相除 print('数组幂运算结果为:',x ** y) #数组幂运算 # 代码 2-35 x = np.array([1,3,5]) y = np.array([2,3,4]) print('数组比较结果为:',x < y) print('数组比较结果为:',x > y) print('数组比较结果为:',x == y) print('数组比较结果为:',x >= y) print('数组比较结果为:',x <= y) print('数组比较结果为:',x != y) # 代码 2-36 print('数组逻辑运算结果为:',np.all(x == y)) #np.all()表示逻辑and print('数组逻辑运算结果为:',np.any(x == y)) #np.any()表示逻辑or # 代码 2-37 arr1 = np.array([[0,0,0],[1,1,1],[2,2,2],[3,3,3]]) print('创建的数组1为:',arr1) print('数组1的shape为:',arr1.shape) arr2 = np.array([1,2,3]) print('创建的数组2为:',arr2) print('数组2的shape为:',arr2.shape) print('数组相加结果为:',arr1 + arr2) # 代码 2-38 arr1 = np.array([[0,0,0],[1,1,1],[2,2,2],[3,3,3]]) print('创建的数组1为:',arr1) print('数组1的shape为:',arr1.shape) arr2 = np.array([1,2,3,4]).reshape((4,1)) print('创建的数组2为:',arr2) print('数组2的shape为:',arr2.shape) print('数组相加结果为:',arr1 + arr2)
false
74df44cb43c3fc886f1c684aab78a5864cdc6893
SamirDjaafer/Python-Basics
/Excercises/Excercise_106.py
868
4.34375
4
age = input('How old are you? ') driver_license = input('Do you have a drivers license? Yes / No ') if driver_license == 'Yes' or driver_license == 'yes': driver_license = True else: driver_license = False # - You can vote and drive if int(age) >= 18 and driver_license == True: print('Nice, you can vote and drive') # - You can vote elif int(age) >= 18: print('You can vote!') # - You can drive elif driver_license == True: print('You can drive!') # - you can't leagally drink but your mates/uncles might have your back (bigger 16) elif int(age) >= 16 and int(age) < 18: print("you can't legally drink but your mates/uncles might have your back") # - Your too young, go back to school! elif int(age) < 16: print("You're too young, go back to school!") # as a user I should be able to keep being prompted for input until I say 'exit'
true
ecf1eaf7b05d97214568ab6fc69c31a41f74fd4f
ssiddam0/Python
/Lab7/lab7-13_Sowjanya.py
1,176
4.28125
4
# program - lab7-13_sowjanya.py 26 April 2019 ''' This program simulates a Magic 8 Ball game, which is a fortune-telling toy that displays a random response to a yes or no question. It performs the following actions: 1) Reads the 12 responses from the file named 8_ball_responses.txt 2) Prompts the user to ask a question 3) Displays random answers from the list using randint method ''' import random # Needed for the randint method def main(): # Open file for reading infile = open('8_ball_responses.txt','r') #Read the contents of the file into a list. answerslist = infile.readlines() #close the file infile.close() play = 'y' while play == 'y': question = input('Please ask me a question:\n') # Generate random number between 0 and 10 as file has 11 answers number = random.randint(0,10) #Display the random answer print(answerslist[number]) play = input('Do you want to play again? y = yes, anything else = no\n') print() main() input('\n\npress enter to continue ')
true
d0c72888e33db08b24f9c9e0b6e089665561fc9b
JackStruthers/CP1404_Practicals
/CP1404_Practicals/week_02/average_age.py
410
4.15625
4
age = int(input("Please enter the age of a person (use a negative if there are no more people): ")) collective_age = 0 people = 0 while age >= 0: people += 1 collective_age += age age = int(input("Please enter the age of a person (use a negative if there are no more people): ")) if people == 0: print("Invalid") else: print("The average age of the group is...", collective_age / people)
true
b8aed7db2cc46f37e0bda243edfa6fc00c9d8e7f
JackStruthers/CP1404_Practicals
/CP1404_Practicals/week_01/Lecture 1 act 2.py
260
4.15625
4
def main(): user_age = int(input("Please enter your age: ")) while user_age < 0: user_age = int(input("You must be older than 0: ")) if user_age < 18: print("You are a child") else: print("You are an adult") main()
false
1cf789a5c355229d5426c3d334e30367eeb5e00c
sanxofon/basicnlp3
/tiposvars.py
2,892
4.375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Tipos de variables y constantes """ # Números # Enteros -n, ...,-1, 0, 1,..., n entero = 5 # Si tengo una cadena u otra cosa y quiero convertirla a entero cadena = "5" entero = int(cadena) # Comprobar si una variable es un entero if isinstance(cadena, int): print(cadena, "Es entero") else: print(cadena, "No es entero") if isinstance(entero, int): print(entero, "Es entero") else: print(entero, "No es entero") # Racionales: 0.5, 0,6534, etc flotante = 5.0982319237 # Si tengo una cadena u otra cosa y quiero convertirla a entero cadena = "5.0982319237" flotante = float(cadena) # Comprobar si una variable es un entero if isinstance(cadena, float): print(cadena, "Es flotante") else: print(cadena, "No es flotante") if isinstance(entero, float): print(entero, "Es flotante") else: print(entero, "No es flotante") if isinstance(flotante, float): print(flotante, "Es flotante") else: print(flotante, "No es flotante") # Diferencias en operaciones entero = 5/7 flotante = 5./7 if isinstance(entero, float): print(entero, "Es flotante") else: print(entero, "No es flotante") if isinstance(flotante, float): print(flotante, "Es flotante") else: print(flotante, "No es flotante") # CADENAS DE TEXTO cadenaUTF8 = "Aquí va un texto" # Como el archivo está en UTF-8 esta cadena también print(cadenaUTF8) cadena = cadenaUTF8.decode('utf-8') # Cadena ya está decodificada print(cadena) cadena = u"Aquí va un texto" print(cadena) # Convertir a cadena cadena = str(entero) cadena = str(flotante).encode('utf-8') # LISTAS SIMPLES lista_simple = [ entero, flotante, cadena, cadena, "Pepito le dijo a su maestra que ¡aguas! bla bla...", # u"Pepito le dijo a su maestra que ¡aguas! bla bla...", ] # Imprime la lista en formato "soy muy conocedor" print(lista_simple) # Imprime la lista datos por dato en limpio, línea por línea for l in lista_simple: print(l) # Implrime la UNION de la lista con un "pegamento" lista_cadenas = [] for l in lista_simple: # Convertimos a cadena y agragamos a lista_cadenas lista_cadenas.append( str( l ) ) # Imprimimos sim problemas!! print(", ".join(lista_cadenas)) # DICCIONARIO SIMPLES diccionario = { "entero": entero, "flotante": flotante, "cadena": cadena, "constante": "Pepito le dijo a su maestra que ¡aguas! bla bla...", } # Imprimir a la brava print(diccionario) # Imprimir UNION de CLAVES (keys) << Siempre funciona !! print(", ".join( diccionario.keys() )) # Imprimir UNION de VALORES (values) << NO Siempre funciona !! # print(", ".join( diccionario.values() )) # OJO # diccionario.values() es una lista!!! # Implrime la UNION de la lista con un "pegamento" lista_cadenas = [] for l in diccionario.values(): # Convertimos a cadena y agragamos a lista_cadenas lista_cadenas.append( str( l ) ) print(lista_cadenas) print(", ".join(lista_cadenas))
false
7fe329824f1077f9f49f8b6595bbfbd9abe1cb75
rahulraghu94/daily-coding-problems
/13.py
670
4.125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". """ string = "abcbcbcbcbca" k = 2 max_count = 0 def if_uniq(str, k): if len(set(str)) > k: return False, 0 else: return True, len(str) for i in range(0, len(string)): for j in range(i, len(string)): is_uniq, length = if_uniq(string[i:j], k) max_count = max(max_count, length) print(max_count)
true
02aae668f0f2be658aefa800ad3e22eac941a801
makoalex/Python_course
/Regular expressions/functions_RE.py
1,084
4.34375
4
import re # making a function that extracts a phone number and all phone numbers in a given sequence def extract_phone(input): phone_regex = re.compile(r'\b\d{3} \d{4}-?\d{3}\b') match = phone_regex.search(input) if match: return match.group() return None def extract_all_phone(input): phone_reg = re.compile(r'\d{3} \d{4}-?\d{3}') match_all = phone_reg.findall(input) return match_all print(extract_phone('new number is 451 3117-231')) print(extract_phone(' 451 3117-231nkn')) print(extract_all_phone('his new number is 451 3117-231 and 465 8973-323')) # checking now if the phone number we extracted is a valid number def valid_phone(func): phone_reg = re.compile(r'\d{3} \d{4}-?\d{3}') match = phone_reg.fullmatch(func) if match: return True return False print(valid_phone(('new number is 451 3117-231'))) print(valid_phone('451 3117-231')) """it can also be done with the code from the forst function by just adding ^ at the beginning of the sequence and $ at the end to limit where it starts end ends"""
true
92d0d3047686d2b0f01898d074e5b585df4e1052
makoalex/Python_course
/Iterator.py
2,040
4.375
4
# the for loop runs ITER in the background making the object an iterator after which it calls next # on every single item making the object an iterable def my_loop(iterable): iterator = iter(iterable) while True: try: it = next(iterator) print(it) except StopIteration: print('end') break my_loop('pup') def new(iterable, func): result = iter(iterable) while True: try: new_iter = next(result) except StopIteration: break else: func(new_iter) def add(i): print(i + 2) print(new([1, 4, 5], add)) # GENERATORS HELP CREATE ITERATORS. Every gnerator is an iterator bu not every iterator is a generator. # they are functions that use YIELD instead of return # generator functions return a generator, generators are iterators def week(): week_day = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] for day in week_day: yield day weekly = week() print(next(weekly)) print(next(weekly)) print('me') for day in weekly: print(day) def yes_or_no(): answers = ('yes', 'no') while answers: for a in answers: yield a # soda song def make_song(number, drink): for i in range(number, -1,-1): if i == number: yield '{} bottles of {} on the wall'.format(number, drink) elif i < number: yield '{} bottles of {} on the wall'.format(i, drink) i = number - 1 else: yield 'no more bottles of {} on the wall'.format(drink) count = make_song(7, 'soda') print(next(count)) def get_multiples(num=2, count=10): for i in range(1, count-1): neww= num*i yield neww eve= get_multiples() print(next(eve)) def get_unlimited_multiples(num = 2): new_list=[] for i in range (1, 29): if i%num==0: yield i new_list.append(i) ev = get_multiples() print(next(ev)) print(next(ev))
true
77164c1cfa58f37069bc368e79ab0268c12d5645
WeikangChen/algorithm
/data_struct/tree/trie0b.py
1,807
4.15625
4
class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.value = None self.children = {} class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for c in word: if c not in node.children: child = TrieNode() node.children[c] = child node = child else: node = node.children[c] node.value = word def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for c in word: if c not in node.children: return false else: node = node.children[c] return node.value is word def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.root for c in prefix: if c not in node.children: return false else: node = node.children[c] return True def main(): print __name__ tree = Trie() tree.insert('ab') tree.insert('abcd') tree.insert('abasdfasdf') tree.insert('acd') tree.insert('betters') tree.insert('better') tree.insert('best') a = tree.startsWith('ab') c = tree.search('ab') d = tree.search('be') print a print c print d if __name__ == '__main__': main()
true
146a08687142b1a7ed5a341541616d637b308056
rolandoquiroz/hackerrank_coderbyte_leetcode
/list2.py
1,260
4.375
4
#!/usr/bin/python3 """ Find Intersection Have the function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a comma-separated string containing the numbers that occur in elements of strArr in sorted order. If there is no intersection, return the string false. Examples Input: ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] Output: 1,4,13 Input: ["1, 3, 9, 10, 17, 18", "1, 4, 9, 10"] Output: 1,9,10 """ def FindIntersection(strArr): # code goes here s1 = set(strArr[0].split(", ")) s2 = set(strArr[1].split(", ")) inter = s1.intersection(s2) if inter == set(): return False strArr = list(inter) for i in range(len(strArr)): strArr[i] = int(strArr[i]) nums = sorted(strArr) strArr = "" for i in range(len(nums)): strArr += str(nums[i]) if i < len(nums) - 1: strArr += "," return(strArr) if __name__ == '__main__': # keep this function call here print(FindIntersection(["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]))
true
01fab7efbe9448f98e97707caac64405ad3a190b
j-python-programming/python-programming
/src/06-area.py
511
4.15625
4
# Python によるプログラミング:第 6 章 # 例題 6.5 Polymorphism # -------------------------- # プログラム名: 06-area.py class Rectangle: def __init__(self, width, height): self.width = width self.height = height self.area = width * height class Circle: def __init__(self, radius): self.radius = radius self.area = 3.14 * radius * radius shapes = [Rectangle(3, 4), Circle(5)] for shape in shapes: print("面積: {}".format(shape.area))
false
c55b2e80288a101ebbc61a3847ca4386b7814f09
diegoro1/Tutorials
/python/guess_list.py
1,539
4.25
4
#---------------------------------------------------------------------------------------------------------- # Short List Exesise #---------------------------------------------------------------------------------------------------------- guests = ['Joe','Jan','June','Julian','Jaylin','Jared'] print("invitations going to:") for guest in guests: print(" ->" + guest) print() print("Oh no looks like " + guests.pop(1) + " won't make it") guests.insert(1, 'John') print("A new inviation to " + guests[1] + " will be sent!\n") print("new list:") for guest in guests: print(" ->" + guest) print() print("table got bigger, inserting someone in the start, middle, and end.\n") guests.insert(0,'Jack') guests.append('Jannet') middle_index = int((len(guests) / 2)) guests.insert(middle_index, 'Jone') print("new list:") for guest in guests: print(" ->" + guest) print() print("invitations: ") for guest in guests: print("Dear, " + guest + "\ncome eat yo.\nlove, me\n\n") print("the dinner table broke! only two seats left!") number_guests = len(guests) while number_guests > 2: print("Sorry " + guests.pop() + " you are not invited! :)") number_guests = number_guests - 1 print() print("invitations: ") for guest in guests: print("Dear, " + guest + "\ncome eat yo.\nlove, me\n\n") print("turns our " + guests[0] + " and " + guests[1] + " are not really your friends") del guests[1] del guests[0] print("A list of who you're eating with: " + str(guests) + ".")
false
1f40b96cdc1c945a813c755336b73bb576ac93c7
ValynseeleAlexis/PythonScripts
/Pong/pong1.py
2,821
4.15625
4
# Valynseele Alexis # From Learn Python by building Full Course - FreeCodeCamp.org # 14/01/2020 import turtle window = turtle.Screen() window.title("Pong") window.bgcolor("black") window.setup(width = 800, height = 600) window.tracer(0) # Paddle A paddleA = turtle.Turtle() paddleA.speed(0) paddleA.shape("square") paddleA.color("white") paddleA.penup() paddleA.goto(-350,0) paddleA.shapesize(stretch_wid=5,stretch_len=1) # Paddle B paddleB = turtle.Turtle() paddleB.speed(0) paddleB.shape("square") paddleB.color("white") paddleB.penup() paddleB.goto(350,0) paddleB.shapesize(stretch_wid=5,stretch_len=1) # Ball ball = turtle.Turtle() ball.speed(1) ball.shape("square") ball.color("white") ball.penup() ball.goto(0, 0) ball.deltaX = 0.15 ball.deltaY = 0.15 # Scoring scoreA = 0 scoreB = 0 pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Lolo : " + str(scoreA) +" | Alexis : " + str(scoreB), align="center", font =("Courier",24, "normal")) # Functions def paddleA_up(): y = paddleA.ycor() y += 20 if y < 300: paddleA.sety(y) def paddleA_down(): y = paddleA.ycor() y -= 20 if y > -300: paddleA.sety(y) def paddleB_up(): y = paddleB.ycor() y += 20 if y < 300: paddleB.sety(y) def paddleB_down(): y = paddleB.ycor() y -= 20 if y > -300: paddleB.sety(y) # Keyboard binding window.listen() window.onkeypress(paddleA_up, "z") window.onkeypress(paddleA_down, "s") window.onkeypress(paddleB_up, "Up") window.onkeypress(paddleB_down, "Down") continuer = True #Main game loop while True: window.update() ball.speed(0.01) #Ball mouvements ball.setx(ball.xcor() + ball.deltaX) ball.sety(ball.ycor() + ball.deltaY) #Border checking if ball.ycor() > 290: ball.sety(290) ball.deltaY *= -1 if ball.ycor() < -290: ball.sety(-290) ball.deltaY *= -1 if ball.xcor() > 390: ball.goto(0, 0) scoreA += 1 ball.deltaX *= -1 pen.clear() pen.write("Lolo : " + str(scoreA) +" | Alexis : " + str(scoreB), align="center", font =("Courier",24, "normal")) if ball.xcor() < -390: ball.goto(0, 0) scoreB += 1 ball.deltaX *= -1 pen.clear() pen.write("Lolo : " + str(scoreA) +" | Alexis : " + str(scoreB), align="center", font =("Courier",24, "normal")) if (ball.xcor() >340 and ball.xcor() < 350) and (ball.ycor() < paddleB.ycor() + 50 and ball.ycor() > paddleB.ycor() - 50): ball.setx(340) ball.deltaX *= -1 if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddleA.ycor() + 50 and ball.ycor() > paddleA.ycor() - 50): ball.setx(-340) ball.deltaX *= -1
false
96b85d55696fb32aaad2a79314b88880a0363da8
MaxKrivulin/Home_Work
/HW_1/HW_1_1.py
786
4.3125
4
#1. Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. number = int(input("Введите целое число: ")) print("Ваше число равно ", number) number_1 = int(input("Введите еще одно целое число: ")) print("Ваше второе число равно ", number_1) text = input("Хотите узнать сумму этих чисел?") Yes ='да' and 'Да' if text == Yes: print('Сумма двух чисел равна:', number+number_1) else: print('Ну как хотите!')
false
8985c182f0d906b520962503eae94659bb7c6553
dongrerohan421/python3_tutorials
/09_if_else.py
522
4.15625
4
''' This program shows use of If-Else conditional statement. 1. Your condition doesn't starts with indentations or tab. 2. statment inside the condition starts with indentation or tab. 3. Once condition satisfied, next statement must starts with new line with no indentation or no tab. ''' n = int(input("Number: ")) if n<0: print ("The absolute value of ",n,"is ",-n) else: print ("The absolute value of ",n,"is ",n) # Else condition ends here. # Next line must start with no tab. sumoftwo = 50+60 print (sumoftwo)
true
baf9a7f27bbb8bb66f3565d3b3be2daf9651d090
dongrerohan421/python3_tutorials
/06_strings.py
686
4.34375
4
''' This program explains Pytho's string ''' # Escape character usefule to jump over any character. # Use double back slash to print back slash in your output. a = 'I am \\single quoted string. Don\'t' b = "I am \\double quoted string. Don\"t" c = """I am \\triple quoted string. Don\'t""" print (a) print (b) print (c) # To calculate length of string use len() function print ("Lentgth of the string c is: ") print (len(c)) d = "Hello " e = "World" f = 5 # '+' operator can be used as concatenation operator to join multiple strings. print (d + e) # Use '*' operator to print letter multiple times print (d * 10) # Use str() to convert integer to string. print (d + str(f))
true
b837247ea4c25e581303bc36092eebafd4f0b0e6
Gowtham-P-M/Coding-with-python
/task5.py
990
4.1875
4
#1)Write a program to create a list of n integer values def add(k): l=int(input("What position do you want to add the item ")) m=int(input("What is the item value ")) k.insert(l,m) print("The new list is ",k) def dele(k): f=int(input("What is the item you want to delete ")) for i in k: if i==f: k.remove(i) print ("The new string is ", k) n=int(input("Enter the value of n ")) u=[] for i in range(1,n+1): u.append(i) j=int(input("Enter a number\n1.add to the list\n2.delete from the list\n")) if j==1: add(u) elif j==2: dele(u) m=max(u) n=min(u) print("max-",m,"\nmin-",n) #2)Create a tuple and print the reverse of the created tuple tu=('f',1,'b',2,3,4,5) for i in range(len(tu)-1,-1,-1): print(tu[i],end=' ') #3)Create a tuple and convert tuple into list u=('a','b','c',1,2,3,4) print("\nThe data type of u is ",type(u)) u=list(u) print("The data type of u is ",type(u))
false
675c80d6f783c90bcec8fc34cb91ddff2ebdfe61
nmounikachowdhary/mounikan28
/firstassignment.py
2,373
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Python Program - Calculate Circumference of Circle print("Enter 'x' for exit."); rad = input("Enter radius of circle: "); if rad == 'x': exit(); else: radius = float(rad); circumference = 2*3.14*radius; print("\nCircumference of Circle =",circumference); # In[2]: print("Enter 'x' for exit."); side = input("Enter side length of square: "); if side == 'x': exit(); else: slength = int(side); perimeter = 4*slength; print("\nPerimeter of Square:", perimeter); # In[3]: # Python Program to Swap Two Numbers a = float(input(" Please Enter the First Value a: ")) b = float(input(" Please Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) temp = a a = b b = temp print("After Swapping two Number: a = {0} and b = {1}".format(a, b)) # In[5]: a = 21 b = 10 c = 0 c = a + b print ("line 1 - Value of c is ", c) c = a - b print ("Line 2 - Value of c is ", c) c = a * b print ("Line 3 - Value of c is ", c) c = a / b print ("Line 4 - Value of c is ", c) c = a % b print( "Line 5 - Value of c is ", c) a = 2 b = 3 c = a**b print ("Line 6 - Value of c is ", c) a = 10 b = 5 c = a//b print ("Line 7 - Value of c is ", c) # In[6]: principle=float(input("enter the principle amount:")) time=int(input("enter the time(years)")) rate=float(input("enter the rate:")) simple_interest=(principle*time*rate)/100 print("the simple interest is:",simple_interest) # In[7]: pi=3.14 r=float(input('enter the radius of the circle:')) area=pi*r*r print("area of the circle:%.2f"%area) # In[8]: a=float(input('enter first side:')) b=float(input('enter second side:')) c=float(input('enter third side:')) #calculate the semiperimeter s=(a+b+c)/2 #calculate the area area=(s*(s-a)*(s-b)*(s-c))**0.5 print('area of triangle is %0.2f'%area) # In[9]: celsius=int(input("Enter the temperature in celcius:")) f=(celsius*1.8)+32 print("Temperature in farenheit is:",f) # In[10]: width = float(input('Please Enter the Width of a Rectangle: ')) height = float(input('Please Enter the Height of a Rectangle: ')) # calculate the area Area = width * height # calculate the Perimeter Perimeter = 2 * (width + height) print("\n Area of a Rectangle is: %.2f" %Area) print(" Perimeter of Rectangle is: %.2f" %Perimeter) # In[ ]:
true
7859e5d4e892f162c23a96dc1a7480f556f28fef
Josglynn/Public
/List Less Than Ten.py
1,487
4.75
5
# Take a list, say for example this one: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # Write a program that prints out all the elements of the list that are less than 13. list_num = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] filtered_1 = [item for item in list_num if item < 13] # Comprehensions style print(filtered_1) filtered_2 = list(filter(lambda item: item < 13, list_num)) # Lambda style print(filtered_2) # Other type to solve this:- for i in list_num: if i < 13: print(i) # A list comprehension behaves like this: [output] for [item] in [list] if [filter] # As you can see there are 4 components in its syntax: # output, item, list and filter. # In the code [aa for aa in a if aa < 5]: #output = aa #item = aa #list = a #filter = aa < 5 # What this means is that I'm outputting the variable 'aa' which refers to each item in the list (a). # Since 'aa' is set to refer to each item in list (a), the output will print the items in list (a). However, I also have a filter specified at the end of the code "if aa < 5". # This means that only the items in the list (referred to as aa) that are below 5 are printed out. # It does help if you use labels that are more intuitive in your code. For example instead of naming the list a, I can name the list "number_list": #number_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # My list comprehension will go like this: #[number for number in number_list if number < 5]
true
0bfc7cae00049db8f2bee365c4d85001c0a92e62
michaelschuff/Python
/DailyCodingChallenge/201.py
499
4.21875
4
#You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle: # 1 # 2 3 #1 5 1 #We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries. triangle=[[1],[2,3],[1,5,1]] s=0 for x in triangle: s+=max(x) print(s)
true
25cb09b0c2f6330633749615ec5264f7a8f3245d
jabedkhanjb/Hackerrank
/30-Days-of-Code/Day 26:_Nested Logic.py
2,276
4.25
4
""" Objective Today's challenge puts your understanding of nested conditional statements to the test. You already have the knowledge to complete this challenge, but check out the Tutorial tab for a video on testing. Task Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows: If the book is returned on or before the expected return date, no fine will be charged (i.e.: . If the book is returned after the expected return day but still within the same calendar month and year as the expected return date, . If the book is returned after the expected return month but still within the same calendar year as the expected return date, the . If the book is returned after the calendar year in which it was expected, there is a fixed fine of . Example returned date due date The book is returned on time, so no fine is applied. returned date due date The book is returned in the following year, so the fine is a fixed 10000. Input Format The first line contains space-separated integers denoting the respective , , and on which the book was actually returned. The second line contains space-separated integers denoting the respective , , and on which the book was expected to be returned (due date). Constraints Output Format Print a single integer denoting the library fine for the book received as input. Sample Input STDIN Function ----- -------- 9 6 2015 day = 9, month = 6, year = 2015 (date returned) 6 6 2015 day = 6, month = 6, year = 2015 (date due) Sample Output 45 Explanation Given the following return dates: Returned: Due: Because , it is less than a year late. Because , it is less than a month late. Because , it was returned late (but still within the same month and year). Per the library's fee structure, we know that our fine will be . We then print the result of as our output. """ # Enter your code here. Read input from STDIN. Print output to STDOUT d1, m1, y1 = map(int, input().split()) d2, m2, y2 = map(int, input().split()) if y1 > y2: print(10000) elif m1>m2 and y1==y2: print((m1-m2) * 500) elif d1>d2 and m1==m2 and y1==y2: print((d1-d2) * 15) else: print(0)
true
3ca41732ad78e387b0d4eb6af55b65cbd08d19be
jabedkhanjb/Hackerrank
/Python/String/Text_Wrap.py
570
4.15625
4
''' Task You are given a string and width . Your task is to wrap the string into a paragraph of width . Input Format The first line contains a string, . The second line contains the width, . Output Format Print the text wrapped paragraph. Sample Input ABCDEFGHIJKLIMNOQRSTUVWXYZ 4 Sample Output ABCD EFGH IJKL IMNO QRST UVWX YZ ''' import textwrap def wrap(string, max_width): return textwrap.fill(string, max_width) if __name__ == '__main__': string, max_width = raw_input(), int(raw_input()) result = wrap(string, max_width) print result
true
63d0bdef7cc2dab2c6bbc15a51f3e5061485d23f
jabedkhanjb/Hackerrank
/30-Days-of-Code/Day16:_Exceptions.py
1,756
4.53125
5
""" Objective Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message. Check out the Tutorial tab for learning materials and an instructional video! Task Read a string, , and print its integer value; if cannot be converted to an integer, print Bad String. Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a score. Input Format A single string, . Constraints , where is the length of string . is composed of either lowercase letters () or decimal digits (). Output Format Print the parsed integer value of , or Bad String if cannot be converted to an integer. Sample Input 0 3 Sample Output 0 3 Sample Input 1 za Sample Output 1 Bad String Explanation Sample Case contains an integer, so it should not raise an exception when we attempt to convert it to an integer. Thus, we print the . Sample Case does not contain any integers, so an attempt to convert it to an integer will raise an exception. Thus, our exception handler prints Bad String. """ #!/bin/python3 import math import os import random import re import sys S = input().strip() try: int_S = int(S) print(int_S) except ValueError: print('Bad String') #Write your code here class Calculator(object): def power(self, n, p): if n<0 or p<0: raise Exception('n and p should be non-negative') else: return n**p myCalculator=Calculator() T=int(input()) for i in range(T): n,p = map(int, input().split()) try: ans=myCalculator.power(n,p) print(ans) except Exception as e: print(e)
true
3515dd6d4de9cea5f774213bc7c4bef6af4d97e5
jabedkhanjb/Hackerrank
/Python/String/Capatilize.py
1,250
4.40625
4
""" You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck. Given a full name, your task is to capitalize the name appropriately. Input Format A single line of input containing the full name, S. Output Format Print the capitalized string, S. Constraints The string consists of alphanumeric characters and spaces. Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc. Sample Input chris alan Sample Output Chris Alan Sample Input 1 w 2 r 3g Sample Output 1 W 2 R 3g """ 1. def solve(s): for i in s.split(): s = s.replace(i,i.capitalize()) return s if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w' s = input() result = solve(s) fptr.write(result + '\n') fptr.close() 2. !/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): return ' '.join([word.capitalize() for word in s.split(' ')]) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = solve(s) fptr.write(result + '\n') fptr.close()
true
c91d3ef1c333c85daf6cfca9de9962d25675b640
jabedkhanjb/Hackerrank
/10_Days_of_Statistics/Day0/Mean_Median_Mode.py
2,255
4.375
4
""" Objective In this challenge, we practice calculating the mean, median, and mode. Check out the Tutorial tab for learning materials and an instructional video! Task Given an array, , of integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal value, choose the numerically smallest one. Note: Other than the modal value (which will always be an integer), your answers should be in decimal form, rounded to a scale of decimal place (i.e., , format). Example The mean is . The median is . The mode is because occurs most frequently. Input Format The first line contains an integer, , the number of elements in the array. The second line contains space-separated integers that describe the array's elements. Constraints , where is the element of the array. Output Format Print lines of output in the following order: Print the mean on the first line to a scale of decimal place (i.e., , ). Print the median on a new line, to a scale of decimal place (i.e., , ). Print the mode on a new line. If more than one such value exists, print the numerically smallest one. Sample Input 10 64630 11735 14216 99233 14470 4978 73429 38120 51135 67060 Sample Output 43900.6 44627.5 4978 Explanation Mean: We sum all elements in the array, divide the sum by , and print our result on a new line. Median: To calculate the median, we need the elements of the array to be sorted in either non-increasing or non-decreasing order. The sorted array . We then average the two middle elements: and print our result on a new line. Mode: We can find the number of occurrences of all the elements in the array: 4978 : 1 11735 : 1 14216 : 1 14470 : 1 38120 : 1 51135 : 1 64630 : 1 67060 : 1 73429 : 1 99233 : 1 Every number occurs once, making the maximum number of occurrences for any number in . Because we have multiple values to choose from, we want to select the smallest one, , and print it on a new line """ # Enter your code here. Read input from STDIN. Print output to STDOUT import numpy as np from scipy import stats n = int(input()) num_list = list(map(int, input().split())) print(np.mean(num_list)) print(np.median(num_list)) print(stats.mode(num_list)[0][0])
true
f651b61ddacc18b64492fe337fbc3fbf0653f86a
yoginee15/Python
/venv/Conditions.py
332
4.3125
4
x = int(input("Enter number")) r = x%2 if r==0: print("You entered even number") else: print("You entered odd number") if x>0: print("You entered positive number") elif x<0 : print("You entered negative number") elif x==0: print("You entered zero") else : print("Please enter number. You entered "+ type(x))
true
85da073031a62446c1e48e915337b04f76a268ba
numeoriginal/multithread_marketplace
/consumer.py
2,118
4.25
4
""" This module represents the Consumer. Computer Systems Architecture Course Assignment 1 March 2021 """ import time from threading import Thread class Consumer(Thread): """ Class that represents a consumer. """ def __init__(self, carts, marketplace, retry_wait_time, **kwargs): Thread.__init__(self, **kwargs) self.carts = carts self.marketplace = marketplace self.retry_wait_time = retry_wait_time self.kwargs = kwargs """ Constructor. :type carts: List :param carts: a list of add and remove operations :type marketplace: Marketplace :param marketplace: a reference to the marketplace :type retry_wait_time: Time :param retry_wait_time: the number of seconds that a producer must wait until the Marketplace becomes available :type kwargs: :param kwargs: other arguments that are passed to the Thread's __init__() """ def run(self): """ Every consumer gets an id Iterating through the cart , verifying the operations to be done add/remove executing the operation the required amount of time In case that the consumer cant find the product, he will wait the pre defined time At the end he will print what he got in his cart. """ cart_id = self.marketplace.new_cart() for el in self.carts: for action in el: if action['type'] == 'add': for _ in range(action['quantity']): approved = self.marketplace.add_to_cart(cart_id, action['product']) while not approved: time.sleep(self.retry_wait_time) approved = self.marketplace.add_to_cart(cart_id, action['product']) else: for _ in range(action['quantity']): self.marketplace.remove_from_cart(cart_id, action['product']) self.marketplace.place_order(cart_id, self.kwargs['name'])
true
620ab9fd31bc864245668f9445ad4801e96d9603
PHILLIPEBLOOD/pythonquestions
/string/quests2.py
411
4.15625
4
'''Nome ao contrário em maiúsculas. Faça um programa que permita ao usuário digitar o seu nome e em seguida mostre o nome do usuário de trás para frente utilizando somente letras maiúsculas. Dica: lembre−se que ao informar o nome o usuário pode digitar letras maiúsculas ou minúsculas. ''' nome = input("Nome: ").upper() i = len(nome) - 1 while i >= 0: print(nome[i], end="") i -= 1 print()
false
111310ed7fc2bff2464a4622ba4b0ba969be21dc
PHILLIPEBLOOD/pythonquestions
/sequencial/quest16.py
542
4.15625
4
'''Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total. ''' import math areapintada = int(input("Area pintada: ")) latas = math.ceil(areapintada/54) # 3*18 = 54 custo = latas * 80 print(latas, "latas de tinta") print(custo, "R$")
false
7eae123f77a6d3ddee18ec46551920ca2fb5ee8d
PHILLIPEBLOOD/pythonquestions
/funcoes/questf1.py
348
4.15625
4
'''Faça um programa para imprimir: 1 2 2 3 3 3 ..... n n n n n n ... n para um n informado pelo usuário. Use uma função que receba um valor n inteiro e imprima até a n-ésima linha. ''' def imprimir(n): cont = 0 while cont < n: print(n, end=", ") n = int(input("Digite: ")) imprimir(n)
false
1a8ea3a5f1983a0f5ef66f35685f27b52e5af392
PHILLIPEBLOOD/pythonquestions
/decisao/questd25.py
991
4.3125
4
'''Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". ''' print("0 para Não,\t 1 para sim") julga = int(input("Esteve no local do crime?")) julga += int(input("Telefonou para a vítima?: ")) julga += int(input("Mora perto da vítima?: ")) julga += int(input("Devia para a vítima?: ")) julga += int(input("Já trabalhou com a vítima?: ")) julgado = "Inocente" if(julga == 2): julgado = "Suspeita" elif(julga == 3 or julga == 4): julgado = "Cumplice" elif(julga == 5): julgado = "Assassino" print(julgado)
false
863ca5da1caa5585a0661baf3f7268f5090ab874
PHILLIPEBLOOD/pythonquestions
/string/quests1.py
936
4.28125
4
'''Tamanho de strings. Faça um programa que leia 2 strings e informe o conteúdo delas seguido do seu comprimento. Informe também se as duas strings possuem o mesmo comprimento e são iguais ou diferentes no conteúdo. Compara duas strings String 1: Brasil Hexa 2006 String 2: Brasil! Hexa 2006! Tamanho de "Brasil Hexa 2006": 16 caracteres Tamanho de "Brasil! Hexa 2006!": 18 caracteres As duas strings são de tamanhos diferentes. As duas strings possuem conteúdo diferente. ''' string1 = input() string2 = input() igualdade = "As duas strings possuem conteúdo diferente." if string1 == string2: igualdade = "As duas strings possuem conteúdo igual." tam1 = len(string1) tam2 = len(string2) string1 += str(tam1) string2 += str(tam2) tamanho = "As duas strings são de tamanhos diferentes." if tam1 == tam2: tamanho = "As duas strings são de tamanhos iguais." print(string1) print(string2) print(tamanho) print(igualdade)
false
c7d134cfabb926abfa32c50ee6e89de88ea987b6
PHILLIPEBLOOD/pythonquestions
/repeticao/questr8.py
236
4.21875
4
'''Faça um programa que leia 5 números e informe a soma e a média dos números. ''' soma = 0 for n in range(1, 6): numero = int(input("Numero: ")) soma += numero media = soma / 5 print("Soma: ", soma) print("Media: ", media)
false
e27300a48afbd15702297b8ec6d2a5b33d493b10
PHILLIPEBLOOD/pythonquestions
/string/quests5.py
225
4.3125
4
'''Nome na vertical em escada invertida. Altere o programa anterior de modo que a escada seja invertida. FULANO FULAN FULA FUL FU F ''' nome = input("Nome: ") i = len(nome) a = 1 while a <= i: print(nome[0:i]) i -= 1
false
bfc1b1dbc57b1f755badff44a4fee261a2d9247a
EladAssia/InterviewBit
/Binary Search/Square_Root_of_Integer.py
990
4.15625
4
# Implement int sqrt(int x). # Compute and return the square root of x. # If x is not a perfect square, return floor(sqrt(x)) # Example : # Input : 11 # Output : 3 ########################################################################################################################################## class Solution: # @param A : integer # @return an integer def sqrt(self, A): if A == 0: return 0 elif A <= 3: return 1 start = 1 end = int(A/2) while start < end: mid = int((start + end) / 2) if mid**2 == A: return mid elif mid**2 > A: end = mid - 1 else: start = mid + 1 if mid**2 > A: return mid - 1 else: return mid ##########################################################################################################################################
true
141a8525869b6a6f2747b61228f70224ae2fcc63
EladAssia/InterviewBit
/Two Pointers Problems/Merge_Two_Sorted_Lists_II.py
1,452
4.125
4
# Given two sorted integer arrays A and B, merge B into A as one sorted array. # Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. # TIP: C users, please malloc the result into a new array and return the result. # If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after your code is # executed should be m + n # Example : # Input : # A : [1 5 8] # B : [6 9] # Modified A : [1 5 6 8 9] ########################################################################################################################################## class Solution: # @param A : list of integers # @param B : list of integers def merge(self, A, B): idx1, idx2 = 0, 0 C = [] while idx1 < len(A) and idx2 < len(B): if A[idx1] < B[idx2]: C.append(str(A[idx1])) idx1 += 1 else: C.append(str(B[idx2])) idx2 += 1 if idx1 == len(A): for ii in range(idx2, len(B)): C.append(str(B[ii])) else: for ii in range(idx1, len(A)): C.append(str(A[ii])) A = ' '.join(C) A += ' ' print(A) ##########################################################################################################################################
true
38bd841245ca882be8cbade1bc9648aee3ea9073
EladAssia/InterviewBit
/Hashing/Anagrams.py
1,774
4.125
4
# Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the # index in the original list. Look at the sample case for clarification. # Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from 'rasp' # Note: All inputs will be in lower-case. # Example : # Input : cat dog god tca # Output : [[1, 4], [2, 3]] # cat and tca are anagrams which correspond to index 1 and 4. # dog and god are another set of anagrams which correspond to index 2 and 3. # The indices are 1 based ( the first element has index 1 instead of index 0). # Ordering of the result : You should not change the relative ordering of the words / phrases within the group. Within a group # containing A[i] and A[j], A[i] comes before A[j] if i < j. ########################################################################################################################################## def count_letters(word): d = {} for ii in word: if ii in d: d[ii] += 1 else: d[ii] = 1 string = '' for k in d: string += str(d[k]) string += k return string class Solution: # @param A : tuple of strings # @return a list of list of integers def anagrams(self, A): B = {} for ii in range(len(A)): let = count_letters(A[ii]) if let in B: B[let].append(ii+1) else: B[let] = [ii+1] lst = [] for k in B: lst.append(B[k]) return lst ##########################################################################################################################################
true
c7cc0ced10bcf0bf1bb0e4da0cd97fc978ac9dd6
zk18051/ORS-PA-18-Homework05
/task6.py
718
4.375
4
""" =================== TASK 6 ==================== * Name: Typewriter * * Write a script that will take file name as user * input. Then the script should take file content * as user input as well until user hits `Enter`. * At the end, the script should store the content * into the file with given name. If the file already * exists the script should append the new content * at the end. * * Note: Please describe in details possible cases * in which your solution might not work. * * Use main() function to test your solution. =================================================== """ print('File must have same path with project.') file = input('Enter a file name:') f = open(file ,'r+') print(f.read()) f.close()
true
f285ba64dd8d68b96db0f7430fe2cf8a9bb111d3
fatpat314/SPD1.4
/Homework2/leet_code.py
2,473
4.15625
4
# Q1 """Given an array of integers, return indices of the two numbers such that they add up to a specific target""" # restate question '''So we have an array of ints. we want to return the position of the index of two numbers that add to our target number''' # clearifying questions '''None''' # assumptions '''No negitive numbers, list is sorted''' # brainstorm '''hokay, so the example that is given is [2, 7, 11, 15], and the target = 9''' '''The first thing to come to mind is to loop over our list and check the indices to see if they add to the target. "for i in list, for j in list, j == i or j and i ++"''' '''But I think the better way to do it would be to find the differential and see if that it exists in the list''' list = [2, 7, 11, 15] target = 17 count = 0 def search(list, target): for i in list: first = list.index(i) diff = target - i if diff in list: second = list.index(diff) if diff + i == target: print('Your first index is ' + str(first)) print('Your second index is ' + str(second)) return diff, i else: print("Does not exist in list") print(search(list, target)) # recap/analysis ''' The way that I did it works well I think. It runs at a time complexity of O(n) I think if I were to use my first solution it would of had a complesity of O(n**2). Binary search would have been an interesting way to go, I am not sure if it would have been anymore time efficient.''' # Q2 """Given a 32-bit signed integer, reverse digits of an integer.""" # restate question '''We will be givin a integer, and we need to reverse the digits''' # clearifying questions '''What do you mean by "32-bit signed integer"?, is the int negitive?''' # brainstorm '''Ummm, there is just a fancy command I could do. But lets try not to use it. digits = digits[::-1] So with that in mind, lets try to make it into a new list.''' input = 123 def reverse(input): list = [] input = str(input) # input = list(input) n = -1 for i in range(len(input)): list.append(str(input[n])) n-=1 string = "" join = string.join(list) print(join) print(reverse(input)) # recap/analysis '''I would have much rathe used that command, but this would generally work except I think the time complexity would be O(n**2) due to the dependent loop and the append is also dependent on the size of the input'''
true
54f4b9f4d9b00e05ccf0e06ae96051cea6873fae
Chewie23/fluffy-adventure
/CodingTestForOpenGov/SortListAndOutputElement.py
913
4.25
4
from random import randrange from heapq import nlargest def organize_and_pull_K_biggest_num(num_of_elem, Kth): if Kth <= 0 or Kth > num_of_elem: print("That number is out of range!") exit(0) num_list = [] for n in range(num_of_elem): num_list.append(randrange(-100, 100)) print ("The unsorted list:", num_list) largest_K_num_list = nlargest(Kth, num_list) #"nlargest" makes a list of the top "K" largest numbers Kth_largest_num = largest_K_num_list[Kth - 1] print ("The #%d largest number in the list: %d" % (Kth, Kth_largest_num)) try: num_of_elem = int(input("Please enter how many numbers you want in the list: ")) Kth = int(input("Please enter a nonzero positive integer to determine 'Kth' biggest number: ")) except ValueError: print ("That is not a valid input!") else: organize_and_pull_K_biggest_num(num_of_elem, Kth)
true
2eea86811100bc9b0d3641ce9b31f58c503fa58d
Tweek43110/PyPractice
/Loops.py
1,679
4.1875
4
# There are two type of loops available FOR and WHILE # FOR examples simpleTest = [1,2,3,4] for number in simpleTest: print(number) # another useful example for i in range(12, 20): print(i) for evenNumbers in range(0,20,2): print(evenNumbers) # WHILE examples x = 0 while x < 5: print(x) x += 1 # BREAKs can help end a loop answer = 46 while True: print(answer) answer +=1 if answer >= 50: break # stops the loop from going on forever until crash # CONTINUE is used as an answer check for top in range(10): if x % 2 == 0: #checks that the answer does not have a remainder continue print(top) #Using ELSE statements count = 1 while(count < 9): print(count) count +=1 else: print('The counting loop has ended!') #Practice numbers = [ 951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527 ] for i in numbers: if i % 2 == 0: print(i) i +=i if i == 237: break # Or the soultion could be: #for i in numbers: #if number == 237: STOPS FOR THE REQUESTED NUMBER #break #if number %2 == 1; IF THE NUMBER IS NOT EVEN IT WILL NOT BE PRINTED #continue #print(number)
true
5c535cf88790186b556a71dacc4eb4b6482ea4db
OliveiraFabioPereirade/introducao_python
/aula11.py
1,450
4.125
4
# lista de exceções nativas do python # https://docs.python.org/3/library/exceptions.html lista = [10, 1] try: arquivo = open('teste.txt', 'r') texto = arquivo.read() divisao = 10/0 # força erro: divisão por zero # numero = lista[3] # força erro: excedeu número de elementos da lista # x = a # força erro: variável não definida # print('fechando arquivo') #neste ponto, o arquivo não será fechado, caso ocorra um erro # arquivo.close() except ZeroDivisionError: # trata erro de divisão por zero print('Não é possível realizar uma divisão por zero!') except IndexError: # trata erro de índice print('Erro ao acessar um índice inválido da lista!') except BaseException as ex: # trata erro pela exceção pai de todas as exceções: pega descrição da exceção e chama de "ex" print('Erro desconhecido. Erro: {}' .format(ex)) # exibe a descrição da exceção except: # trata erro genérico print('Ocorreu um erro desconhecido!') else: # trata quando não ocorre erro print('Executa quando não ocorreu nenhum erro!') finally: # trecho que é executado com ou sem erro print('Sempre executa!') print('fechando arquivo') #neste ponto, o arquivo sempre será fechado, caso ocorra um erro ou não arquivo.close() ### lembrar que o tratamento é uma árvore e é melhor colocar as exceções filhas antes das exceções pais ### a primeira que atender salta as demais
false
46d626b6ae270bca958857b813b6baea359b8804
hongkailiu/test-all
/trunk/test-python/script/my_exception.py
922
4.1875
4
#!/usr/bin/python def kelvin_to_fahrenheit(temperature): """test exception""" assert (temperature >= 0), "Colder than absolute zero!" return ((temperature - 273) * 1.8) + 32 print kelvin_to_fahrenheit(273) print int(kelvin_to_fahrenheit(505.78)) # will raise an exception # print kelvin_to_fahrenheit(-5) try: print kelvin_to_fahrenheit(-5) except AssertionError, e: print "AssertionError with message", e.message else: print "everything is fine" # Here is an example related to RuntimeError. # Here, a class is created that is sub-classed from RuntimeError. # This is useful when you need to display more specific information when an exception is caught. class NetworkError(RuntimeError): def __init__(self, arg): self.args = arg self.message = "test error message" try: raise NetworkError("Bad hostname") except NetworkError, e: print e.args, ":", e.message
true
8813818cf837609e9c75a9ae8ddfd1954246ba7f
RizwanRumi/python_Learning
/OOP/constructor_callingmethod.py
999
4.21875
4
class eval_equations: # single constructor to call other methods def __init__(self, *inp): # when 2 arguments are passed if len(inp) == 2: self.ans = self.eq2(inp) # when 3 arguments are passed elif len(inp) == 3: self.ans = self.eq1(inp) # when more than 3 arguments are passed else: self.ans = self.eq3(inp) def eq1(self, args): x = (args[0] * args[0]) + (args[1] * args[1]) - args[2] return x def eq2(self, args): y = (args[0] * args[0]) - (args[1] * args[1]) return y def eq3(self, args): temp = 0 for i in range(0, len(args)): temp += args[i] * args[i] temp = temp / max(args) z = temp return z inp1 = eval_equations(1, 2) inp2 = eval_equations(1, 2, 3) inp3 = eval_equations(1, 2, 3, 4, 5) print("equation 2 :", inp1.ans) print("equation 1 :", inp2.ans) print("equation 3 :", inp3.ans)
false
382861d6c759a0954249f94c18732f562183bebf
jahick/pythonSamples
/convert.py
901
4.1875
4
# Put your code here decimal = int(input("Enter an integer: ")); base = int(input("Enter a base number to convert to. (2, 8, 10, 16): ")); def decimalToRep(decimal,base): if base == 10: return decimal; elif base == 2: return str(bin(decimal)[2:]); elif base == 8: return oct(decimal)[2:]; elif base == 16: hexString = hex(decimal)[2:]; return hexString.upper(); else: print("Please choose a valid base. (2, 8, 10, 16)"); # A main for testing your program def main(): """Tests the function.""" print("") print("Testing:") print(decimalToRep(10, 10)); print(decimalToRep(10, 8)); print(decimalToRep(10, 2)); print(decimalToRep(10, 16)); print(""); print("Real:") print(decimalToRep(decimal,base)); # The entry point for program execution if __name__ == "__main__": main();
true
aacf2efce41b7894a1e69ab400e9efdffcb16758
goosen78/simple-data-structures-algorithms-python
/bubble_sort.py
912
4.4375
4
#!/usr/bin/env python3 """ Bubble Sort Script """ def bubble_sort(L): """ Sorts a list in increasing order. Because of lists are mutable this function does not have to return something. This algorithm uses bubble sort. @param L: a list (in general unsorted) """ for i in range(len(L) - 1): already_sorted = True for j in range(len(L) - i - 1): if L[j] > L[j + 1]: already_sorted = False L[j], L[j + 1]= L[j + 1], L[j] # if no swaps were developed in the previous loop, # it means that the list is already sorted. Thus, # loop is exited and function terminates (returns None) if already_sorted: break list1 = [1, -2, 3, 2, 0, 4, -1, 2, 0, 1, -5, 5, -6] #list1 = [2, 1, -1] bubble_sort(list1) print(list1)
true
81c3ccbe5b8b5a1464a2244761a38c18f60e265d
imrajashish/python-prog
/heap&queu.py
789
4.4375
4
#Write a Python program to find the three largest integers from a given list of numbers using Heap queue algorithm import heapq h = [12,34,56,786,56,45,3,453] print("Three largest number in list: ") print(heapq.nlargest(3,h)) #Write a Python program to find the three smallest integers from a given list of numbers using Heap queue algorithm. import heap h = [12,34,56,786,56,45,3,453] print("original list",h) print(heapq.nsmallest(3,h)) #Write a Python program to implement a heapsort by pushing all values onto a heap and then popping off the smallest values one at a time. import heapq as hq def heapsort(iterable): h = [] for value in iterable: hq.heappush(h, value) return [hq.heappop(h) for i in range(len(h))] print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
true
3d7582f3f5e45f2d1819763c4e96a3b4c5e26bb8
imrajashish/python-prog
/list2.py
550
4.625
5
#Write a Python program to extract the nth element from a given list of tuples. def extract_nth_element(test_list, n): result = [x[n] for x in test_list] return result students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] print ("Original list:") print(students) n = 0 print("\nExtract nth element ( n =",n,") from the said list of tuples:") print(extract_nth_element(students, n)) n = 2 print("\nExtract nth element ( n =",n,") from the said list of tuples:") print(extract_nth_element(students, n))
true
95bd03109ce74e6f3207be3dfa2f7ff15cd26840
imrajashish/python-prog
/lambda2.py
2,376
4.34375
4
#Write a Python program to sort a list of dictionaries using Lambda. models = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'Mi Max', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}] print("\n originals dict in model:") print(models) sorted_models = sorted(models,key = lambda x:x['color']) print(sorted_models) #Write a Python program to filter a list of integers using Lambda. nums = [1,23,24,65,97,87,98,89] print("\n Original nums") print(nums) even_nums=list(filter(lambda x: x%2 ==0,nums)) print(even_nums) odd_nums=list(filter(lambda x: x%2 !=0,nums)) print(odd_nums) #Write a Python program to square and cube every number in a given list of integers using Lambda. nums = [12,23,34,56,78,87] print(nums) square_nums = list(map(lambda x: x ** 2, nums)) print("\n square of nums:") print(square_nums) cube_nums = list(map(lambda x: x ** 3, nums)) print("\n cube of nums:") print(cube_nums) #Write a Python program to find if a given string starts with a given character using Lambda. starts_with = lambda x: True if x.startswith('P') else False print(starts_with('Python')) starts_with = lambda x: True if x.startswith('P') else False print(starts_with('Java')) #Write a Python program to extract year, month, date and time using Lambda. import datetime now = datetime.datetime.now() print(now) year = lambda x : x.year month = lambda x : x.month date = lambda x : x.date t = lambda x : x.time() print(year(now)) print(month(now)) print(date(now)) print(t(now)) #Write a Python program to check whether a given string is number or not using Lambda. is_num = lambda q: q.replace('.','',1).isdigit() print(is_num('26587')) print(is_num('4.2365')) print(is_num('-12547')) print(is_num('00')) print(is_num('A001')) print(is_num('001')) print("\nPrint checking numbers:") is_num1 = lambda r: is_num(r[1:]) if r[0]=='-' else is_num(r) print(is_num1('-16.4')) print(is_num1('-24587.11')) #Write a Python program to create Fibonacci series upto n using Lambda. from functools import reduce fib_series = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1]) print("Fibonacci series upto 2:") print(fib_series(2)) print("\nFibonacci series upto 5:") print(fib_series(5)) print("\nFibonacci series upto 6:") print(fib_series(6)) print("\nFibonacci series upto 9:") print(fib_series(9))
true
c0ef45938c2daadcd8095d36ef7037c502ad0fc1
imrajashish/python-prog
/lambda3.py
2,251
4.28125
4
#Write a Python program to find intersection of two given arrays using Lambda num1 = [1,2,3,4,5,6,7,8,7] num2 = [3,4,5,6,6,8,8,9,8,7] print("\n original arrays:") print(num1) print(num2) result = list(filter(lambda x: x in num1,num2)) print("\n Intersection of the said array: ",result) #Write a Python program to rearrange positive and negative numbers in a given array using Lambda. num1 = [12,23,43,54,5,-2,-3,-4,-3232] print("\n original array: ") print(num1) result = [x for x in num1 if x<0] + [x for x in num1 if x>0] print(result) #Write a Python program to count the even, odd numbers in a given array of integers using Lambda. array_nums = [1,2,3,4,5,67,76,678,78,789,989,90,-1] print("\n original array: ") print(array_nums) odd_ctr = len(list(filter(lambda x: (x%2 != 0) , array_nums))) even_ctr = len(list(filter(lambda x: (x%2 == 0) , array_nums))) print(odd_ctr) print(even_ctr) # Write a Python program to find the values of length six in a given list using Lambda. weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] days = filter(lambda day: day if len(day)==6 else '', weekdays) for d in days: print(d) #Write a Python program to add two given lists using map and lambda. nums1 = [1, 2, 3] nums2 = [4, 5, 6] print("Original list:") print(nums1) print(nums2) result = map(lambda x, y: x + y, nums1, nums2) print("\nResult: after adding two list") print(list(result)) #Write a Python program to find the second lowest grade of any student(s) from the given names and grades of each student using lists and lambda. Input number of students, names and grades of each student. students = [] sec_name = [] second_low = 0 n = int(input("Input number of students: ")) for _ in range(n): s_name = input("Name: ") score = float(input("Grade: ")) students.append([s_name,score]) print("\nNames and Grades of all students:") print(students) order =sorted(students, key = lambda x: int(x[1])) for i in range(n): if order[i][1] != order[0][1]: second_low = order[i][1] break print("\nSecond lowest grade: ",second_low) sec_student_name = [x[0] for x in order if x[1] == second_low] sec_student_name.sort() print("\nNames:") for s_name in sec_student_name: print(s_name)
true
d1f0d16d6f96eeec6981e70ead1cf21d33762dd3
brianchun16/PythonPractices
/Lecture04/practice1_while.py
238
4.15625
4
x = int(input('Enter an integer: ')) x = abs(x) ans = 0 while ans**3 < x: ans = ans+1 if ans**3 == x: print('X is a perfect cube') print('The X value is: ', ans) else: print('X is not a perfect cube') print('The X value is:', ans)
true
ff0b42c3fd172deb291c9e510b3f1cff9ef61497
nikhilgurram97/CS490PythonFall2017
/Lab Assignment 1/gameboard.py
611
4.25
4
hinp=int(input("Enter Height of Board : ")) winp=int(input("Enter Width of Board : ")) #For taking input height and input width respectively def board_draw(height,width): #Initializing a drawing function for j in range(0,height): #In this loop, the reverse shaped 'U's are drawn which contains - and |, according to count given print(" --- "*width) print("| | "*width) print(" --- "*width) # prints the last line of '---' board_draw(hinp,winp) #draws board using the function
true
1a4d6a0fc3ae833fa1bb09a2130c9d11eab3417a
plammens/python-introduction
/Fundamentals I/Elements of Python syntax/Statements expressions/main.py
1,011
4.40625
4
# ----- examples of statements (each separated by a blank line): ----- import math # import statement my_variable = 42 # assignment statement del my_variable # del statement if __name__ == '__main__': # if statement print('executing as script') # else: # print('false') # assert True # assert statement 13 + 45 # expression statement (a statement which only evaluates an expression when executed) print("hello world") # expression statement # ----- examples of expressions (each on its own line): ----- 42 # an integer literal "a string" # a string literal None # the special value None (which is also a keyword) 2*(3 + 1) # the expression '(3 + 1)' is nested within the expression '2*(3 + 1)' 12*3 + 10**(42//7) str(123) # a function call is an expression because it has a value (the return value of the call) print("hello world") is None # print is a function, so calling it is an expression with a value
true
a2b0fd51ade7db2efafb76fab1291b73ccf516af
rduvalwa5/Examples
/PythonExamples/src/PyString.py
2,687
4.21875
4
''' Created on Mar 24, 2015 @author: rduvalwa2 https://docs.python.org/3/library/string.html?highlight=string#module-string https://docs.python.org/3/library/stdtypes.html#string-methods This is how to reverse a string http://stackoverflow.com/questions/18686860/reverse-a-string-in-python-without-using-reversed-or-1 ''' class py_string: def __init__(self,strng = "NoString"): self._inString = strng def reverse(self,text = "Not a string"): if len(text) <= 1: return text return self.reverse(text[1:]) + text[0] def reverseSimple(self, text): return text[::-1] def makeUpper(self,text): return text.upper() def makeLower(self, text): return text.lower() def makeCaps(self, text): return text.capitalize() def splitString(self, text, sep): return text.split(sep) def stringJoin(self,itr,seq): #list return itr.join(seq) def stringReplace(self,text,original,replacement,maxreplace=1): return text.replace(original,replacement,maxreplace) ''' s = "This is a string of words. It has punctuation! Does't it? But \"not this\"." s1 = "1234567890ABcdefG{};:" print(s) print(s[0]) print(s[3:15]) for a in s: if a in {".","?","!","'","\""}: print(a) print("upper " ,s.upper()) print("lower ", s.lower()) print("capitalize ",s.capitalize()) print(s.count("i")) print(s.count("i",20,-1)) s = s + s1 print(s) print("s[::-1]" ,s[::-1]) print("reverse(s)",reverse(s)) ''' if __name__ == '__main__': myString = "New string with punctuation! What do you think? No way." s1 = py_string() print(s1._inString) print(s1.reverse()) print(s1.reverseSimple(s1._inString)) s2 = py_string(myString) print(s2._inString) print(s2.reverse(myString + "0987654321")) print(s2.reverse()) print("double reverse ", s2.reverse(s2.reverseSimple(myString))) capString = "one two three four five. Six seven eight?" print(capString) print("Capitilize",s2.makeCaps(capString)) print("split", s2.splitString(capString, " ")) splitString = s2.splitString(capString, " ") print("spliotString ", splitString) newString = "" for word in splitString: newString = newString + s2.makeCaps(word) + " " print(newString) separator = "+" seq = ("one","two","three","four") print("Join ", s2.stringJoin(separator,seq)) stringR = "one two three four five two. Six seven eight two?" print(s2.stringReplace(stringR,"two","twelve")) print(s2.stringReplace(stringR,"two","twelve",2))
true
d570c49f66084ad88db859791decfc6b6e296911
Shashwat15/GitHackeve
/project1.py
657
4.25
4
def fib(number_for_fibonacci): # Add code here return #Fibonacci number def is_prime(number_to_check): n=0 while n<=b/2: if b/n==0: print ("not prime") elif b/n!=0: print ("prime") n=n+1 return #boolean value def reverse_string(string_to_be_reversed): a=list(string_to_be_reversed) a.reverse() str1="" for i in a: str1=str1+i return str1 #Take input for fib in variable a print(fib(a)) #Take input for is_prime in variable b b=int(input()) print(is_prime(b)) #Take input for reverse in variable c c=input() print(reversed_string(c))
false
65059eda46952316221245f7b021616acb7b7c87
Exubient/UTCS
/Python/Assignment 4/assignment4.py
2,830
4.15625
4
""" Assignment 4: Metaprogramming The idea of this assignment is to get you used to some of the dynamic and functional features of Python and how they can be used to perform useful metaprogramming tasks to make other development tasks easier. """ #Hyun Joong Kim #hk23356 import functools import logging import sys def logcalls(prefix): """ A function decorator that logs the arguments and return value of the function whenever it is called. The output should be to sys.stderr in the format: "{prefix}: {function name}({positional args}..., {keyword=args}...)" and "{prefix}: {function name} -> {return value}" respectively for call and return. Look up functools.wraps and use it to make the function you return have the same documentation and name as the function passed in. This will be used like: @logcalls("test") def f(arg): return arg (This is a more refined version of what I did in class) """ def decorator(func): @functools.wraps(func) def inner(*args, **kwargs): value=func(*args, **kwargs) joined_args = ", ".join([repr(args) for args in args] + [kwargs[0] + "=" + repr(kwargs[1]) for kwargs in kwargs.items()]) sys.stderr.write(prefix +": " + func.__name__ + "(" + joined_args+ ")\n" ) sys.stderr.write(prefix + ": " + func.__name__ + " -> "+ repr(value) + "\n" ) return value return inner return decorator def module_test(mod): """ Run all the test functions in the module mod (which is a module object). A test function is a function with a name that begins with "test". All the test functions take no arguments and throw an exception if the test fails. For each test, print a block to stderr in the following format: {test function name}: {either PASS or FAIL: {exception type name} {exception as a string}} {test function doc string} For example of a test is defined: def testA(): '''Test A''' raise RuntimeError("Blah") Your function should print: testA: FAIL: RuntimeError 'Blah' Test A Make sure you handle functions without doc strings without crashing (you can treat it as an empty doc string). """ for tests in mod.__dict__: if tests.startswith('test'): if callable(mod.__dict__[tests]): if(mod.__dict__[tests])(): sys.stderr.write (tests +': PASS') else: sys.stderr.write (tests +': FAIL :' + mod.__dict__[tests]) sys.stderr.write('\n') sys.stderr.write(mod.__dict__[tests].__doc__)
true
537fc9c10ae830cd564ae892235719b048178bb3
johncmk/cloud9
/rec_pointer.py
726
4.3125
4
''' Updating the el in the li while traversing in recursion can effect the changes of original value of the li in running time because its updating the value via address. Updating the value that is pass by value through recursion would not change the orginal value beause it copies the value before it goes into the next stack frame ''' def foo(x,n=3): if n == 0: return 0 a = foo(x,n-1) b = foo(x,n-1) x = max(x, a+b) return x def foo_li(li,n=3): if n == 0: return 0 a = foo_li(li,n-1) b = foo_li(li,n-1) li[0] = max(li[0], a+b) return li[0] if __name__ == "__main__": li = [5,4,3,2,1] print foo(1) # >> 4 print foo_li([1]) # >> 6
true
2b4c15c744d01b2a58a72f47a4b9bcca85336c2c
johncmk/cloud9
/qsort_CLRS.py
792
4.125
4
'''This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot''' def partition(arr,low,high): i = (low-1) pivot = arr[high] '''''' for j in range(low, high): if arr[j] <= pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return (i+1) def quickSort(arr,low,high): if low < high: pi = partition(arr,low,high) quickSort(arr,low,pi-1) quickSort(arr,pi+1,high) if __name__ == "__main__": li = [5,4,3,2,1] quickSort(li,0,len(li)-1) print li
true
fe0846d78614934ff88ecbe3a04dc09e9b77e9b4
johncmk/cloud9
/Perm_Comb.py
1,351
4.3125
4
'''Factorial function means to multiply a series of descending natural number 3! = 3 x 2 x 1 Note: it is generally agreed that 0! = 1. It may seem funny that the multiplying no numbers together gets us 1, but it helps simplify a lot of equation.''' '''non-tail recursion; waste more memory when n is big integer such as 1,000,000.''' def fact(n): if n <= 1: return n return n * fact(n-1) '''tail recursion; save more stack frame even though the integer is big such as 1,000,000''' def fact_tail(n, ret = 1): if n <= 1: return ret return fact_tail(n-1,ret*n) '''PERMUTATION: To find the number of ways k items can be order in n times''' def perm(n,k): numerator = fact_tail(n) denominator = fact_tail(n-k) return numerator / denominator '''COMBINATION: The number of ways to combine k items from a set of n''' def comb(n,k): numerator = perm(n,k) denominator = fact_tail(k) return numerator / denominator if __name__ == "__main__": '''Permutation: How many ways can we award a 1st, 2nd and 3rd place prize among 10 contestants? (Gold / Silver / Bronze)''' print "Permutation : ",perm(10,3) '''Combination: How many ways can I give 3 tin cans to 10 people? ''' print "combination : ",comb(10,3)
true
97dc89fba3c044b3da16e5fcf6468ecd45d33efb
timvan/reddit-daily-programming-challenges
/multiplication_table.py
569
4.21875
4
# Multiplication Table # Request two numbers and create the multiplication table of those numbers def start(): print ("Welcome to multiplication table emulator!") print ("Choose two numbers to create a multiplication table!") while True: N1 = raw_input("Number 1:") try: N1 += 1 except TypeError: if not isinstance(N1 , (int, long)) print('Error: Insert Whole Number') else: N2 = raw_input("Number 2:") if not isinstance( N2,(int,long)) print('Error: Insert Whole Number') else: print("Here..") quit() start()
true
59dd3f87c0c58dc421fcf023143edc716299389c
darloboyko/py_courses
/codewars/kata_7/NegativeConnotation_04.py
1,214
4.46875
4
#You will be given a string with sets of characters, (i.e. words), seperated by between one and # three spaces (inclusive). #Looking at the first letter of each word (case insensitive-"A" and "a" should be treated the same), # you need to determine whether it falls into the positive/first half of the alphabet ("a"-"m") # or the negative/second half ("n"-"z"). #Return True/true if there are more (or equal) positive words than negative words, False/false otherwise. #"A big brown fox caught a bad rabbit" => True/true #"Xylophones can obtain Xenon." => False/false #https://www.codewars.com/kata/5ef0456fcd067000321baffa/train/python def connotation(strng): strng = list(strng.replace(' ','').lower()) newstring = "".join(c for c in strng if c.isalpha()) positive = 0 chars_p = list('abcdefghijklm') for i in newstring: if i in chars_p: positive += 1 return positive >= (len(newstring)-positive) strng = str(input("String: ")) print(connotation(strng)) print(connotation("Xylophones can obtain Xenon.")) print(connotation("A big brown fox caught a123456123!@#$ bad bunn")) print(connotation("A big brown fox caught a bad rabbit"))
true
46b238bee670488bed3f121c59febe2abce590c3
darloboyko/py_courses
/codewars/kata_8/task_01.py
1,169
4.28125
4
'''David wants to travel, but he doesn't like long routes. He wants to decide where he will go, can you tell him the shortest routes to all the cities? Clarifications: David can go from a city to another crossing more cities Cities will be represented with numbers David's city is always the number 0 If there isn't any route to a city, the distance will be infinite (float("inf")) There's only one road between two cities Routes are one-way (start city -> end city) The arguments are: n: the number of cities (so the cities are numbers from 0 to n-1 inclusive) routes: a list of routes (tuples): (start city, end city, length) The output is a list of shortest routes (tuples) from David's city to all the others, sorted by city number: (city number, distance) Example: shortest_routes(3, [(0, 1, 1), (0, 2, 10), (1, 2, 2)]) # return [(1, 1), (2, 3)]''' routes = list[(0, 1, 1), (0, 2, 10), (1, 2, 2)] distance = [] visited_city = [] #def shortestRoutes(n=3): for rout in len(routes): if routes[rout][2]<routes[rout+1][2]: distance.append(routes[rout][2]) visited_city.append(routes[rout][1]) print(distance) print(visited_city)
true
609d502011f4d6dbb5bac47aaa2f8c93a7a7819f
darloboyko/py_courses
/codewars/kata_7/comfortableWords_04.py
1,348
4.1875
4
#A comfortable word is a word which you can type always alternating the hand you type with #(assuming you type using a QWERTY keyboard and use fingers as shown in the image below). #That being said, create a function which receives a word and returns true/True if it's a # comfortable word and false/False otherwise. #The word will always be a string consisting of only ascii letters from a to z. #To avoid problems with image availability, here's the lists of letters for each hand: #Left: q, w, e, r, t, a, s, d, f, g, z, x, c, v, b #Right: y, u, i, o, p, h, j, k, l, n, m def comfortable_word(word): result = [] left = ['q', 'w', 'e', 'r', 't', 'a', 's', 'd', 'f', 'g', 'z', 'x', 'c', 'v', 'b'] right = ['y', 'u', 'i', 'o', 'p', 'h', 'j', 'k', 'l', 'n', 'm'] for i in word.lower(): if i in left: result.append('left') elif i in right: result.append('right') print(result) for n in range(1, len(result)): if result[n-1] == result[n]: return False else: continue return True #word = str(input("Word: ")) #print(comfortable_word(word)) print(comfortable_word("lalalalalalalal")) #print(comfortable_word("A big brown fox caught a123456123!@#$ bad bunn")) #print(comfortable_word("A big brown fox caught a bad rabbit"))
true
213e764cb9f5daa61e1a52034de135ad1c131b99
darloboyko/py_courses
/homeworks/home_work_4/PrintNumberInWord.py
649
4.1875
4
#Написать программу с названием “PrintNumberInWord”, # которая напечатает “ONE”, “TWO”, …, “NINE”, # “OTHER” если переменная “number” типа int будет 1, 2, 3, 4, … 9, или любой другой. number = int(input("number: ")) if number == 1: print("ONE") elif number == 2: print("TWO") elif number == 3: print("THREE") elif number == 4: print("FOUR") elif number == 5: print("FIVE") elif number == 6: print("SIX") elif number == 7: print("SEVEN") elif number == 8: print("EIGHT") elif number == 9: print("NINE") else: print("OTHER \n")
false
5e4348ef368e6c84323177ab213768049cb940fe
darloboyko/py_courses
/homeworks/home_work_6/SumOfTwoColumns.py
663
4.1875
4
#5. Написать программу, которая считает сумму двух колонок. Если одна из колонок имеет больший размер # - вывести, какая колонка больше. Если колонки одинаковы, вывести результат так: # | row_1 | row_2 | sum | # | 2 | 5 | 7 | row_1 = [1, 2, 5, 6, 54] row_2 = [11, 5, 5, 7, 3] if len(row_1) == len(row_2): for i in range(0, len(row_1)): print("|",row_1[i],"|",row_2[i],"|", row_1[i]+row_2[i], "|") elif len(row_1) > len(row_2): print("The row_1 biggest") else: print("The row_2 biggest")
false
8733c8cf2c440511396a3f70075dbcbb9a2aab73
darloboyko/py_courses
/homeworks/home_work_3/task_04.py
567
4.125
4
#Посчитать площадь треугольника по формуле Герман: #S = sqrt(p * (p-a) * (p-b) * (p-c)) #Где p = (a + b+ c) / 2 - полупериметр треугольника #Сделать 3 варианта возведения в степень import math a = float(input("Enter a: ")) b = float(input("Enter b: ")) c = float(input("Enter c: ")) p = (a + b + c) / 2 S = ((p * (p-a) * (p-b) * (p-c))**(1/2)) print(S) S = pow((p * (p-a) * (p-b) * (p-c)), 1/2) print(S) S = math.sqrt((p * (p-a) * (p-b) * (p-c))) print(S)
false
b8a5f2c3249336321cce13fc43cce156f4f37283
darloboyko/py_courses
/homeworks/home_work_2/part_1/temperature.py
765
4.34375
4
# Написать программу, которая умеет переводить температуру из C в из Фаренгетов и Кельвинов Например: # дана температура в Цельсиях 25 С # Фаренгейт: 45.9F - считается по формуле (C + 32) * 5/9 # Кельвины: 298.16K - считается по формуле C + 273.16 print("Temperature converter") temperature_сelsius = int(input("Enter temperature_сelsius: ")) temperature_kelvin = (temperature_сelsius + 273.16) temperature_fahrenheit = (temperature_сelsius * 9/5 +32) print("Temperature in Kelvin:", round(temperature_kelvin, 2), "K") print("Temperature in Fahrenheit:", round(temperature_fahrenheit, 2), "F")
false
f6ce75e92016710e60e625e80adfb0911d7b44ec
darloboyko/py_courses
/codewars/kata_7/niceArray_03.py
575
4.21875
4
#A Nice array is defined to be an array where for every value n in the array, there is also an # element n-1 or n+1 in the array. #example: #[2,10,9,3] is Nice array because #2=3-1 #10=9+1 #3=2+1 #9=10-1 #Write a function named isNice/IsNice that returns true if its array argument is a Nice array, else false. # You should also return false if input array has no elements. #https://www.codewars.com/kata/59b844528bcb7735560000a0/train/python arr = [2,10,9,3] is_nice = lambda arr: sorted(arr) map(is_nice, arr) "even" if sum(arr)%2 == 0 else "odd" print(is_nice(arr))
true
771ca2a109d51e3aa667106e3b44c071a1cb86f3
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_13.py
2,667
4.90625
5
""" Exercise 13: Parameters, Unpacking, Variables In this exercise we will cover one more input method you can use to pass variables to a script (script being another name for you .py files). You know how you type python lesson_03.py to run the lesson_03.py file? Well the lesson_13.py part of the command is called an "argument". What we'll do now is write a script that also accepts arguments. """ from sys import argv # line 1 script, first, second = argv # line 3, third print "The script is called: ", script print "Your first variable is: ", first print "Your second variable is: ", second # print "Your third variable is: ", third """ On line 1 we have what's called an "import". This is how you add features to your script from the Python feature set. Rather than give you all the feature at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts documentation for other programmers who read you code later. The argv is the "argument variable", a very standard name in programming, that you will find used in many other language. This variable holds the arguments you pass to your Python script when you run it. In the exercise you will get to play with this more and see what happens. Line 3 "unpacks" argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third. This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in argv, unpack it, and assign it to all of these variables on the left in order". """ """ Hold Up! Features Have Another Name I call them "features" here (these little things you import to make your Python program do more) but nobody else call them features. I just used that name because I needed to trick you into learning what they are without jargon. Before you can continue, you need to learn their real name: modules. From now on we will be calling these "features" that we import modules. I'll say things like, "You want to import the sys module". They are also call "libraries" by other programmers, but let's just stick with modules. """ """ Study Drills 1. Try giving fewer than three arguments to your script. See that error you get? 2. Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variable good names. 3. Combine raw_input with argv to make a script that gets more input from a user. 4. Remember that modules give you features. Modules. Modules. Remember this because we'll need it later. """
true
308bdfde1b97e5dc0f719c1c620d257479c55464
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_18.py
2,333
4.75
5
""" Exercise 18: Name, Variables, Code, Functions Functions do three things: 1. They name pieces of code the way variables name strings and numbers. 2. They take arguments the way your scripts take argv. 3. Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands". You can create a function by using the word def in Python. """ # this one is like you scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." print_two("Zed", "Shaw") print_two_again("Zed", "Shaw") print_one("First!") print_none() """ Study Drills ***** Create a function checklist for later exercises. Write these checks on an index card and keep it by you while you complete the rest of these exercise or until you feel you do not need the index card anymore: 1. Did you start your function definition with def? 2. Does your function name have only characters and _ (underscore) characters? 3. Did you put an open parenthesis ( right after the function name? 4. Did you put your arguments after the parenthesis ( separate by commas? 5. Did you make each argument unique (meaning no duplicated names)? 6. Did you put a close parenthesis and a colon ): after arguments? 7. Did you "end" your function by going back to writing with on indent (dedenting we callit)? ***** When you run ("use" or "call") a function, check these things: 1. Did you call/use/run this function by typing its name? 2. Did you put the ( characters after the name to run it? 3. Did you put the values you want into the parenthesis separated by commas? 4. Did you end the function call with a ) character? Use these two checklist on the remaining lessons until you do not need them anymore. Finally, repeat this a few times to yourself: "To 'run', 'call', or 'use' a function all mean the same thing." """
true
14626d6e41bbc14f2569725273aa3aad5210d8cf
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_20.py
1,703
4.46875
4
""" Exercise 20: Functions and Files """ from sys import argv # get the input file name from terminal [script, input_file] = argv def print_all(f): # output a whole file print f.read() def rewind(f): # jump to the beginning of a file f.seek(0) def print_a_line(line_count, f): # output a line of the file print line_count, f.readline() # open a file current_file = open(input_file) print "First let's print the whole file:\n" # print the whole file print_all(current_file) print "Now let's rewind, kind of like a tape." # jump the reader to the beginning of the file rewind(current_file) print "Let's print three lines:" # output the first line of the file current_line = 1 print_a_line(current_line, current_file) # output the second line of the file # current_line = current_line + 1 current_line += 1 print_a_line(current_line, current_file) # output the third line of the file # current_line = current_line + 1 current_line += 1 print_a_line(current_line, current_file) """ Study Drills 1. Write English comments for each line to understand what that line does. 2. Each time print_a_line is run, you are passing in a variable current_line. Write out what current_line is equal to on each function call, and trace how it becomes line_count in print_a_line. 3. Find each place a function is used, and check its def to make sure that you are giving it the right arguments. 4. Research online what the seek function for file does. Try pydoc file and see if you can figure it out from there. Then try pydoc file.seek to see what see does. 5. Research the shorthand notation += and rewrite the script to use += instead. """
true
46f2a1f6ce47d9f80f71ef4250d3b3389068f2ca
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_23.py
2,091
4.46875
4
""" ***** Exercise 23: Read Some Code You should have spent the last week getting your list of symbols straight and locked in your mind. Now you get to apply this to another week of reading code on the internet. This exercise will be daunting at first. I'm going to throw you in the deep end for a few days and have you just try your best to read and understand some source code from real project. The goal isn't to get you to understand code, but to teach you the following three skills: 1. Finding Python source code for things you need. (how about Deep learning?) 2. Reading through the code and looking for files. 3. Trying to understand code you find. At your level you really do not have the skills to evaluate the things you find, but you can benefit from getting exposure and seeing how things look. When you do this exercise think of yourself as an anthropologist, trucking through a new land with just barely enough of the local language to get around and survive. Except, of course, that you will actually get out alive because the internet isn't a jungle. Here's what you do: 1. Go to bitbucket.org, github.com, or gitorious.org with your favorite web browser and search for "Python". 2. Pick a random project and click on it. 3. Click on the Source tab and browse through the list of files and directories until you find a .py file. 4. Start at the top and read through the code, taking notes on what you think it does. 5. If any symbols or strange words seem to interest you, write them down to research later. That's it. Your job is to use what you know so far and see if you can read the code and get a grasp of what it does. Try skimming the code first, and then read it in detail. Try taking very difficult parts and read each symbols you know out loud. Now try some of these other sites: github.com launchpad.net gitorious.org sourceforge.net """
true
230bba3cff67045255bc24d2d6b6702a42d0fb75
tmcook23/NICAR-2016
/intro-to-python/part2/2_files.py
739
4.15625
4
# Import modules import csv # Write a function that accepts one file name as an argument. # The function should print each row from a csv file as well as each row's length and its type. def output_rows_from(file_name): # Open the csv csv_file = open(file_name, 'rb') # Create the object that represents the data in the csv file csv_data = csv.reader(csv_file) # Loop through each row in the object for row in csv_data: # Output the contents print row # Output the length of the row print len(row) # Output the type print type(row) # Close the csv file csv_file.close() # Call the function, passing as an argument the name of the csv file to open. output_rows_from('../data/marijuana_gross_sales.csv')
true
59665fb98044dc3610126dd3b08b1cc43ce0b8d7
tmcook23/NICAR-2016
/intro-to-python/part1/1_workingwintegers.py
1,402
4.375
4
#INTEGERS #In programming, an integer is a whole number. You can do all sorts of math on integers, #just like you'd do with a calculator or in Excel or a database manager. 2+2 5*5 # In the command line Python interpreter, these results will always show up. # But if you run an entire Python (.py) program, however short, they won't. # To get results to actually appear, you need to "print" them to the screen. print 2+2 print 100/5 # Order of operations works the same as real-world math you learned back in grade school 2+2*10 # ...is different than: (2+2)*10 # VARIABLES # Instead of always using actual values, we can create a VARIABLE to hold it # It's kind of like a nickname, but much more than that. # It stores the value and let's us do things with it. mynumber = 14 # Let's print to see what we get print mynumber # Once you have a variable, you can run math on it by using its name like you would the number # Multiplication print mynumber * 5 # Division print mynumber / 2 # Addition print mynumber + 20 # Subtraction print mynumber - 5 # You can get as complex as you want with these... print (mynumber*2+56)/100 # You can also create more than one variable num1 = 100 num2 = 5 print num1*num2 # You can idenifty what TYPE your variable is like this type(mynumber) # Are there other types? The answer - indeed! # Let's find out in the next module... --->
true
51a776bb343bb4b917107e5f6009760141ed134b
akjha013/Python-Rep
/test7.py
791
4.21875
4
#LOOP PRACTICE EXAMPLE PYTHON command = "" hasStarted = False hasStopped = True while True: command = input('>').lower() if command == 'start' and hasStarted is False: print('Car has started') hasStopped = False hasStarted = True elif command == 'start' and hasStarted is True: print('Car is already running') elif command == 'stop' and hasStopped is False: print('Car has stopped') hasStarted = False hasStopped = True elif command == 'stop' and hasStopped is True: print('Car is already idle') elif command == 'help': print(""" start for starting stop for stopping quit for exit """) elif command == 'quit': break; else: print('I do not understand the command')
true
3aa6555c1783ec5428bed334fdb94f429bc0b087
Girum-Haile/PythonStudy
/DecisionMaking.py
806
4.125
4
# if statement -It is used to decide whether a certain statement or block of statements will be executed or not. # simple if statement age = int(input("Enter your age: ")) # we use input() to get input from a user if age <= 30: print("accepted") # nested if statement name = input("enter name") sex = input("enter sex") if name == 'jack': if sex == 'male': print("your name is jack and your gender is male") else: print("your gender is not male") else: print("you are not jack") # if else statement if age <= 30: print("accepted") else: print("rejected") # elif statement num = int(input("enter number")) if num > 0: print("positive number") elif num < 0: print("negative number") elif num == 0: print("zero") else: print("invalid input")
true
a7d1334d4cdcb8b8273111a495eb2d3bf0badc9d
Girum-Haile/PythonStudy
/OOP-Class.py
1,290
4.28125
4
# class - creates user defined data structure. # class is like a blue print of an object # class creation class New: pass class Dogs: type = "Doberman" # class attributes atr = "mamal" def method(self): print("Dog breed:", self.type) print("Dog atr:", self.atr) Dog1 = Dogs() # object instantiation Dog1.method() # accessing class attributes class Person: def __init__(self, name, age): # '__init__'- Constructors are used to initialize the object’s state. self.name = name self.age = age def name_age(self): print(f'Hello {self.name} you are {self.age} years old'.format(self.name, self.age)) person1 = Person("girum", 12) person1.name_age() # instance variable- are for data each for unique instance. # class instances are for attributes and methods shared by all instance of the class class Family: family = 'alex' # class variable def __init__(self, name, age): self.name = name # instance variable self.age = age def setcolor(self, color): self.color = color def getcolor(self): return self.color namee = Family("alex",21) namee.setcolor("blue") print(namee.getcolor()) def main(): print('hello world') if __name__ == '__main__': main()
true
d8a274f82384cce62ec81666552b1c45484cf035
aduanfei123456/algorithm
/back_track/array_sum_combinations.py
827
4.25
4
""" WAP to take one element from each of the array add it to the target sum. Print all those three-element combinations. /* A = [1, 2, 3, 3] B = [2, 3, 3, 4] C = [1, 2, 2, 2] target = 7 */ Result: [[1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3], [2, 3, 2], [2, 3, 2], [3, 2, 2], [3, 2, 2]] """ def get_three(a,b,c,sum): result=[] for num in a: if num<sum: res=get_two(b,c,sum-num) for r in res: r.append(num) result.append(r) return result def get_two(b,c,sum): result=[] for num in b: if num<sum: for nc in c: if nc==sum-num: result.append([num,nc]) return result A = [1, 2, 3, 3] B = [2, 3, 3, 4] C = [1, 2, 2, 2] print(get_three(A,B,C,7))
true
8cab6c1c7f300b82ba739fc47993357228e2601b
yiyinghsieh/python-algorithms-data-structures
/cw_odd_or_even.py
1,081
4.46875
4
"""Codewars: Odd or Even? 7 kyu URL: https://www.codewars.com/kata/5949481f86420f59480000e7/train/python Task: Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching "odd" or "even". If the input array is empty consider it as: [0] (array with a zero). Example: odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even" Have fun! """ def odd_or_even(arr): arr_sum = 0 for d in arr: arr_sum += d if arr_sum % 2 == 0 or arr_sum == 0: return 'even' else: return 'odd' def odd_or_even(arr): arr_sum = sum(d for d in arr) if arr_sum % 2 == 0 or arr_sum == 0: return 'even' else: return 'odd' def odd_or_even(arr): return 'even' if sum(arr) % 2 == 0 else 'odd' def main(): assert odd_or_even([0]) == "even" assert odd_or_even([0, 1, 2]) == "odd" assert odd_or_even([0, 1, 3]) == "even" assert odd_or_even([1023, 1, 2]) == "even" if __name__ == '__main__': main()
true
fdeebbb4cdf146cb9f1456617c4ab9e0b240917d
raviss091/assignment
/CS102 Assignment Q-03.py
1,251
4.25
4
# CS102 Assignment-03, Python Program for Post order and Depth first level search. # 19BCS091, RAVI SHANKAR SHARMA class Node: def __init__(self,key): self.left = None self.right = None self.val = key def printInorder(root): if root: printInorder(root.left) print(root.val) printInorder(root.right) def printPostorder(root): if root: printPostorder(root.left) printPostorder(root.right) print(root.val) def printPreorder(root): if root: print(root.val) printPreorder(root.left) printPreorder(root.right) root=Node(1) root.left=Node(2) root.right=Node(3) root.left.left=Node(4) root.left.right=Node(5) root.right.left=Node(6) root.right.right=Node(7) print ("Preorder traversal of binary tree is") printPreorder(root) print ("\nInorder traversal of binary tree is") printInorder(root) print ("\nPostorder traversal of binary tree is") printPostorder(root) #OUTPUT: #Preorder traversal of binary tree is #1 #2 #4 #5 #3 #6 #7 # #Inorder traversal of binary tree is #4 #2 #5 #1 #6 #3 #7 # #Postorder traversal of binary tree is #4 #5 #2 #6 #7 #3 #1
true
ed8f1be00e133ac5283ff5c2db68d744937a5886
JHolderguru/OPP
/dog_class.py
2,203
4.40625
4
# Abstract and create the class dog # from animal import * # from cat_class import * class Dog(Animal): # this is a special method # it comes defined either was but we can re-write it # this methods stands for initialize class object AKA the constructor # in other languages # Allows us to set a attribute to Dog Objects # ...Like the poor thos doestn even have a name :( # we should give it name ...possibly MAx. def __init__(self, name='Mad Max', age=0): # setting attribute name to instances of Dog class self.name = name # encapsulate age and make it private self.__age_dog = age self.__human_age = 0 self.paws = 4 self.fur = 'Luxurious black and grey' # this is a method that can be used by a Dog instance def bark(self, person=''): return 'woof, woof!, I see you there' + person def eat(self, food): return 'NOM, nom, nom' + food.lower() def sleep(self): return 'zzzZZZzzzz zzzZZ' def potty(self): return 'UHHHH ! UUHH !! AHHH !!...o.o ' def getter_age(self): return self.__age_dog # This print should not be here def get_name(self): return self.__name def set_name(self, new_name): self.__name = new_name return True def __increase__and__humanyears_(self): self.__human_age += 1 self.__age_dog += 7 def dog_birthday_incrementer(self): # complex block # celebrate the dog's birthday print(f' happy birthday Dog! Good Boy {self.name}!') # update human year self.__human_age += 1 # update dog years self.__age_dog += 7 return f'dog years at{self.__age_dog} and human years{self.__human_age}' ringo = Dog(name='Ringo') print(ringo.name) # print ringo.name age not longer accessible because it's encapsulated print(ringo.getter_age()) ringo.dog_birthday_incrementer() print(ringo.getter_age()) ringo.dog_birthday_incrementer() print(ringo.getter_age()) # or in this file you define the class dog and add attributes and methods to th class. # That is it # print ('woof woof' ) << should not be here
true
c0d965379441722987627ba1e8eb0aa5930fd5e6
nvovk/python
/Recursion/D - Точная степень двойки/index.py
461
4.125
4
""" Дано натуральное число N. Выведите слово YES, если число N является точной степенью двойки, или слово NO в противном случае. Операцией возведения в степень пользоваться нельзя! """ def test(n): if n == 2: return 'Yes' elif n % 2 == 1: return 'No' else: test(n // 2) print(test(2))
false
6d97c798e03fddff1356794f5297341525c6bd3a
jtplace1/School_Projects
/Python/Mile-2-km/Mile-2-Km.py
1,248
4.3125
4
# Program Name: Test 2 p2.py # Course: IT1113/Section w01 # Student Name: Jabari Smith # Assignment Number: Test 2 Due Date: 10/25/20 def main(): #enter the choice for x in range(0,15): choice = int(input("1. Miles to Kilometers \n2. Kilometers to Miles \nEnter 1 or 2: ")) if choice == 1: # enter the distance in kilometers d_mile = float(input("\nEnter the distance: ")) mile_to_km = Miles_to_Kilometers(d_mile) #distance in miles. print("\nMiles %.3f mile" % (d_mile)) #converted distance in kilometers print("Kilometers %.3f km" % (mile_to_km)) elif choice == 2: d_km = float(input("\nEnter the distance: ")) km_miles = Kilometers_to_Miles(d_km) #distance in km. print("\nKilometers %.3f km" % (d_km)) #converetd distance in kilometers. print("Miles %.3f mile" % (km_miles)) #choice is not valid else: print("Invalid choice.") # miles 2 kilometers. def Miles_to_Kilometers(Distance): return Distance / 0.6214 # kilometers 2 miles. def Kilometers_to_Miles(Distance): return Distance * 0.6214 main()
false
eda80049c2742dd09afdfc8c103418a3ce33f200
Chruffman/Personal-Projects
/binary_search.py
1,398
4.28125
4
# Recursive function that uses the binary search algorithm to find a given value in a list in O(logn) time # Does not require a sorted list, sorting is performed within def binary_search(arr, val): # if the list is empty or there is only one element and it is not the value we are looking for if len(arr) == 0 or (len(arr) == 1 and arr[0] != val): return False # sort the list # since illustrating binary search is the focus, and the input sizes for testing will not be large, # the sorting is done using Bubble Sort n = len(arr) #nested for loops lead to O(n^2) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: #swap if true arr[j], arr[j+1] = arr[j+1], arr[j] sorted_list = arr # find the value at the midpoint of the list mid = sorted_list[len(sorted_list) // 2] if val == mid: return True # recursively call the function using second half of the array if val > mid: return binary_search(sorted_list[len(sorted_list) // 2 + 1:], val) # recursively call the function using first half of the array if val < mid: return binary_search(sorted_list[:len(sorted_list) // 2], val) print (binary_search([5,1,7,9,2,3,10,1], 1)) print (binary_search([5,1,7,9,2,3,10,1], 5)) print (binary_search([5,1,7,9,2,3,10,1], 3)) print (binary_search([5,1,7,9,2,3,10,1], 40)) # should return True True True False
true
e4ced192f6fab6fddf6101649759fee018ae522a
saadmgit/python-practice-tasks
/task8.py
958
4.4375
4
# TASK 8: Take integers input from user as a comma separated make_list = [] odd_list = [] input_nums = str(input("Enter numbers in comma ',' separated : ")) # Taking input as a comma separated input_list = input_nums.split(",") # Making string a list for i in input_list: # Making list integer based (it was considered as string when input because comma separated) make_list.append(int(i)) print("User input LIST : ", make_list) # final list on which operation is to be done for num in make_list: # main loop for finding odd nums in list if num % 2 != 0: odd_list.append(num) # making another list of all the odd nums instead of just displaying them print("ODD numbers LIST : ", odd_list) # List conatining odd numbers
true
5b3821a5bd436027a0672d2755fdcffdbd8257d7
AthulKrishna14310/Learn_Python
/dictionary.py
1,049
4.3125
4
#Initialise _dictionary={ "Name":"Game of Thrones", "Actor":"Peter Dinglage", "Actress":"Emilia Clarke", "Director":"George Lucas", "Year":2011, "Episodes":73, "Season":8, } #Print Element print(_dictionary["Season"]) _year=_dictionary["Year"] print(_year) #Changing value _dictionary["Year"]=2021 print(_dictionary) #Printing keys print("\n\nPrinting Keys") for key in _dictionary: print(key) #Printing Values print("\n\nPrinting Values") for value in _dictionary.values(): print(value) #Printing items for item in _dictionary.items(): print(item) #Printing two variables for key,value in _dictionary.items(): print(str(key)+str(value)) #Adding element _dictionary["Villian"]="Leena Hedy" print(_dictionary) #removing element _dictionary.pop("Villian") print(_dictionary) #clear new=_dictionary print(new) new.clear() print(new) #Nested Dictionary _nestedDictionary={ "food1":{ "eat":"Rice", "drink":"Milk" }, "food2":{ "eat":"biriyani", "drink":"cola" } } print(_nestedDictionary["food2"])
true
012d5ac14fd9bf17f1c7ef924a24a4d83cf6e278
jaimecabrera911/PythonBasico
/02 Operadores y expresiones/Ejercicio1.py
558
4.15625
4
# Ejercicio 1 # # Realiza un programa que lea 2 números por teclado y determine los siguientes aspectos (es suficiene con mostrar True o False): # # # # Si los dos números son iguales # # Si los dos números son diferentes # # Si el primero es mayor que el segundo # # Si el segundo es mayor o igual que el primero a = input("Ingresa un numero") b = input("Ingresa otro numero") print("Son Iguales?", a == b) print("Son diferentes?", a != b) print("El primer numero es mayor al segundo?", a > b) print("El segundo numero es mayor al primero?", b > a)
false
c5b812e1751f4dfdc560e58bfb4aa24a73bb92e3
prasen7/python-examples
/time_sleep.py
393
4.1875
4
import time # Write a for loop that counts to five. for i in range(1,6): print(i,"Mississippi") # Body of the loop - print the loop iteration number and the word "Mississippi". time.sleep(1) # suspend the execution of each next print() function inside the for loop for 1 second # Write a print function with the final message. print("Ready or not, here I come!")
true
3344d7f063149be56690a4065d2f5e69b2d4b379
prasen7/python-examples
/pyhton_read.py
1,840
4.3125
4
# python reading materials #1. decorator: # a decorator is a design pattern in python that allows a user to add new # functionality to an existing object without modifying its structure. from time import time def timer(func): def f(*args, **kwargs): before=time() rv=func(*args, **kwargs) after=time() print(f'elapsed time: {afetr-before}') return rv return f @timer def add(x,y,z): return x+y+Z print(add(5,5,5)) # 2. Generator: # a generator is a special type of function which does not return a single value. # instead, it returns an iterator object with a sequence of values. from time import sleep def compute(): for i in range(10): sleep(.5) yield i for val in compute(): print val #------------------------------------------------------------ # 3.setattr and getattr:- # setattr function sets the value of specified attribute of the specified object. # getattr method returns the value of the named attribute of an object. class Person: pass person=Person() person_info={"first": "Danny", "Last": "Steenman"} for key, value in person_info.items(): setattr(person, key, value) for key in person_info: print(getattr(person, key)) # 4. Enumerate :----------------------------------------------------------- # enumerate adds a counter to an iterable and returns it in a form of enumerate object. my_list=["apple", "banana", "grapes", "pear"] for counter, value in enumerate(my_list): print(counter, value) # output: # 0 apple # 1 banana # 2 grapes # 3 pear #---------------------------- # 5. ternary operator # ternary operator quickly tests a condition instead of a multiline if statement condition=True x=1 if condition else 0 print(x) #-------------------------------
true
c809a4e3c916ac15635078c03d4cd71f13e0e7ea
prasen7/python-examples
/listslice.py
1,007
4.375
4
# Lists (and many other complex Python entities) are stored in different ways than ordinary (scalar) variables. # 1. the name of an ordinary variable is the name of its content. # 2. the name of a list is the name of a memory location where the list is stored. # The assignment: list2 = list1 copies the name of the array, not its contents. # In effect, the two names (list1 and list2) identify the same location in the computer memory. # Modifying one of them affects the other, and vice versa. list1 = [1] list2 = list1 list1[0] = 2 print(list2) # A slice is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list. # Copying the whole list list1 = [1] list2 = list1[:] list1[0] = 2 print(list2) # Copying part of the list myList = [10, 8, 6, 4, 2] newList = myList[1:3] print(newList) # deleting the l3 variable does not delete the list saved in memory. l1 = ["A", "B", "C"] l2 = l1 l3 = l2 del l1[0] del l2 print(l3)
true
99c8dff869acb2bf89280f747bb371a3d5824e81
Johanna-Mehlape/TDD-Factorial
/TDD Factorial/factorial.py
705
4.375
4
#factorial.py """python code to find a Factorial of a number""" def factorial(n): """factorial function""" try: #to try the input and see if it is an integer n = int(n) #if it is an integer, it will print out its factorial except:#if it is not an integer, except will return an message print("Only integers have factorials") return "Only integers have factorials" if n < 0: print("False") return False elif n == 0: return 1 elif n == 1: return 1 else: return n * factorial(n-1) if __name__ == '__main__': n = input("Please enter an integer > = 0 to find its Factorial : ") factorial(n)
true
c0bb38dc8e38eac9c7f1d1bad6a3ba60f217fbbd
steve1998/scripts
/palindromechecker.py
1,010
4.1875
4
# checks if a word is a palindrome # palindrome function def palindrome(str): reversedWord = str[::-1] # comparison of each word if str.lower() != reversedWord.lower(): return False return True def main(): filename = input("Enter list of words to check for palindrome: ") counter = 0 # final value goes here # reads each line in the list of files with open(filename) as f: content = f.readlines() # removes whitespace content = [x.strip() for x in content] # iterates over every word in the txt file for word in content: num = palindrome(word) if num == True: counter += 1 print("There are", counter, "palindromes in this list of words") # old version # str = input("Enter the word to check: ") # pal = palindrome(str) #if pal == True: #print("Word is a palindrome") #else: #print("Word is not a palindrome") if __name__ == "__main__": main()
true