blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0552222b7656a21b392d008968bffefd86505f6e
ramaisgod/My-Python-Practice
/prog30_Map_Filter_Reduce.py
2,226
4.65625
5
#---- Map Function -------------------------------------------------------- print("#---- Map Function --------------------------------------------------------") # It apply any function to all list items. map is a kind of object # ------- Example -1 ------------------------------ print(" ------- Example -1 ------------------------------") # convert all list items into integer format #-- Normal method --- num = ["23", "32", "44", "64", "5"] # list item is in string format print(num) for i in range(len(num)): num[i] = int(num[i]) print(num) print(num[2]+1) # add 1 in third element of list #-- using Map function. --- num = list(map(int, num)) print(num) # ------- Example -2 ------------------------------ print("------- Example -2 ------------------------------") # convert all list items into square using map function # --- Method -1 ------- num = [4, 5, 9, 25, 12, 3] num = list(map(lambda x: x*x, num)) print(num) # --- Method -2 ------- num = [4, 5, 9, 25, 12, 3] def sq(x): return x*x num = list(map(sq, num)) print(num) # ------- Example -3 ------------------------------ print("------- Example -3 ------------------------------") def squ(x): return x*x def cube(x): return x*x*x myfunc = [squ, cube] num = [4, 5, 9, 25, 12, 3] for item in num: val = list(map(lambda x: x(item), myfunc)) print(val) #---- Filter Function -------------------------------------------------------- print("#---- Filter Function --------------------------------------------------------") # It creates a list where given criteria/function returns true list_1 = [1,2,3,4,5,6,7,8,9] def is_greater_5(num): return num>5 greater_than_5 = list(filter(is_greater_5, list_1)) print(greater_than_5) #---- Reduce Function -------------------------------------------------------- print("#---- Reduce Function --------------------------------------------------------") # It is a part of functools. It is used to apply any function to each element of given list in sequence. from functools import reduce list_2 = [1, 2, 3, 4, 5] list_3_sum = reduce(lambda x,y: x+y, list_2) print("Sum of list_2 is : ", list_3_sum)
true
3463f196d8c50ea685fc8f9814dda8b45168e45b
ramaisgod/My-Python-Practice
/prog26_decorators.py
996
4.34375
4
''' ------- Example -1 ----------------- ''' # def myfunc1(): # print("Hello, I am Ram") # myfunc2 = myfunc1 # del myfunc1 # myfunc2() ''' ------- Example -2 ----------------- You can return a Function using a function. Function can return function. ''' # def myfunction_1(num): # if num == 0: # return print # if num == 1: # return sum # a = myfunction_1(0) # print(a) # a = myfunction_1(1) # print(a) ''' ------- Example -3 ----------------- Pass function as an argument of a function ''' # def myfunction_2(myfunction_1): # myfunction_1("Hello Python Decorators") # myfunction_2(print) ''' ------- Example -4 ----------------- Decorator ''' def dec1(func1): def nowexec(): print("Execute Now") func1() print("Executed") return nowexec @dec1 def Ram_function(): print("Ram is a good boy") #Ram_function = dec1(Ram_function) Ram_function()
false
a234f006b908a1be198c9015e9da9863c6e56728
ramaisgod/My-Python-Practice
/Q3_factorial.py
472
4.4375
4
''' The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers, and the factorial of zero is one, 0! = 1 ''' num = 6 if num < 0: print("Invalid Number !!!") elif num == 0: print("Factorial of 0 = 1") factorial = 1 for i in range(1, num+1): factorial = factorial * i print("Factorial of {} = {}".format(num, factorial))
true
cb8bcad011263cf963c56de2dc5e09879f382f60
tsghosh/euler-solutions
/python/p004.py
1,555
4.15625
4
# Solution to Project Euler problem 4 # Largest palindrome product # A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 \xc3 99. # Find the largest palindrome made from the product of two 3-digit numbers. #assume AZZA is the number we are searching then AZZA = YY x XX #lets create a program to find the largest palindrom from the product of two 2-digit numbers as explained in problem #largest 2 digit number = 99 and smallest is 10, so we loop through each and check plaindrom def find_largest_plaindrom_from_product_2_digit(): max_pal=0 for x in range(10,100): for y in range(10,100): prod = str(x*y) rev_str = str(x*y)[::-1] if prod == rev_str: if x*y > max_pal: max_pal = x*y print max_pal, 'is a largest palindrome which is product of two 2-digit numbers' # similarly largest 3 digit number = 999 and smallest is 100, so we loop through each and check plaindrom def find_largest_plaindrom_from_product_3_digit(): max_pal=0 for x in range(100,1000): for y in range(100,1000): prod = str(x*y) rev_str = str(x*y)[::-1] if prod == rev_str: if x*y > max_pal: max_pal = x*y print max_pal, 'is a largest palindrome which is product of two 3-digit numbers' if __name__ == "__main__": #find_largest_plaindrom_from_product_2_digit() find_largest_plaindrom_from_product_3_digit()
true
596d1e0574d00467016db85fd2c0194cb0a5800a
ChrEphosD/epitech-test
/star.py
1,639
4.3125
4
def star(): u = float(input("Entrez un chiffre entier svp : ")) while u.is_integer() != True: u = float(input("Entrez un chiffre entier svp : ")) #the number has to be integer top = int(3*u)#variable that calculate the first * position if u == 0: pass elif u ==1: print(""" * *** *** * * *** *** * """) #if 0 end without error, if 1 print the star bellow, else start program else: print((top-1)*" "+"*") #print the top * u2 = u while u2 > 1: space_before = int(top + u2 - u - 2) space_after = int((-u2 + u)* 2 + 1) print(" "*space_before+"*"+" "*space_after+"*") u2 = u2-1 #print the top part of the star u_between = int(2*u-3) print("*"*int(2*u+1)+" "*u_between+"*"*int(2*u+1)) #print the long line of * u3 = u while u3 > 0: space2_before = int(1+u-u3) space2_after = int(2*(2*u+1)+u_between-4-2*(u-u3)) u3 = u3-1 print(" "*space2_before+"*"+" "*space2_after+"*") #print second part of the star while u3 < u-1: space2_before = space2_before - 1 space2_after = space2_after + 2 u3 = u3+1 print(" "*space2_before+"*"+" "*space2_after+"*") #print 3rd part which is 2nd in reverse print("*"*int(2*u+1)+" "*u_between+"*"*int(2*u+1)) #print the second long line of * u4 = u while u4 > 1: print(" "*space_before+"*"+" "*space_after+"*") space_before = space_before + 1 space_after = space_after - 2 u4 = u4-1 #print the bottom part of the star, which is top part in reverse print((top-1)*" "+"*") #print the last * at the very bottom
false
8bd0aead820505fb323259095300af105ba42876
surazova/harvardsCS50
/pset6/mario.py
502
4.125
4
# Python version of mario.c # To run: python3 mario.py from cs50 import get_int # User determines height while True: height = get_int("What is the height of the pyramid? ") # Height must be no greater than 23 if height >= 0 and height < 24: break # Print a pyramid of # if i(integer) is between 1 and 23 for i in range(height): # Aligns the pyramid to the right print(" " * (height - i - 1), end="") # Top stack is always ## print("#" * (i + 2))
true
6e3f712dbc94a00f4fc963e945f9f1ac51a9797b
nathandalal/statistics-csnyc
/api/py_code/src/merge_sort.py
365
4.125
4
def merge_sort(arr): '''Sorts parts and combines sorted halves.''' # one element by itself is sorted if len(arr) == 1: return arr # sort two halves using recursion mid = len(arr) / 2 first_half = merge_sort(arr[:mid]) second_half = merge_sort(arr[mid:]) # combine two sorted lists into one sorted list return merge(first_half, second_half)
true
07b21cdfe165e8984ca27cdaf3cdac5c939cbbf9
brickatyourfeet/python-refresher
/lists_tuples_sets.py
1,374
4.125
4
my_var = 'hello' #below is a list grades = [77, 80, 90, 95, 100] #below is a tuple - tuples are immutable tuple_grades = (77, 80, 90, 95, 100) #lists are like arrays, can be added to - for example grades.append(108) #tuples are immutable - no adding or subtracting from them tuple_single = 15, #single item tuples have to have comma after set_grades = {77, 80, 100, 90, 100} #sets are unique and unordered - the non-unique values are auto removed print(sum(grades) / len(grades)) #operations for lists tuples and sets grades.append(50) #50 is added to the end tuple_grades = tuple_grades + (100,) # must have comma, this will add 100 and it is ordered so its at the end print(tuple_grades) print(grades[0]) #accessing elements is just like javascript grades[0] = 60 #changes the first item to 60 #tuple_grades[0] = 60 -this is an error, tuples immutable #set_grades[0] = 60 -would also error because its unordered set_grades.add(60) #this will 'add' 60 but its not unique so, peace out ## set operations set_one = {1, 2, 3, 4, 5} set_two = {1, 3, 5, 7, 9, 11} print(set_one.intersection(set_two)) # outputs a set that has all matching numbers [1, 3, 5] print(set_one.union(set_two)) #prints both in one set but all unique values [1, 2, 3, 4, 5, 7, 9, 11] #no duplicate in sets! print({1,2,3,4}.difference({1,2})) #prints the items that do NOT match
true
1a1268605127f64c02fa2ad0235f46e8b2b217a7
PeterXUYAOHAI/basic_algo
/python/heap_sort.py
991
4.25
4
# heap sort use in-place sort, the heap tree is represent by the list #better check https://www.geeksforgeeks.org/heap-sort/ if forget def swap(sqc, i,j): sqc[i],sqc[j] = sqc[j], sqc[i] #built a max-heap def heapify(sqc, end, i): left = 2*i+1 right = 2*(i+1) #locate left and right child in the list largest = i if left<end and sqc[left] > sqc[largest]: largest = left if right<end and sqc[right] > sqc[largest]: largest = right if largest != i: swap(sqc, largest, i) heapify(sqc, end, largest) def heap_sort(sqc): end = len(sqc) start = end/2-1 # start from the last non-leaf node for i in range(start, -1, -1): heapify(sqc, end, i) # take max from max-heap and put it in the end of list for i in range(end-1, 0, -1): swap(sqc, i, 0) #after take max, nead to re heapify heapify(sqc, i, 0) return sqc list = [45,2,56,34,7,32,6,3,23,76] print heap_sort(list)
true
c022ebfdab67769d7409f088e3f2fde745db1c67
huseyinyilmaz/pyds
/node.py
1,271
4.1875
4
""" Node manipulation functions. """ def left(node): """ get left branch of given node """ return node[0] def set_left(node, left_node): """ set left branch of given node """ return (left_node, node[1], node[2], (1 + count(left_node) + count(node[2]))) def right(node): """ get right branch of given node """ return node[2] def set_right(node, right_node): """ set right branch of given node """ return (node[0], node[1], right_node, (1 + count(node[0]) + count(right_node))) def value(node): """ get value of given node """ return node[1] def set_value(node, value): """ set vlaue of given node """ return(node[0], value, node[2], node[3]) def count(node): """ return length of current heap """ if not node: result = 0 else: result = node[3] return result def is_leaf(node): """ check if current node is a leaf """ # return not left(node) and not right(node) return count(node) == 1 def make_node(left, value, right): """ Creates a new node """ return (left, value, right, (1 + count(left) + count(right)))
true
7f28e3deae36c02e3cf7adffdb6f4d5e74fc5e61
catrielzz/python_practices
/techwithtim/functions/functions.py
2,163
4.34375
4
# La idea básica es que una función es un bloque de código que hace algo. Normalmente usamos funciones cuando repetimos # la misma tarea o una similar. A continuación se muestra uno de los ejemplos más básicos de una función: def addTwo(x): return x + 2 print(addTwo(3)) # esto imprimirá 5 # Antes de que podamos profundizar en las funciones, hay algunas definiciones que debemos entender: # - Parámetros: son la entrada para la función, aparecen entre paréntesis de la definición de la función. # En el ejemplo anterior, nuestro único parámetro es x (puede tener tantos parámetros como desee). # - Argumentos: son lo que nosotros (el programador) pasamos a la función como entrada. # Aparecen en la llamada a la función. En el ejemplo anterior, el único argumento es 3. # Esta función verifica si cada elemento en una lista es cero. # Nos devuelve un valor Verdadero o Falso dependiendo de la lista dada. def isZeros(li): for element in li: if element != 0: return False return True print(isZeros([0, 0, 0, 1])) # Esto imprimirá falso # Esta función verifica si cada elemento en una lista es cero. # It displays to the screen True or False. # NO devuelve un valor. def isZeros(li): check = True for element in li: if element != 0: check = False break if check: print("True") else: print("False") isZeros([0, 0, 0, 0]) # Llamar a esto dará como resultado que True se imprima en la pantalla # Nota: Las funciones están destinadas a ser reutilizadas y, por lo tanto, se pueden usar tantas veces como desee. # Si alguna vez se encuentra repitiendo código, piense en ponerlo en una función y # llamar a esa función en lugar del código repetido. # Problema: queremos hacer un conjunto de preguntas 5 veces: name, age and country def askQuestions(): name = input('Ingrese su Nombre: ') age = input('Ingrese su edad: ') country = input('Ingrese su pais de residencia: ') print('Tu nombre es', name, 'tienes', age, 'vives en', country) for i in range(5): askQuestions()
false
901f518f4dd1e938871a7bc1766c903b608730ac
catrielzz/python_practices
/techwithtim/OOP/indroduction_to_objects.py
1,160
4.25
4
# Instancia: Cada vez que creamos un nuevo objeto, se dice que estamos creando una instancia de una clase. # Por ejemplo, escribir el comando x = 1 se traduce en: crear una nueva instancia de la clase int con el valor 1 # y el nombre x. # Método: puede pensar en un método como una función específica de ciertos objetos y clases. # Los métodos se crean dentro de una clase y solo son visibles para las instancias de esa clase. # Un ejemplo de un método es .strip (). Solo se puede usar en objetos de clase str ya que es específico de la clase str. # Todos los métodos deben invocarse en una instancia de una clase. # No podemos simplemente escribir strip () ya que necesitamos incluir una instancia seguida de un punto antes. x = 5 y = "string" y.strip() print(type(x)) # x es una instancia de la clase int <class 'int'> print(type(y)) # y es una instancia de la clase str <class 'str'> # Atributos: Un atributo es cualquier cosa que sea específica de un determinado objeto. # Por ejemplo, el objeto tiene un color de atributo. Podemos cambiar ese color y modificarlo y si creamos un nuevo # objeto tortuga puede tener un color diferente.
false
06263ca566019527a23658a0fceb4b231e67fafd
YashMistry1406/data-structures-and-algo
/implementation _pyhton/tree/tree_using_queue.py
2,987
4.46875
4
# creation of a linked list tyoe of connection beteween the # nodes where in each node is divided in 3 parts # left->pointing to the left node and left part of the tree or the samller value # center-> It has the data # right ->pointing to the left node and left part of the tree or the samller value class Node: def __init__(self,data): self.data=data self.right=None self.left=None #creating a node and inserting the value for #newly created node #greater value is pushed at right #while the smaller value than the previous node ios pushed at left side #it is recursive function and goes until the root parameter becomes zero #after that it creates a new node #which then followed by the link formation #and at the end of the recursive #function the last leaf is connected to the main root of the tree def Insert(root,data): if(root==None): root=Node(data) elif(root.data<=data): root.left=Insert(root.left,data) elif(root.data>data): root.right=Insert(root.right,data) return root #finding the minimum in the tree def findMin(root): if(root ==None): print("not found") return -1 temp=root.data left_min=findMin(root.left) right_min=findMin(root.right) if left_min<temp: temp=left_min else: temp=right_min return temp #insert maxfor finding a max form the tree #def findMin(root): # if(root ==None): # print("not found") # return -1 # temp=root.data # left_min=findMin(root.left) # right_min=findMin(root.right) # if left_min<temp: # temp=left_min # else: # temp=right_min # return temp #Height of node – The height of a node is the number of edges on the longest downward path #between that node and a leaf. #depth =height-1 # def FindHeight(root): if(root ==None): return -1 return max(FindHeight(root.right),FindHeight(root.left))+1 def level_order(root): if(root == None): return; queue=[] queue.append(root) while(len(queue)>0): print(queue[0].data) node=queue.pop() if node.right is not None: queue.append(node.right) if node.left is not None: queue.append(node.left) def preorder(root): if root==None: return print(root.data) preorder(root.left) preorder(root.right) def postorder(root): if root==None: return postorder(root.left) postorder(root.right) print(root.data) def inorder(root): if root==None: return inorder(root.left) print(root.data) inorder(root.right) if __name__=='__main__': tree=Node(1) tree=Insert(tree,2) tree=Insert(tree,3) #tree=BinaryTree(1) #tree.root.left = Node(2) #tree.root.right = Node(3) #tree.root.left.left = Node(4) #tree.root.left.right = Node(5) #tree.root.right.left = Node(6) #tree.root.right.right = Node(7)
true
e93226b15e60cbe1c50360d973d878f9819c293f
FlyMeToTheMars/PythonHelloWorld
/hugh_02_oop/fh_06_extends.py
2,022
4.125
4
class Animal: def eat(self): print("吃") def drink(self): print("喝") def run(self): print("跑") def sleep(self): print("睡") wangcai = Animal() wangcai.eat() wangcai.drink() wangcai.run() wangcai.sleep() # 子类拥有父类的所有方法 class Dog(Animal): def bark(self): print("汪汪叫") wangwang = Dog() wangwang.eat() wangwang.drink() wangwang.run() wangwang.sleep() wangwang.bark() class XiaoTianQuan(Dog): def fly(self): print("我会飞") def bark(self): print("我是啸天犬") super().bark() # Python2.0 如果要实现上面的功能,有点复杂 代码如下 """ Dog.bark(self) """ print("aafsdwaerwgybds") # 有没有括号 对Python来说 说法很大 xtq = XiaoTianQuan() xtq.bark() class A: # 属性在init方法中定义 def __init__(self): self.num1 = 100 self.__num2 = 200 def __test(self): print("私有方法 %d %d" % (self.num1, self.__num2)) class B(A): def demo(self): # 在子类的对象方法中不能访问父类的私有属性和方法 # 但是可以通过调用父类的共有方法间接调用父类的公有属性和方法 print("访问父类的私有属性 %d" % self.__num2) b = B() print(b) """ 在外界不能直接访问对象的私有属性,调用方法 print(b.__num2) b.__test() """ print(b.num1) class C: def test(self): print("test 方法") class D: def demo(self): print("demo 方法") # 多继承 class E(C, D): pass # 创建子类对象 e = E() e.test() e.demo() # 应该避免两个父类汇总存在同名的属性和方法 """ python中多继承两个父类出现相同的方法 属性名的时候 使用MRO选择执行顺序的 """ print(E.__mro__) """ 新式类 以Object为基类的对象 旧式类 不以Object为基类的对象 两者在多继承时 会影响到方法的搜索顺序 """
false
c33ded44246d8d1faae72f4b674a841c88b4ffe8
FlyMeToTheMars/PythonHelloWorld
/hugh_02_oop/fh_07_polymorphism.py
900
4.25
4
# 多态 """ 不同的子类对象调用相同的父类方法,产生不同的执行结果 多态可以增加代码的灵活度 以继承和重写父类方法为前提 是调用方法的技巧,不回影响到类的内部设计 """ class Dog(object): def __init__(self, name): self.name = name def game(self): print("%s 蹦蹦跳跳的玩耍。。。" % self.name) class XiaoTianQuan(Dog): def game(self): print("%s 飞到天上去玩耍。。。" % self.name) class Person(object): def __init__(self, name): self.name = name def game_with_dog(self, dog): print("%s 和 %s 快乐的玩耍" % (self.name, dog.name)) dog.game() wangcai = Dog("旺财") xiaoming = Person("小明") xiaoming.game_with_dog(wangcai) wangcai_1 = XiaoTianQuan("wangcai") xiaoming_1 = Person("xiaoming") xiaoming_1.game_with_dog(wangcai_1)
false
8ea24665252e3818a22a694050284d498f7a8a41
FlyMeToTheMars/PythonHelloWorld
/hugh_01_base/fh_11_container.py
1,247
4.21875
4
import keyword """ 列表(别的编程语言 一般叫数组) """ name_list = ["zs", "ls", "ww"] print(name_list[2]) # 修改 name_list[2] = "aa" print(name_list[2]) print(name_list.index("aa")) # 增加 name_list.append("王小二") name_list.insert(1, "nice") temp_list = ["孙悟空", "猪八戒"] # 可以把其他列表中的完整内容追加到当前列表末尾 name_list.extend(temp_list) print(name_list) # 删除 # remove name_list.remove("ls") print(name_list) # 默认删除最后一个数据 name_list.pop() print(name_list) # 指定索引可以删除 name_list.pop(3) print(name_list) # len 长度 list_len = len(name_list) print(list_len) # count 方法可以统计列表中某一个数据出现的次数 count = name_list.count("zs") print("张三出现了 %d 次" % count) # 排序 # 升序 name_list.sort() print("排序") print(name_list) # 降序 name_list.sort(reverse=True) print(name_list) # 逆序(反转) 把列表中的顺序完全翻转 name_list.reverse() print(name_list) # clear 清空列表 name_list.clear() print(name_list) # del 关键字 本质上是用来讲一个变量从内存中删除,后续就不能再使用了 # 日常开发中使用得不多 name = "小明" del name print(name)
false
8e16d70625f2f2ca152440e1edf5c88c62b1bb28
idzhalalov/plural_for_num
/plural_for_num.py
1,160
4.78125
5
def plural_for_num(num, word_forms): """ Function returns a correct plural form of a word for a num. Based on https://habr.com/post/105428/. Tested only with russian language. Args: num (int): A number that precedes a word word_forms (list): A list that contains 3 plural forms of a word Returns: string: a correct form on a word for the num Example: records_count = 21 record_forms = ['сообщение', 'сообщения', 'сообщений'] new_forms = ['новое', 'новых', 'новых'] print('У вас {} {} {}'.format( records_count, plural_for_num(records_count, new_forms), plural_for_num(records_count, record_forms)) ) """ num = num % 100 if 11 <= num <= 19: result = word_forms[2] else: num = num % 10 endings = { 1: word_forms[0], 2: word_forms[1], 3: word_forms[1], 4: word_forms[1], } result = endings.get(num) if result is None: result = word_forms[2] return result
true
5f9781912372376a6ec50241befe938c57194c5d
vasu-kukkapalli/python_git
/Udemy/DataStructure/set_3.py
468
4.125
4
from os import remove set1 = {'a', 'b', 'c'} set2 = {'c', 'd', 'e'} ## YOUR CODE STARTS HERE #set3 contains all unique elements present in set1 and set2 set3=set1.union(set2) print(set3) #set4 contains the elements that exist in both set1 and set2 set4= set1.intersection(set2) print(set4) #set5 contains the elements that exist only in set1, but not in set2 set5= set1.difference(set2) print(set5) #remove the element 'c' from set1 set1.remove('c') print(set1)
true
492a836d65ed347d3f117f6d4b0fbe8242a22898
dannteMich/python_course
/lesson_02/01_loops/patbas_guess_number.py
426
4.21875
4
chosen_number_as_string = input("Please select a number for the Player to guess: ") chosen_number = int(chosen_number_as_string) guess = int(input("Player, what is your guess? ")) while guess != chosen_number: if guess < chosen_number: print("Your guess is too low") else: print("Your guess is too high") guess = int(input("Player, what is your guess? ")) print("Correct. It was", chosen_number)
true
26c0a540ab36a04236f924fb828019acc24c79ec
Saatvik17/pythonws
/strings/practice/001date/classes/main.py
744
4.1875
4
class human: def __init__(self , name): self.name = name print("let's see what happens") def hello(self): print(self.name) class Person(human): def __init__(self , name , key): super().__init__(name) #you can comment this out and not call the class human print("does this run") #just declare self.name and human does not run self.key = key def vital_info(self): print("in second func") print(self.key) person = Person("Doom" , "Betrayal") Human = human("moneypenny") person.hello() person.vital_info() Human.hello() print(f"is Person subclass of human ? Answer is :\n{issubclass(Person,human)}")
false
5ef4ae7d2922a754fff1d99a543446476ec246a0
deepakdp1989/Python
/shell_sort.py
1,760
4.1875
4
""" ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. """ def sort(elements_list): """ Python program for implementation of Shell Sort """ # Start with a big gap, then reduce the gap size = len(elements_list) gap = int(size / 2) # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped # order keep adding one more element until the entire array # is gap sorted while gap > 0: for i in range(gap, size): # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = elements_list[i] # shift earlier gap-sorted elements up until the correct # location for a[i] is found j = i while j >= gap and elements_list[j - gap] > temp: elements_list[j] = elements_list[j - gap] j -= gap # put temp (the original a[i]) in its correct location elements_list[j] = temp gap = int(gap / 2) return elements_list def main(): """ Main. Running the code """ list_of_elems = [3, 178, 4, 101, 40, 44, 205, 89, 10, 112, 2, 45] print(sort(list_of_elems)) # will print [2, 3, 4, 10, 40, 44, 45, 89, 101, 112, 178, 205] if __name__ == "__main__": main()
true
28dfb94dd54c23c3a1e3c0b5e9708d62fc9a7bbc
deepakdp1989/Python
/radix_sort.py
2,008
4.65625
5
""" The idea of Radix Sort is to do digit by digit sort starting from least significant digit to most significant digit. Radix sort uses counting sort as a subroutine to sort. """ def count_sort(elements_list, exponent): """ A function to do counting sort of arr[] according to the digit represented by exponent. """ size = len(elements_list) # The output array elements that will have sorted arr output = [0] * (size) # initialize count array as 0 count = [0] * (10) # Store count of occurrences in count[] for pos in range(0, size): index = (int(elements_list[pos] / exponent)) count[(index) % 10] += 1 # Change count[i] so that count[i] now contains actual # position of this digit in output array for pos in range(1, 10): count[pos] += count[pos - 1] # Build the output array pos = size - 1 while pos >= 0: index = int((elements_list[pos] / exponent)) output[count[(index) % 10] - 1] = elements_list[pos] count[(index) % 10] -= 1 pos -= 1 # Copying the output array to elements_list[], # so that elements_list now contains sorted numbers pos = 0 for pos in range(0, len(elements_list)): elements_list[pos] = output[pos] def sort(elements_list): """ Method to do Radix Sort """ # Find the maximum number to know number of digits max_value = max(elements_list) # Do counting sort for every digit. Note that instead # of passing digit number, exp is passed. exp is 10^i # where i is current digit number exponent = 1 while max_value / exponent > 0: count_sort(elements_list, exponent) exponent *= 10 return elements_list def main(): """ Main. Running the code """ list_of_elems = [3, 178, 4, 101, 40, 44, 205, 89, 10, 112, 2, 45] print(sort(list_of_elems)) # will print [2, 3, 4, 10, 40, 44, 45, 89, 101, 112, 178, 205] if __name__ == "__main__": main()
true
0be2abc47bc8e17236a7b32e5c39d73fdf2a252a
reemanaqvi/HW04
/HW04_ex07_04.py
1,099
4.6875
5
#!/usr/bin/env python # HW04_ex07_04 # The built-in function eval takes a string and evaluates it using the Python # interpreter. # For example: # >>> eval('1 + 2 * 3') # 7 # >>> import math # >>> eval('math.sqrt(5)') # 2.2360679774997898 # >>> eval('type(math.pi)') # <type 'float'> # Write a function called eval_loop that iteratively prompts the user, takes the # resulting input and evaluates it using eval, and prints the result. # It should continue until the user enters 'done', and then return the value of # the last expression it evaluated. ################################################################################ # Imports import math # Body def eval_loop(): while True: ui = raw_input ("Enter command or 'done' to quit: ") # User input prompt if ui == 'done': # Breaks if user enters 'done' return ui else: print eval(ui) # Evaluates the code entered by user ################################################################################ def main(): eval_loop() if __name__ == '__main__': main()
true
5ce4039ffcd9745a8e226b6e79ebab9489b9b51f
sunsongpy/python_standard_library_study
/string模块.py
1,073
4.21875
4
""" python的string模块提供了常见的字符常量、字符串模板类和格式化类 """ import string import json import random # 1.常见的常量,如果要生成定长的字母和数字组合的字符串,就不需要自己定义常量了 print('八进制字符(0-7): ', string.octdigits) print('十进制字符(0-9): ', string.digits) print('十六进制字符(0-9a-fA-F) ', string.hexdigits) print('a-z: ', string.ascii_lowercase) print('A-Z: ', string.ascii_uppercase) print('a-Z: ', string.ascii_letters) print('空白字符: ', json.dumps(string.whitespace)) print('标点符号: ', string.punctuation) print('可打印字符: ', json.dumps(string.printable)) def generate_random_string(length=32, include_uppercase=False): if include_uppercase: letters = string.ascii_letters else: letters = string.digits + string.ascii_lowercase return ''.join(random.choice(letters) for _ in range(length)) if __name__ == '__main__': print('随机生成32位定长的数字和字母的字符串: ', generate_random_string(32))
false
48126429f905971eee90e635493b037acd1c25ab
WangRongsheng/Python-functions
/functions/all函数详解.py
1,010
4.15625
4
''' all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。 元素除了是 0、空、FALSE 外都算 TRUE。 语法 以下是 all() 方法的语法: all(iterable) 参数 iterable -- 元组或列表。 返回值 如果iterable的所有元素不为0、''、False或者iterable为空,all(iterable)返回True,否则返回False; 注意:空元组、空列表返回值为True,这里要特别注意。 ''' print(all(['a','b','c',''])) #列表存在一个为空的元素,返回False print(all(['a','b','c','d'])) #列表都有元素,返回True print(all([0,1,2,3,4,5,6])) #列表里存在为0的元素 返回False print(all(('a','b','c',''))) #元组存在一个为空的元素,返回Fasle print(all(('a','b','c','d'))) #元组都有元素,返回True print(all((0,1,2,3,4,5))) #元组存在一个为0的元素,返回Fasle print(all([])) #空列表返回 True print(all(())) #空元组返回 True
false
12fb8c19521e25f35716a523601b787cc2bf71dd
WangRongsheng/Python-functions
/functions/hasattr函数详解.py
862
4.25
4
''' hasattr()函数用于判断是否包含对应的属性 语法: hasattr(object,name) 参数: object--对象 name--字符串,属性名 返回值: 如果对象有该属性返回True,否则返回False ''' class People(): sex='男' def __init__(self,name): self.name=name def peopleinfo(self): print('欢迎%s访问'%self.name) obj=People('zhangsan') print(hasattr(People,'sex')) #输出 True print('sex'in People.__dict__) #输出 True print(hasattr(obj,'peopleinfo')) #输出 True print(People.__dict__) #输出 {'__module__': '__main__', 'sex': '男', '__init__': <function People.__init__ at 0x0000019931C452F0>, 'peopleinfo': <function People.peopleinfo at 0x0000019931C45378>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
false
a9c2d495e009fd72fcab19d5d8f30dcbabd6411a
WangRongsheng/Python-functions
/functions/any函数详解.py
930
4.5625
5
''' any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。 元素除了是 0、空、FALSE 外都算 TRUE。 语法 以下是 any() 方法的语法: any(iterable) 参数 iterable -- 元组或列表。 返回值 如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true。 ''' print(any(['a','b','c',''])) #列表存在一个为空的元素,返回True print(any(['a','b','c','d'])) #列表都不为空,返回True print(any([0,'',False])) #列表里的元素全为 0,'',False 返回False print(any(('a','b','c',''))) #元组存在一个为空的元素,返回True print(any(('a','b','c','d'))) #元组都有元素,返回True print(any((0,'',False))) #元组里的元素全为 0,'',False 返回False print(any([])) #空列表返回 False print(any(())) #空元组返回 False
false
5742bff7dd4965c94ccf97768e8824563c296368
AyrtonDev/Curso-de-Python
/aula23.py
2,032
4.15625
4
# Aula sobre Tratamento de erros e Exceções ''' primt(x) ''' # Ao trocar N pelo M, temos um erro de sintaxe, e o outro problema é não ter declado x, gerando uma exceção d tipo NameError # Exemplos de Exceção.: ''' n = int(input('Número ')) print(f'Você digitou o número {n}') ''' # se digitar oito numeral, o programa vai rodar normal, mas se digitarmos oito por extenso, vai ter uma exceção do tipo ValueError ''' a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b print(f'O resultado é {r}') ''' # Neste caso, além da exceção ValueError, se o Denominador for 0, teremos a exceção do tipo ZeroDivisionError ''' r = 2 / '2' ''' # Neste havera a exceção do tipo TypeError ''' lst = [3, 6, 4] print(lst[3]) ''' # Este sera uma exceção do tipo IndexError ''' try: a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b except Exception as erro: print(f'Problema encontrado foi {erro.__class__}') else: print(f'O resultado é {r}') finally: print('Volte sempre! Muito Obrigado!') ''' # O comando try, irá testar o código # except ira executar se o codigo digitado der erro, podemos passar parametros para capturar o tipo de erro, neste caso 'Exception as erro:' # else é para quando estiver tudo perfeitamente # finally sera executado indiferente se der certo ou errado o codigo. Obs.: else e finally sao opcionais. try: a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b except (TypeError, ValueError): print('Tivemos um problema com os tipos de dados que você digitou.') except ZeroDivisionError: print('Não é possível dividir um número por zero!') except KeyboardInterrupt: print('O usuário preferiu não informar os dados!') except Exception as erro: print(f'O erro encontrado foi {erro.__cause__}') else: print(f'O resultado é {r:.1f}') finally: print('Volte sempre! Muito Obrigado!') # Um try pode ter varios except, e cada um pode ser programado para mostrar o tipo de erro.
false
fd2f5d24b21a5a51174ff865ce74373d3ac11283
KelvinGitu/PythonCodingCompetition
/palindrome.py
372
4.28125
4
#the program tests whether a given word is a palindrome. def isPalidrome(string): left_pos = 0 right_pos =len(string) - 1 while right_pos >= left_pos: if not string[left_pos] == string[right_pos]: return False left_pos += 1 right_pos -=1 return True name = str(input("Enter a name: ")) print(isPalidrome(name))
true
89e88a6aad1e494bb12a7c155f624cbbe19bfeb4
KelvinGitu/PythonCodingCompetition
/sum_of_first_n_nums.py
205
4.1875
4
def fastSum(number): """ the function takes a parameter, n and returns the sum of the first n numbers """ return int(num * (num + 1) / 2) num = int(input("Enter number: ")) fastSum(num)
true
34158a7afa6983dd02cdfc148a0c9fcd18170568
Vijayalakshmi-krishna/DataStructures-Practice
/problem_3.py
1,693
4.1875
4
""" Copyright (C) 2020 vijayalakshmisuresh This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ """ PROBLEM 3 Group Anagrams Given an array of strings, group anagrams together. Example: SAMPLE Input: ["eat", "tea", "tan", "ate", "nat", "bat"], SAMPLE Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. """ def find_anagrams(): inp_list = ["eat", "tea", "tan", "ate", "nat", "bat"] temp_list=[] op_list=[] i=0 while inp_list: curr_str=inp_list[i] temp_list=check_list(curr_str,inp_list) for j in temp_list: inp_list.remove(j) op_list.append(temp_list) print(op_list) ''' check_list() For anagrams program return anagram strings of the current string ''' def check_list(curr_str,inp_list): temp_list=[] for i in inp_list: count = 0 for char in curr_str: if char in i: count += 1 if count == len(curr_str): temp_list.append(i) return temp_list if __name__ == "__main__": find_anagrams()
true
ef72c1ca4962bfb12e5e8bd1ff5fe9fdb5466459
dreops/first-py-train
/task_grade_avg.py
1,698
4.3125
4
# flowchart exists name: Python_task_grading.drawio bio_score = float(input("What did you score for biology?")) chem_score = float(input("What did you score for chemistry?")) phy_score = float(input("What did you score for physics?")) # creating an average of the 3 scores ave_score = (bio_score + chem_score + phy_score) / 3 # bio_score grading if bio_score >= 70: print("Your biology grade is 1st") elif bio_score >= 60: print("Your biology grade is 2:1") elif bio_score >= 50: print("Your biology grade is 2:2") elif bio_score >= 40: print("Your biology grade is pass") else: print ("Your biology grade is fail, but don't let anyone ever tell you that you are a failure") # chem_score grading if bio_score >= 70: print("Your chemistry grade is 1st") elif bio_score >= 60: print("Your chemistry grade is 2:1") elif bio_score >= 50: print("Your chemistry grade is 2:2") elif bio_score >= 40: print("Your chemistry grade is pass") else: print ("Your chemistry grade is fail, but don't let anyone ever tell you that you are a failure") # phy_score grading if phy_score >= 70: print("Your physics grade is 1st") elif phy_score >= 60: print("Your physics grade is 2:1") elif phy_score >= 50: print("Your physics grade is 2:2") elif phy_score >= 40: print("Your physics grade is pass") else: print ("Your physics grade is fail, but don't let anyone ever tell you that you are a failure") # showing the final result: an average of the three scores print("Your average score from all 3 grades is" , ave_score) # bonus: add some logic! Task: if any score < 40 print fail # turns out I have kind of already included this initially
true
762420ae793a9411a87f430b55de1169dca8d535
joyDDT/python_code
/py/Python_Crash_Course/make_album.py
698
4.125
4
def make_album(singer,album,song = ''): if song: mk = {'singer_name':singer,'album_name':album,'song_number':song} else: mk = {'singer_name':singer,'album_name':album} return print(mk) make_album('cyx','wdg') make_album('zjl','nzhm',10) print('\n') print('\n') ##This code is for exercise 8-8 active = True while active: singer = input("Please enter a singer's name(enter 'q' to quit): ") if singer != 'q': album = input("Please enter one this singer's album(enter 'q' to quit): ") else: break if singer == 'q' or album == 'q': active = False else: make_album(singer,album) print('\n')
false
46228313868fbe9a2bac12f2cc36fe94bac66757
joyDDT/python_code
/py/Python_Crash_Course/chapter_9/ex9_13.py
707
4.375
4
from collections import OrderedDict vocabulary = OrderedDict( ) vocabulary['list'] = 'A list is a date structure that holds on an ordered collection of items.' vocabulary['tuple'] = 'Tuples are used to hold together multiple objects.' vocabulary['for'] = 'The for ... in loop statement is another looping statement which iterates over a sequence of objects.' vocabulary['if'] = 'The if statement is used to check a condition:if the conition is true, we run a block of statements, else we just jump over them.' vocabulary['string'] = 'A string is a seqeunce of character. Strings are basically just a bunch of words.' for term in vocabulary: print(term.title( ) + " : " + vocabulary[term])
true
95c0cbaa669d5ca4f41618a6ae7fda9850ea3a61
joyDDT/python_code
/py/Python_Crash_Course/even_or_odd.py
212
4.28125
4
number =int( input('Enter a number, and I will tell you if it is even or odd: ')) if number%2 == 0: print('The number ' + str(number)+ ' is even.') else: print('The number ' + str(number) + ' is odd.')
true
ac15df39fd721a9790d8aac28843616925639265
joyDDT/python_code
/py/oop_objvar.py
1,387
4.21875
4
#coding = UTF-8 class Robot: """This is a robot with a name.""" #This is a class variable which we can use to count the number of robots. population = 0 def __init__(self, name): """Initializes the data.""" self.name = name print("(Initializing {})".format(self.name)) #When this person is created,the robot #adds to the population Robot.population += 1 def die(self): """I am dying.""" print("{} is being destroyed!".format(self.name)) Robot.population -= 1 if Robot.population == 0: print("{} was the last one.".format(self.name)) else: print("There are still {:d} robots working.".format( Robot.population)) def say_hi(self): """Greeting by the robot.Yeah,they can do that.""" print("Greetings,my masters call me {}.".format(self.name)) @classmethod def how_many(cls): """Print the current population of robots.""" print("We have {:d} robots.".format(cls.population)) driod1 = Robot("R2-D2") driod1.say_hi( ) Robot.how_many( ) driod2 = Robot("C-3PO") driod2.say_hi( ) Robot.how_many( ) print("\nRobots can do some work here.\n") print("Robots have finished their work.So let's destroy them.") driod1.die( ) driod2.die( ) Robot.how_many( )
true
46d6212d924fe1ebbdde8f7db2684012e0c75a28
jimjshields/python_learning
/think_python/other/check_fermat.py
287
4.1875
4
def check_fermat(a, b, c, n): if n > 2 and a**n == b**n + c**n: print "Fermat was wrong!" else: print "Fermat was right..." a = int(raw_input("a?")) b = int(raw_input("b?")) c = int(raw_input("c?")) n = int(raw_input("n?")) check_fermat(a, b, c, n)
false
727281e5676bb290227dcc5d68e1fad8798a2d80
jimjshields/python_learning
/exercises/ex20.py
1,255
4.28125
4
# importing argv from sys module from sys import argv # assigning variables to argv - must type in command line script, input_file = argv # defining print_all function def print_all(f): # it prints f - the file in the command line print f.read() # defining the rewind function def rewind(f): # it goes to the beginning of the file f.seek(0) # defining the print_a_line function def print_a_line(line_count, f): # it prints "line_count" (an argument) and one line of the file - the line it's on print line_count, f.readline(), # defining current_file as the opening of the input_file current_file = open(input_file) # printing some nonsense print "First let's print the whole file:\n" # printing the entire file print_all(current_file) # printing some nonsense print "Now let's rewind, kind of like a tape." # rewinding the file rewind(current_file) # printing some nonsense print "Let's print three lines:" # starting at the first line current_line = 1 # printing the first line print_a_line(current_line, current_file) # moving to the next line current_line += 1 # printing that line print_a_line(current_line, current_file) # moving to the next line current_line += 1 # printing that linepyth print_a_line(current_line, current_file)
true
6b1d25b4e9e985ff1db301065979bce2905e9134
exer047/homework_8
/task_1_v1.py
1,100
4.34375
4
# хотел попробовать реализовать через классы, но так не получилось class Numbers: def __init__(self, value): self.value = value def __str__(self): return str(self.value) def __add__(self, other): return self.value + other.value def __sub__(self, other): return self.value - other.value def __mul__(self, other): return self.value * other.value def __truediv__(self, other): return self.value / other.value def __neg__(self): return - self.value if __name__ == '__main__': a = Numbers(3) b = Numbers(0) def error_checker(): try: operation_1 = a + b operation_2 = a - b operation_3 = a * b print(operation_1) print(operation_2) print(operation_3) except TypeError: print("Value is not a number!") try: operation_4 = a / b print(operation_4) except ZeroDivisionError: print("Division by zero!") except TypeError: pass error_checker()
true
37acc331802b3afa72ef6b8ba54bfe60aec8fe8a
TyreeBlakeBailey/Eng88_cybercourse
/Python/Python_Functions/FizzBuzz.py
2,660
4.46875
4
# Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number # For the multiples of five print “Buzz”. # For numbers which are multiples of both three and five print “FizzBuzz”."''' import random # imports teh random libary done for a bit of extra fun class FizzBuzz: # declared the calss with the name FizzBuzz @staticmethod def Fizz_Check(Num): # function that checks if the current number is a multiple of 3 if Num % 3 == 0: # if it is it will return True return True else: # else it will return false return False def Buzz_Check(Num): # function that checks if the current number is a multiple of 5 if Num % 5 == 0: # if it is it will return True return True else: # else it will return false return False def FizzBuzz(Amount): # main function that prints the numbers and text, takes a user input to tell it what number to # run to y = random.randint(1,Amount) # used for the extra sections on line 28 will generate a random number between 1 # and user input x = 1 while x <= Amount: # runs a loops up until the inputted number while also incrementing x while is inclusive if x == y: # random number will have a little surprise (Easter Egg) print( "༼つ ◕_◕ ༽つ") # What ever the random number is will be replaced with this face instead of the number elif FizzBuzz.Fizz_Check(x) and FizzBuzz.Buzz_Check(x): # checks if the current value of x is multiple of 3 and 5 print("FizzBuzz") # if the number is both a multiple of 3 and 5 it will print this line elif FizzBuzz.Fizz_Check(x): # checks if the current value of x is multiple of 3 print("Fizz") elif FizzBuzz.Buzz_Check(x): # checks if the current value of x is multiple of 5 print("Buzz") else: print(x) # if the value of x doesnt match any of the condition it will prints the number x += 1 # incrementation of x at the end of the loop Amount = input("How much would you like to go to? ") # allows the user to input if Amount.isdigit() and Amount != "0": # checks that the user has entered a nnumber and nothing else FizzBuzz.FizzBuzz(int(Amount)) # if it is a number then run the main function in the FizzBuzz class else: print("Please only enter numbers") # if the user enters anything that isnt a number that it will close and print # this line
true
cbd8e8b9630156825c4fe1f9c3d49712c45751ee
sphilmoon/coreyschafer
/basic/odd_numbers.py
341
4.28125
4
# printing odd numbers from the lists: list1 = [9, 62, 52, 89, 101, 22] list2 = [572, 85, 48, 137, 64] # by using the modulus %: print("These are the odd numbers:") for num in list1: if num % 2 != 0: print(num) # fiding the even numbers: print("Now the even numbers:") for num in list2: if num % 2 == 0: print(num)
true
2664be31fd7149bdb16ca283f8f152987c55e5ce
sphilmoon/coreyschafer
/basic/04_1_lists.py
692
4.15625
4
numbers = [2, 50, 33, 931, 16] print(sum(numbers)) # printing the summation of numbers courses = ['frozen', 'thread', 'weakref', 'imp', 'warnings'] print(courses.index('frozen')) print('imp' in courses) for item in courses: # creating a for loop, print(item) # indent basically means this command belongs to the for loop. # enumerate function: for index, item in enumerate(courses, start = 1): print(index, item) # turn list into a string (joint): courses_str = ' - '.join(courses) print(courses_str) # reversing back to the way it (split): new_list = courses_str.split(' - ') print(new_list) # creating empty lists: empty_list = [] empty_list = list()
true
4e80ebc1ff78e2442243df0fb498d556a9bb0d57
XxdpavelxX/Python-Projects
/Simple,Useful Python Projects/fileRenamer.py
646
4.21875
4
import os def rename_files(): #Get a list of file names. file_list=os.listdir(r"C:\Users\xxdpavelxx\Pictures\Anatomy\Injuries") #lists files in specified directory print file_list current_path=os.getcwd() os.chdir(r"C:\Users\xxdpavelxx\Pictures\Anatomy\Injuries") # can change directory who's files you want to rename. #For each file change its name. for file_name in file_list: print "old name of file: " +file_name os.rename(file_name,file_name.translate(None,"abc")) # will take out the characters 'a','b','c' from file names and replace it with ''. print "new name of file: " +file_name os.chdir(current_path) rename_files()
true
1908b579e47eb9aceb47cb8e76f26ef21bf92977
saithapan/code-20200227-saithapanragipani
/python_test.py
2,874
4.25
4
# Question1---------------Calculate the BMI (Body Mass Index) using Formula 1, BMI Category and Health # Question1---------------risk from Table 1 of the person and add them as 3 new columns # Question2 --------------Count the total number of overweight people using ranges in the column BMI Category of Table 1 # !!!! In line number 43 we are checking the condition for Question 2 # user data storing in variable users_data = [ {"Gender": "Male", "HeightCm": 171, "WeightKg": 96 }, { "Gender": "Male", "HeightCm": 161, "WeightKg":85 }, { "Gender": "Male", "HeightCm": 180, "WeightKg": 77 }, { "Gender": "Female", "HeightCm": 166,"WeightKg": 62}, {"Gender": "Female", "HeightCm": 150, "WeightKg": 70}, {"Gender": "Female","HeightCm": 167, "WeightKg": 82} ] # we will store final data in final_data list final_data = [] # creating a dict new_dict = {} over_weight_people_count = 0 for each_user_data in users_data: # assign each user weight to a variable -->weight weight = each_user_data['WeightKg'] # assign each user height to a variable -->height height = each_user_data['HeightCm'] # converting the heigth cms to mts height_to_cms = height/100 # We are creating new dictionary data for above users_data variable new_dict['Gender'] = each_user_data['Gender'] new_dict['HeightCm'] = each_user_data['HeightCm'] new_dict['WeightKg'] = each_user_data['WeightKg'] # calculating the BMI new_dict['BMI'] = weight/(height_to_cms**2) # condition for BMI Range and Health risk if(new_dict['BMI']<=18.4): new_dict['BMI_Category'] = 'Underweight' new_dict['Health_risk'] = 'Malnutrition risk' elif(new_dict['BMI']>=18.5 and new_dict['BMI'] <= 24.9): new_dict['BMI_Category'] = 'Normal weight' new_dict['Health_risk'] = 'Low risk' elif(new_dict['BMI']>=25 and new_dict['BMI'] <= 29.9): new_dict['BMI_Category'] = 'Overweight' # here we are also checking the overweight count for ----------------> QUESTION 2 over_weight_people_count += 1 new_dict['Health_risk'] = 'Enhanced risk' elif(new_dict['BMI']>=30 and new_dict['BMI'] <= 34.9): new_dict['BMI_Category'] = 'Moderately obese' new_dict['Health_risk'] = 'Medium risk' elif(new_dict['BMI']>=35 and new_dict['BMI'] <= 39.9): new_dict['BMI_Category'] = 'Severely obese' new_dict['Health_risk'] = 'High risk' elif(new_dict['BMI']>=40): new_dict['BMI_Category'] = 'Very severely obese' new_dict['Health_risk'] = 'Very high risk' # here we are appending the each user data to a list(final_data) and we are making the new_dict empty final_data.append(new_dict) new_dict = {} print(final_data) print(over_weight_people_count)
false
ce1595359104f4c54d5d2feef40fe6653ae70dac
Bartosz-Wegrzyn/Python_Exercises
/Task 26.py
2,092
4.25
4
# # This exercise is Part 2 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 1, Part 3, and Part 4. # # As you may have guessed, we are trying to build up to a full tic-tac-toe board. However, this is significantly more # than half an hour of coding, so we’re doing it in pieces. # # Today, we will simply focus on checking whether someone has WON a game of Tic Tac Toe, not worrying about how the # moves were made. # # If a game of Tic Tac Toe is represented as a list of lists, like so: # # game = [[1, 2, 0], [2, 1, 0], [2, 1, 1]] where a 0 means an empty square, a 1 means that player 1 put their token # in that space, and a 2 means that player 2 put their token in that space. # # Your task this week: given a 3 by 3 list of lists that represents a Tic Tac Toe game board, tell me whether anyone # has won, and tell me which player won, if any. A Tic Tac Toe win is 3 in a row - either in a row, a column, # or a diagonal. Don’t worry about the case where TWO people have won - assume that in every board there will only be # one winner. # # Here are some more examples to work with: winner_is_2 = [[2, 2, 0], [2, 1, 0], [2, 1, 1]] winner_is_1 = [[1, 2, 0], [2, 1, 0], [2, 1, 1]] winner_is_also_1 = [[0, 1, 0], [2, 1, 0], [2, 1, 1]] no_winner = [[1, 2, 0], [2, 1, 0], [2, 1, 2]] also_no_winner = [[1, 2, 0], [2, 1, 0], [2, 1, 0]] def who_won_tic_tac_toe(board, size): # only for 3x3 game for i in range(size): if board[i][0] == board[i][1] == board[i][2] and board[i][0]: return board[i][0] for j in range(size): if board[0][j] == board[1][j] == board[2][j] and board[0][j]: return board[0][j] if board[0][0] == board[1][1] == board[2][2] and board[0][0] != 0: return board[0][0] if board[0][2] == board[1][1] == board[2][0] and board[0][2] != 0: return board[0][0] print(who_won_tic_tac_toe(also_no_winner, 3))
true
22a60a5a3f3753f30c603e4d6b23e8dfb352bdf9
Bartosz-Wegrzyn/Python_Exercises
/Task 13.py
689
4.4375
4
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this # opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in # the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the # sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, # 13, …) def fib_number(n): if n == 0: return(0) elif n == 1: return(1) elif n > 1: return(fib_number(n-1)+fib_number(n-2)) for fib in range(21): print(fib_number(fib))
true
1dad17b83b1a6de0a3c85cec8b41ce066df1733f
wytoriaa/Algoritmos_EstruturaDeDados_UFPE_S2
/lista01.py
1,418
4.21875
4
# Malu precisa da sua ajuda para criar um programa que verifica se uma expressão está bem formada por chaves. A definição de expressão bem formada é a seguinte: # Uma expressão vazia é sempre bem formada (i.e. uma string vazia) # Se E é bem formada, então { E } também é bem formada # Se E é bem formada, então E E também é bem formada # Ela conseguiu coletar alguns exemplos de expressões bem formadas para te ajudar a entender o problema: # { { { } } } # { } { } # { { } } { } # { { } { { } { } } } # E também alguns exemplos de expressões mal formadas: # { } { # { { } } { } } # { } { } } # { { } } { { { } } def main(): leitura = input() percorrer_chaves = [] #o len vai ser todos os input da leitura, pq ele vai calcular o tamanho da entrada # o i é a posição do elemento, ele conta a partir do zero for i in range(len(leitura)): if leitura[i] == '{': percorrer_chaves.append('{') #print(percorrer_chaves) if leitura[i] == '}': if len(percorrer_chaves) > 0: percorrer_chaves.pop() #print(percorrer_chaves) else: percorrer_chaves.append('}') #print(percorrer_chaves) if len(percorrer_chaves) == 0: print('S') else: print('N') if __name__ == '__main__': main()
false
068958ccf4def63f2d98d87419103dc773ad135a
MauKi/ccri
/concepts/Class_3/mpg.py
262
4.34375
4
# # This program will calculate the user's MPG # milesDriven = int(input("How many miles have you driven? ")) gallonsUsed = int(input("How many gallons have you used? ")) MPG = milesDriven / gallonsUsed print("Your car is getting", int(MPG), "miles per gallon.")
true
9e24374c105226638a0469c0a6ed4f907f8d087a
csdotson/Data_Structures_Algorithms
/algorithms/quick_sort.py
1,495
4.125
4
''' Python implementation of quicksort algorithm ''' comparison_count = 0 def quick_sort(A, left, right): global comparison_count if right - left <= 1: return comparison_count += (right - left - 1) pivot_location = partition(A, left, right) quick_sort(A, left, pivot_location) quick_sort(A, pivot_location+1, right) def partition(A, left, right): # # Choosing first element as pivot: # pivot = A[left] # # Choosing last element as pivot: # pivot = A[right - 1] # swap(A, left, right - 1) # Using median of 3 as pivot pivot = median_of_three(A, left, right) i = left + 1 for j in range(i, right): if A[j] < pivot: swap(A, i, j) i += 1 swap(A, left, i-1) return i-1 def median_of_three(A, left, right): first, last, middle = A[left], A[right - 1], A[(left + right -1)//2] values = [first, middle, last] for i in range(len(values)): for j in range(i+1, len(values)): if values[i] > values[j]: swap(values, i, j) if values[1] == last: swap(A, left, right - 1) if values[1] == middle: swap(A, left, (left + right -1)//2) return values[1] def swap(A, first, second): A[first], A[second] = A[second], A[first] # Manipulating content file with open("int_list.txt") as f: content = f.readlines() content = [x.strip() for x in content] content = [int(x) for x in content]
true
894a3bdae734a77aa109842efd20d92c5d185612
jackb0swell/com404
/99-practice/minTCAtry1/Q3-loop/bot.py
333
4.25
4
print("How many days remain until the next full moon?") days_remaining = int(input()) print("We must count the days...") print() for count in range(days_remaining, 0, -1): print("The full moon will be upon us in", count, "days") print("It's a full moon. The beast has been unleashed!") print("May it have mercy on our souls")
true
64f46d04a525e44d0c0b70233095458b9628df62
Flevian/andelabootcamp16
/day1/fizz_buzz.py
651
4.3125
4
def fizz_buzz(number): ''' this a fizz_buzz that prints the number if it is not divisible by 3 or 5 prints buzz if the number is divisible by 5 only prints fizz if the number is divible by 3 only prints FizzBuzz if the number is divible by both 3 and 5 ''' number3 = "Fizz" number5 = "Buzz" if number % 3 == 0 and number % 5 == 0: allnumber = number3, number5 value = "".join(allnumber) elif number % 5 == 0: value = number3 elif number % 3 == 0: value = number5 else: value = number return value print(fizz_buzz(7))
true
4bc767bda74b37cd773136fd3f6452085261a23b
bschwyn/Think-Python
/exercises/2_Variables/exercise3.py
779
4.5625
5
#3 #Write a Python program to solve the general version of the above problem. #Ask the user for the time now (in hours), and ask foro the number of hours to wait. #Your program should output what the time will be on the clock #when the alarm goes off. #input number, returns string time = input("What time is it?") print(type(time)) #need to turn time into an int before performing operations on it print('The time on the clock will be', int(time) % 12, "o'clock") #things that don't work: #time = input("What time is it?") #'not all arguments converted during string formatting' #print('The time on the clock will be ', time+1, "o'clock") #Can't convert 'int' object to str implicitely' # **questions** # when you print the type, is says "class: ____" What's the class?
true
fdd79de456f2c45b7b8bdd3b79e99022a607f76f
shreyakapadia10/Using-Python-to-Interact-with-the-Operating-System
/Module4/seconds.py
500
4.1875
4
def to_seconds(hours, minutes, seconds): return 3600*hours+minutes*60+seconds print("Welcome to this time converter") cont = 'y' while cont.lower() == 'y': hours = int(input("Please enter hours: ")) minutes = int(input("Please enter minutes: ")) seconds = int(input("Please enter seconds: ")) print("That's {} seconds: ".format(to_seconds(hours, minutes, seconds))) print() cont = input("Do you want to do another conversion? ['y' to continue]: ") print("Good Bye!")
true
7c38d27f89b6a045fceeda75f01b35da1c60ec22
sammysamsamsama/ProjectEuler
/Python/Problem_37.py
1,141
4.125
4
# Trunctable primes # # The number 3797 has an interesting property. # Being prime itself, it is possible to continuously remove digits from left to right, # and remain prime at each stage: 3797, 797, 97, and 7. # Similarly we can work from right to left: 3797, 379, 37, and 3. # # Find the sum of the only eleven primes that are both truncatable from left to right and right to left. # # NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. from Problem_26 import is_prime def is_trunctable_prime(n): if not is_prime(n): return False n = str(n) for i in range(1, len(n)): if not is_prime(int(n[i:])) or not is_prime(int(n[:-i])): return False return True if __name__ == '__main__': trunctable_primes = [] n = 23 while len(trunctable_primes) < 11: if is_trunctable_prime(n): trunctable_primes.append(n) n += 2 print("The sum of the only eleven primes that are both trunctable from left to right and right to left:", sum(trunctable_primes)) print("The eleven primes:", trunctable_primes)
true
74a4eac4a74f4046378155856f0fe0f584a31b7d
sammysamsamsama/ProjectEuler
/Python/Problem_41.py
902
4.125
4
# Pandigital prime # # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. # For example, 2143 is a 4-digit pandigital and is also prime. # # What is the largest n-digit pandigital prime that exists? from Problem_26 import is_prime from Problem_32 import is_pandigital largest_n_digit_pandigital_prime = 1 # start from 7654321 because {987654321} (9-digit pandigitals) and {87654321} are divisible by 3 and so not prime # remember that if the sum of a number's digits is divisible by 3, the number is also divisible by 3 n = 7654321 while largest_n_digit_pandigital_prime == 1: if is_prime(n) and is_pandigital(n, n_max=len(str(n))): print(n, "is prime and is a {}-digit pandigital".format(len(str(n)))) largest_n_digit_pandigital_prime = n break n -= 2 print(largest_n_digit_pandigital_prime)
false
92809fee9aec78581f8b1b4695b122f72975bea3
rodionlim/algorithms
/python/Data Structures/BinarySearchTree.py
850
4.15625
4
from BinaryTree import Node # Driver program to test the binary tree functions # Let us create the following BST # 8 # / \ # 3 10 # / \ / \ # 1 6 60 80 # / \ \ # 4 7 14 # / # 13 bTree = Node(8) bTree.left = Node(3) bTree.right = Node(10) bTree.left.left = Node(1) bTree.left.right = Node(6) bTree.left.right.left = Node(4) bTree.left.right.right = Node(7) bTree.right.right = Node(14) bTree.right.right.left = Node(13) def search(root, key, traverse=False): if traverse: print(root.val) if root == None: return root if root.val == key: return root elif key < root.val: return search(root.left, key, traverse) else: return search(root.right, key, traverse) search(bTree, 13) # Binary search path = search(bTree, 7, True) # Print out the path traversed
true
c50469d1b6ec2e2a95dc9b3a84363eef3fbb8f9a
aniketgauba67/Python-programs
/Task2.py
239
4.28125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 00:34:23 2021 @author: admin """ # Finding file extension name=input("Enter file name:") file_extension= name.split(".") print("the extension of the file is:",file_extension[1])
true
95dbf9e1c4702ba108e097b37917bd3f40192696
Krish3na/Edyst-TCS-Codevita-Solutions
/Basics/TakeInputs/stringArray.py
793
4.25
4
''' Input String Array Input String Array Write a program that takes as input String arrays and prints the String arrays Input Format The first line contains N, the number of test cases. The N lines after that contain the test cases Each test case starts with k, the number of elements in the array This is followed by k elements of the array Output Format Print each array in a single line Sample Input / Output Input 3 1 hello 5 hello welcome to the codevita 8 there is nothing better than coding agreed ? Output hello hello welcome to the codevita there is nothing better than coding agreed ? ''' N=int(input()) for i in range(N): x=list(map(str,input().split())) for i in range(1,len(x)): print(x[i],end=" ") print()
true
ec52278fcbcd646a5f87f5d6c15f1bdf85afc058
RapetiBhargav/Data_Science_Playground
/Python-Basics/Python-Tuple.py
910
4.28125
4
a_tuple = ("a", "b", "mpilgrim", "z", "example") print (a_tuple) #('a', 'b', 'mpilgrim', 'z', 'example') print (a_tuple[0] ) #a print (a_tuple[-1]) #example print (a_tuple[1:3] ) #('b', 'mpilgrim') #Tuples are immutable #print (a_tuple.append("new")) #print (a_tuple.remove("z")) print (a_tuple.index("example") ) #Boolean context def is_it_true(anything): if anything: print("yes, it's true") else: print("no, it's false") print (is_it_true((False,))) #yes, it's true #None print (type((False))) #<class 'bool'> ##Just False is boolean. Give (False,) for tuple print (type((False,))) #<class 'tuple'> #Assigning Multiple Values At Once v = ('a', 2, True) (x, y, z) = v print (x) #a print (y) #2 print (z) #True
false
ffba21062dcd7ccb77324f8942cebabf011736e7
Sobolp/GB_python_base
/HW2/3.py
558
4.25
4
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. """ a = str(int(input('Введите натуральное число: '))) def reverse(s): # print(s) if len(s) == 2: return s[-1] + s[0] if len(s) == 1: return s[0] return s[-1] + reverse(s[1:len(s) - 1]) + s[0] print(reverse(a))
false
f5a8d834e4f1921781e816cdf7d080be78d32472
Sobolp/GB_python_base
/HW2/2.py
562
4.15625
4
""" 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). """ a = str(int(input('Введите натуральное число: '))) even = 0 odd = 0 for num in a: if int(num) % 2 == 0: even = even + 1 else: odd = odd + 1 print('В числе %s цифр четных - %d, нечетных - %d ' % (a, even, odd))
false
42246f0924f65b9f893d433ea19666dd8b00cb4b
abhim4536/Python-Game
/Fun With Python/Find the hidden number.py
677
4.125
4
import random n = random.randint(1,101) number_of_guesses = 1 print("You Have Only 10 Chance To Guess The Right Number Try Your Luck") while number_of_guesses <= 10: guesse_number = int(input("Guess The Right Number Between 1 To 100: ")) if guesse_number > n: print("Your Guessing is Too High!") elif guesse_number < n: print("Your Guessing is Too Low!") else: print("You Won") print("Your Winning Guesses Is", number_of_guesses) break print(10-number_of_guesses,"Guesses Has Left") number_of_guesses += 1 if(number_of_guesses>10): print("Game Over,Better Luck Next Time,\n"f"The Hidden Number Is {n}.")
true
11d7f99e9720b6f18a66e837a5a73d86761fa153
dsernst/Learn-Python-the-Hard-Way
/ex6.py
1,005
4.25
4
#define the string, with a decimal int inside of it x = "There are %d types of people." % 10 #define the string binary = "binary" #define the string do_not = "don't" #define the string, using the two previous in there. y = "Those who know %s and those who %s." % (binary, do_not) #print the first string x print x #print the string y print y #print a string with the string x inside of it print "I said: %r." % x #print a string with the string y inside of it print "I also said: '%s'." % y #define the boolean var False hilarious = False #define the string, with a format string inside of it, #although the var that gets added is left unstated joke_evaluation = "Isn't that joke so funny?! %r" #print string joke_evaluation using var hilarious as the format string print joke_evaluation % hilarious #define the string w = "This is the left side of..." #define the string e = "a string with a right side." #print the last two strings, one after another print w + e
true
3b37ae8f048005520a82a2f330120796fba9f4c5
PromytheasN/FromZeroToHeroCompletePythonBootcamp
/Generators Homework.py
1,271
4.34375
4
import random """ Problem 1 Create a generator that generates the squares of numbers up to some number N. """ def gensquares(N): for number in range(N): yield number**3 """ Problem 2 Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. """ def rand_num(low, high, n): for n in range(n): yield random.randint(low, high) """ Problem 3 Use the iter() function to convert the string below into an iterator: s = "hello" """ def iterator(s): for letter in s: yield letter """ Problem 4 Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement. """ """ You can do this anywhere where you do not need the full list of something stored but you would like to calculate numbers by creating a list and use some of them, in order to gain better memory managment """ """ Extra Credit! Can you explain what gencomp is in the code below?) my_list = [1,2,3,4,5] gencomp = (item for item in my_list if item > 3) for item in gencomp: print(item) """ """ It creates values acording to the parameters provided and prints them while does not store them in a list. """
true
a783fa95d2dd57e1dfd5db49073de3c1e4a0d252
johnstill/euler
/python/problem001.py
449
4.28125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def sum_multiples_in_range(start, stop, *mults): """ >>> sum_multiples_in_range(1, 10, 3, 5) 23 >>> sum_multiples_in_range(1, 1000, 3, 5) 233168 """ return sum(n for n in range(start, stop) if any(n % m == 0 for m in mults))
true
157faf3d4bad1e9e38f1c45367f9bc63be5c1f13
diegolinkk/exercicios-python-brasil
/estrutura-de-repeticao/exercicio10.py
271
4.15625
4
#Faça um programa que receba dois números inteiros e gere os números inteiros que # estão no intervalo compreendido por eles. n1 = int(input("Digite um número inteiro: ")) n2 = int(input("Digite outro número inteiro: ")) for n in range((n1 +1),n2): print(n)
false
106d259513a04788cb5ad0ee06653328a65cb685
diegolinkk/exercicios-python-brasil
/exercicios-com-listas/exercicio07.py
421
4.3125
4
#Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a multiplicação e os números. numeros = [] for _ in range(5): numero = int(input("Digite um número: ")) numeros.append(numero) print(f"Soma dos números: {sum(numeros)}") multiplicacao = 1 for numero in numeros: multiplicacao *= numero print(f"Multiplicação dos números: {multiplicacao}") print(f"Números: {numeros}")
false
5b29c04a87bd78cabbafc5f2e95f07b102f081a6
diegolinkk/exercicios-python-brasil
/estrutura-de-decisao/exercicio02.py
219
4.15625
4
#Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. n1 = int(input("Digite um número: ")) if n1 >= 0: print("O número é positivo") else: print("O número é negativo")
false
81ad9400379364f441058bade41c384d5bcbb2ed
diegolinkk/exercicios-python-brasil
/estrutura-de-repeticao/exercicio17.py
308
4.28125
4
#Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5!=5.4.3.2.1=120 numero = int(input("Digite um número: ")) numero_inicial = numero fatorial = numero while numero > 1: numero -=1 fatorial *= numero print(f"Fatorial de {numero_inicial} é: {fatorial}")
false
d54a2dcd518aeb9f78fafda8e3261a20e040bfa5
diegolinkk/exercicios-python-brasil
/estrutura-de-repeticao/exercicio43.py
1,594
4.21875
4
# O cardápio de uma lanchonete é o seguinte: # Especificação Código Preço # Cachorro Quente 100 R$ 1,20 # Bauru Simples 101 R$ 1,30 # Bauru com ovo 102 R$ 1,50 # Hambúrguer 103 R$ 1,20 # Cheeseburguer 104 R$ 1,30 # Refrigerante 105 R$ 1,00 # Faça um programa que leia o código dos itens pedidos e as quantidades desejadas. # Calcule e mostre o valor a ser pago por item (preço * quantidade) e o total geral do pedido. # Considere que o cliente deve informar quando o pedido deve ser encerrado. itens = { 100: ("Cachorro Quente", 1.20), 101: ("Bauru Simples", 1.30), 102: ("Bauru com ovo", 1.50), 103: ("Hambúrguer", 1.20), 104: ("Cheeseburguer", 1.30), 105: ("Refrigerante", 1.00), } pedido = [] while True: codigo = int(input("Digite um número da tabela ou 0 para sair: ")) if codigo == 0: break quantidade = int(input("Digite a quantidade desejada: ")) pedido.append((codigo,quantidade)) print(f"{'codigo'} {'Item'} {'Valor Unitário':>32} {'Quantidade':>14} {'Total':>8}") valor_total_pedido = 0.0 for codigo_item,quantidade in pedido: if codigo_item in itens: nome_item = itens[codigo_item][0] valor_unitario = itens[codigo_item][1] quantidade = float(quantidade) valor_total_item = valor_unitario * quantidade valor_total_pedido += valor_total_item print(f"{codigo_item} {nome_item:>15} {valor_unitario:>15.2f} {quantidade:>15.0f} {valor_total_item:>15.2f}") print(f"Valor total do pedido: R$ {valor_total_pedido:>41.2f}")
false
efc027bf22072d8db0606b04baaf32f0739a1b88
diegolinkk/exercicios-python-brasil
/exercicios-com-funcoes/exercicio13.py
876
4.25
4
# Desenha moldura. # Construa uma função que desenhe um retângulo usando os caracteres ‘+’ , ‘−’ e ‘| ‘. # Esta função deve receber dois parâmetros, linhas e colunas, sendo que o valor por omissão é o valor mínimo igual a 1 e o valor máximo é 20. # Se valores fora da faixa forem informados, eles devem ser modificados para valores dentro da faixa de forma elegante. def desenha_moldura(linha = 1, coluna = 1): print("+",end="") for coluna in range(coluna): print("-",end="") print("+") for linha in range(linha -1): print("|",end="") for coluna in range(coluna + 1): print(" ",end="") print("|") print("+",end="") for coluna in range(coluna + 1): print("-",end="") print("+") desenha_moldura(4,4) desenha_moldura(15,2) desenha_moldura(33,100)
false
bd90204c0075cc155675ff0ee9e9284e39c579dc
diegolinkk/exercicios-python-brasil
/estrutura-de-repeticao/exercicio31.py
1,078
4.1875
4
# O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui uma loja de conveniências. # Faça um programa que implemente uma caixa registradora rudimentar. O programa deverá receber um número desconhecido de valores referentes aos preços das mercadorias. # Um valor zero deve ser informado pelo operador para indicar o final da compra. # O programa deve então mostrar o total da compra e perguntar o valor em dinheiro que o cliente forneceu, para então calcular e mostrar o valor do troco. # Após esta operação, o programa deverá voltar ao ponto inicial, para registrar a próxima compra. A saída deve ser conforme o exemplo abaixo: # Lojas Tabajara # Produto 1: R$ 2.20 # Produto 2: R$ 5.80 # Produto 3: R$ 0 # Total: R$ 9.00 # Dinheiro: R$ 20.00 # Troco: R$ 11.00 # ... numero_produto = 0 valor = -1 total = 0 while valor !=0: numero_produto +=1 valor = float(input(f"Produto {numero_produto}: R$: ")) total += valor print(f"Total: R${total}") dinheiro = float(input("Dinheiro: R$")) print(f"Troco: R${dinheiro - total:.2f}")
false
4cf233e79c8f79f57e3ebb629a79cd27129f8e3c
Voodur/Python-Programs
/10_19_15.py
331
4.25
4
numbers_list = [] number = int(input('Enter a positive integer')) while number > 0: numbers_list.append(number) number = int(input('Enter a positive integer')) numbers_list.sort() print(numbers_list) print() print('Smallest number:', numbers_list[0]) print('Largest number: ',numbers_list[len(numbers_list)-1])
true
ee580dd7c716006219a95fe0e69bbbf53b599333
meoclark/ML_Models_Projects
/ProjectPerceptronLG.py
1,336
4.15625
4
#Guide #In this project, we will use perceptrons to model the fundamental building blocks of computers — logic gates. #diagrams of AND, OR, and XOR gates #Input 1 Input 2 Output #0 0 0 #0 1 0 #1 0 0 #1 1 1 #We’ll discuss how an AND gate can be thought of as linearly separable data and train a perceptron to perform AND. #Input 1 Input 2 Output #0 0 0 #0 1 1 #1 0 1 #1 1 0 #We’ll think about why an XOR gate isn’t linearly separable and show how a perceptron fails to learn XOR import seaborn as sns from sklearn.linear_model import Perceptron import matplotlib.pyplot as plt import numpy as np from itertools import product data = [[0, 0],[0,1],[1,0], [1,1]] labels = [0, 0, 0,1] plt.scatter([point[0] for point in data],[point[1] for point in data],c = labels) plt.show() classifier = Perceptron(max_iter = 40) classifier.fit(data,labels) print(classifier.score(data,labels)) #print(classifier.decision_function([[0, 0], [1, 1], [0.5, 0.5]])) x_values = np.linspace(0, 1, 100) y_values = np.linspace(0, 1, 100) point_grid = list(product(x_values,y_values)) distances = classifier.decision_function(point_grid) abs_distances = [abs(pt) for pt in distances] distances_matrix = np.reshape(abs_distances, (100,100)) heatmap = plt.pcolormesh(x_values,y_values,distances_matrix) plt.colorbar(heatmap) plt.show()
true
1a1d3cf9ad86f0261fcf2d91c23fb4db55a3fa80
deep56parmar/python-examples
/Introduction/variablesPart3.py
505
4.15625
4
# Created By: Deep Parmar ('deep56parmar@hotmail.com') # Variables Part 3 (Strings and Function) age = 22 print('My age is ' + str(age) + ' years.') # str() funtion convert any datatype to string. # Replacement Fields print('My age is {0} years.'.format(age) ) # format() use for formatting strings using multiple arguments. print('There are {0} days in {1}, {2}, {3}, {4}, {5}, {6}, {7}, '.format(31, "January", "March", "May", "July", "August", "October", "December")) print('Pi is approximately {0:12.50f} '.format(22/7))
true
c56f6479215750dc40150c43dff69da39030f6d3
Solers36/python_my
/website/Chapter_14_Modules_testov.py
1,242
4.28125
4
import square answer = input("Введите цифру соответствующую фигуте, площадь которой Вы хотите вычислить? (прямоугольника-1, треугольника-2 или круга-3) ") if answer == "1": a = float(input("Чему равна длина прямоугольника? ")) b = float(input("Чему равна ширина прямоугольника? ")) result_of_calculation = square.rectangle(a, b) elif answer == "2": a = float(input("Чему равна длина основания треугольника? ")) h = float(input("Чему равна высота треугольника? ")) result_of_calculation = square.triangle(a, h) elif answer == "3": r = float(input("Чему равен радиус круга? ")) result_of_calculation = square.circle(r) else: print("Для вычисления площади необходимо ввести цифру соответствующую фигуре(прямоугольника-1, треугольника-2 или круга-3)") print("А Вы ввели '{0}'.".format(answer)) print("Площадь равна: {0}".format(result_of_calculation))
false
07de3d5c1dc141c44721da495437524184864216
Solers36/python_my
/website/Chapter_19_Tuple_testov.py
1,932
4.28125
4
# 1. # Чтобы избежать изменения исходного списка, не обязательно использовать кортеж. Можно создать его копию с помощью # метода списка copy() или взять срез от начала до конца [:]. Скопируйте список первым и вторым способом и убедитесь, # что изменение копий никак не отражается на оригинале. first_list = [1, 2, 3] second_list = ["4", "5", "6"] third_list = first_list.copy() fourth_list = second_list[:] third_list[1] = "2" fourth_list.append(7) print(first_list, second_list, third_list, fourth_list, sep="\n", end="\n\n") # 2 # Заполните один кортеж десятью случайными целыми числами от 0 до 5 включительно. Также заполните второй кортеж # числами от -5 до 0. Для заполнения кортежей числами напишите одну функцию. Объедините два кортежа с помощью оператора +, # создав тем самым третий кортеж. С помощью метода кортежа count() определите в нем количество нулей. Выведите на экран # третий кортеж и количество нулей в нем. import random def creating_a_random_tuple(first, last, size): new_list = [] for i in range(size): i = random.randint(first, last) new_list.append(i) return tuple(new_list) first_tuple = creating_a_random_tuple(0, 5, 10) second_tuple = creating_a_random_tuple(-5, 0, 10) third_tuple = first_tuple + second_tuple print(third_tuple) print("Колличество нулей в кортеже: {}.".format(third_tuple.count(0)))
false
6aeeffac90b33c28344ced34b913e8b29f0e5aec
Aaron-Raphael/Python_Crash_Course-Book
/8_Classes/electric_car.py
1,164
4.21875
4
# importing module inside a module from car import Car class Assistant(): """attempt to model a assistant""" def __init__(self , assistant_version = 2.0): """initialise assistant attribute""" self.assistant_version = assistant_version def describe_assistant(self): print('the A.I assistant is version', self.assistant_version) class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """Initialize attributes of the parent class.""" super().__init__(make, model, year) # super function makes connection between child and parent class self.battery_size = 70 # defining attribute for child class self.assistant = Assistant() # defining external class as attribute def describe_battery(self): """Print a statement describing the battery size.""" print("This car has a " + str(self.battery_size) + "-kWh battery.") def fill_gas_tank(self): # overriding methods from the parent class """Electric cars don't have gas tanks.""" print("This car doesn't need a gas tank!")
true
61e986986be22c86cd716b02bc262151edc900bd
Aaron-Raphael/Python_Crash_Course-Book
/5_Dictionaries/1_Person.py
702
4.25
4
# dictionary is declared by key value pair in {} person = { 'name':'aaron', 'age':19, 'city':'cbe', 'lang_2':'tamil' } # looping through dictionary for key in person: # for key in person.keys(): print( key,'is',person[key]) # entering new key:value pair if 'school' not in person: sch_name = input('enter "school" value: ') person['school'] = sch_name # person['school'] = input('enter "school" value: ') # for looping key and value for key,val in person.items(): print(key,'is',val) # sorted looping for key in sorted(person): print( key,'is',person[key]) # looping through the values print('user info :') for v in person.values(): print('\t',v)
true
82bfdb9b4d0a2894c8ab2f564ad089fddd621917
gladystyn/MCQ_revision_program
/app.py
2,946
4.21875
4
print("Title of program: MCQ revision program") print() counter = 0 score = 0 total_num_of_qn = 3 counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "What is the formula for speed?") print(" a) distance x time") print(" b) distance divide by time") print(" c) distance + time") print(" d) time - distance") answer = input("Your answer: ") answer = answer.lower() if answer == "a": output = "Wrong. This is not the correct formula." score -=1 elif answer == "b": output = "Yes, that's right!" score -=1 elif answer == "c": output = "Wrong. This is not the correct formula." tracker =1 score +=1 elif answer == "d": output = "Wrong. This is not the correct formula." score -=1 else: output = "Please choose a, b, c or d only." print() print(output) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "What is the function of fats?") print(" a) insulator against heat loss") print(" b) forms the bulk of faeces") print(" c) repairs worn out cells in the body") print(" d) promotes cell growth") answer = input("Your answer: ") answer = answer.lower() if answer == "a": output = "Yes, that's right!" tracker =1 score +=1 elif answer == "b": output = "Wrong. This is the function of fibre from some types of carbohydrates." score -=1 elif answer == "c": output = "Wrong. This is the function of proteins." score -=1 elif answer == "d": output = "Wrong. This is the function of proteins." score -=1 else: output = "Please choose a, b, c or d only." print() print(output) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "Which is a property of light?") print(" a) Light travels slower than sound.") print(" b) Light is a longitudinal wave.") print(" c) Light travels in a curvy line.") print(" d) Light travels in a straight line.") answer = input("Your answer: ") answer = answer.lower() if answer == "a": output = "Wrong. Light travels faster than sound. That's why we see the light from lightning before hearing thunder." score -=1 elif answer == "b": output = "Wrong. Light is a transverse wave." score -=1 elif answer == "c": output = "Wrong. Light travels in a straight line." score -=1 elif answer == "d": output = "Yes, that's right!" tracker =1 score +=1 else: output = "Please choose a, b, c or d only." print() print(output.lower()) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() print("End of quiz!")
true
5903f65d49655109e693e2e5d67cdbf077ca5ce2
christensenst/python_sandbox
/python_sandbox/iteration/basic_iteration.py
2,872
4.3125
4
# The Iteration Protocol # Any object with a next() method (Python 2.X) to advance to a next result, which raises StopIteration at the end of # the series of results, is considered an iterator in Python. Any such object may also be stepped through with a for # loop or other iteration tool, because all iteration tools normally work internally by calling next() on each # iteration and cathcing the StopIteration exception to determine when to exit. # # The iteration protocol is really based on two objects, used in two distinct steps by iteration tools: # the iterable object you request iteration for, whose __iter__ is run by iter # the iterator object returned by the iterable that actually produces values during the iteration, whose next # method is run by the built-in next() and raises StopIteration when finished producing results. # In some cases, such as files, these two objects are the same def basic_iteration(): # files have a method called readline. At the end of the file, an empty string is returned. f = open('__init__.py') print f.readline() print f.readline() print f.readline() print f.readline() print f.readline() f.close() # files also have a method called next. The only noticeable difference is that next() raises a builtin # StopIteration exception at end of file instead of returning an empty string. f = open('__init__.py') try: print f.next() print f.next() print f.next() print f.next() print f.next() except StopIteration: print "Whoa, we really had to catch StopIteration, otherwise this would've blown sky high!" finally: f.close() # the best way to read a text file line by line is to not read it at all - instead, allow the for loop to # automatically call next() to advance to the next line on each iteration. When the for loop begins, it first # obtains an iterator from the iterable object by passing it to the iter built-in function; the object returned # by iter in turn has the required next method. The iter function internally runs the __iter__ method. for line in open('__init__.py'): print line #FYI: iterators run at C language speed inside Python # we can also manually iterate by calling the built-in next() method and passing in an iterator object f = open('__init__.py') try: print next(f) print next(f) print next(f) print next(f) print next(f) except StopIteration: print "yep, had to catch StopIteration again" # Here's how it works for sequence objects (which are not their own iterator object) numbers = [1, 2, 3] iterator = iter(numbers) print iterator.next() print iterator.next() print iterator.next() if __name__ == '__main__': basic_iteration()
true
fe8984f9c4cc4de593600214c5aa10519f1b6f0c
cris711/100daychallenge
/evens and odds.py
991
4.1875
4
def evens(x): for i in range(x): tmp = i % 2 if tmp == 0: print(i) else: pass def odds(x): for i in range(x): tmp = i % 2 if tmp == 0: pass else: print(i) while 1: choice = int(input("Please enter 0 for even or 1 for odd: ")) if choice == 0: check = 0 while check == 0: try: x = int(input("Please enter a number to get all even numbers up to the inputed number: ")) evens(x) check = 1 except ValueError: print("Error Input was not an Integer") elif choice == 1: check = 0 while check == 0: try: x = int(input("Please enter a number to get all odd numbers up to the inputed number: ")) odds(x) check = 1 except ValueError: print("Error Input was not an Integer")
false
c695f89bce626f46e95b9453c7c99864aac93439
machester/Learning
/python_code/python_function/for_loop.py
513
4.125
4
# -*- coding: UTF-8 -*- import sys # for loop rang from 1 to 10, step is 1 for index in range(1, 10, 1): print('index = ', + index) print('----------------------------------') # for loop rang from 0 to 20, step is 5 for index in range(0, 20, 5): print('index step by 5 is: ', + index) print('----------------------------------') # for loop print 'end = ''' test print('index = ', sep=' ', end=' ') for index in range(0, 20, 5): print(index, end=', ') print('\n') print('----------------------------------')
true
1935545b43f5710e917bda6e7f1905670879645b
adamelid/PythonVerk
/Assignment11/listToTuple.py
495
4.3125
4
#list_to_tuple function goes here def list_to_tuple(a_list): a_tuple = () intList = [] try: for i, value in enumerate(a_list): intList.append(int(value)) a_tuple += tuple(intList[i]) except ValueError: print("Error. Please enter only integers.") return a_tuple # Main program starts here - DO NOT change it a_list = input("Enter elements of list separated by commas: ").strip().split(',') a_tuple = list_to_tuple(a_list) print(a_tuple)
true
65a05bd5aaf384cd32c9d095fdb9e9c0aca91773
lakshmick96/python-practice-book
/chapter_5/problem1.py
433
4.375
4
#Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. class reverse_iter: def __init__(self, n): self.i = 0 self.n = n[::-1] def __iter__(self): return self def next(self): if self.i < len(self.n): i = self.i self.i += 1 return self.n[i] else: raise StopIteration() ''' hello '''
false
cbbd594cd0c489d23f745a6e04ecf1c75a826a0e
TSG405/Miscellaneous-Programs
/Python/Binary Tree.py
2,283
4.1875
4
''' Create a Binary Tree, and traverse through it's nodes (inorder, preorder, postorder) and print the tree accordingly ! ''' class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Inserting a Node def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # Printing the B.Tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() # Inorder traversal------------------------------------ # Left -> Root -> Right def inorderTraversal(self, root): res = [] if root: res = self.inorderTraversal(root.left) res.append(root.data) res = res + self.inorderTraversal(root.right) return res # Preorder traversal----------------------------------- # Root -> Left ->Right def PreorderTraversal(self, root): res = [] if root: res.append(root.data) res = res + self.PreorderTraversal(root.left) res = res + self.PreorderTraversal(root.right) return res # Postorder traversal---------------------------------- # Left ->Right -> Root def PostorderTraversal(self, root): res = [] if root: res = self.PostorderTraversal(root.left) res = res + self.PostorderTraversal(root.right) res.append(root.data) return res # Driver Program-------------------------------------- root = Node(27) root.insert(14) root.insert(35) root.insert(10) root.insert(19) root.insert(31) root.insert(42) print(root.PostorderTraversal(root)) print(root.PreorderTraversal(root)) print(root.inorderTraversal(root)) ''' OUTPUT: [10, 19, 14, 31, 42, 35, 27] [27, 14, 10, 19, 35, 31, 42] [10, 14, 19, 27, 31, 35, 42] > '''
true
3fa7a37e0f696335242d11d8e3d5b86cc9e383a3
LucasMayer02/UFCG_Exercicios
/atividades/dna/questao.py
374
4.15625
4
# 2021-03-22, lucas.mayer.almeida@ccc.ufcg.edu.br # Define a menor sequência de DNA dna1 = input() dna2 = input() dna3 = input() if len(dna1) <= len(dna2) and len(dna1) <= len(dna3) : print(f"{dna1} {len(dna1)}") elif len(dna2) <= len(dna1) and len(dna2) <= len(dna3) : print(f"{dna2} {len(dna2)}") elif len(dna3) <= len(dna1) and len(dna3) <= len(dna2) : print(f"{dna3} {len(dna3)}")
false
ff6d491ab138667d0e0c4db8c42aa4f5b33847ce
liaison/LeetCode
/python/425_word_squares.py
2,964
4.125
4
''' Given a set of words (without duplicates), find all word squares you can build from them. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. b a l l a r e a l e a d l a d y Note: - There are at least 1 and at most 1000 words. - All words will have the exact same length. - Word length is at least 1 and at most 5. - Each word contains only lowercase English alphabet a-z. Example 1: Input: ["area","lead","wall","lady","ball"] Output: [ [ "wall", "area", "lead", "lady" ], [ "ball", "area", "lead", "lady" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). Example 2: Input: ["abat","baba","atan","atal"] Output: [ [ "baba", "abat", "baba", "atan" ], [ "baba", "abat", "baba", "atal" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). ''' class Solution: def wordSquares(self, words: List[str]) -> List[List[str]]: trie = {} SIZE = len(words[0]) WORD_KEY = '$' for word in words: node = trie for letter in word: node = node.setdefault(letter, {}) node[WORD_KEY] = word ret = [] word_square = [''] * SIZE def backtracking(keyword, row:int, col:int, node): if row == SIZE: ret.append(word_square[:]) return while col < row: letter = word_square[col][row] col += 1 node = node.get(letter, None) if not node: return # while col < SIZE-1 and len(node) == 1: # node = next(iter(node.values())) # col += 1 for letter in node: nextNode = node[letter] newRow, newCol = row + (col + 1) // SIZE, (col + 1) % SIZE # end of line if newCol == 0: newWord = nextNode[WORD_KEY] word_square[row] = newWord nextNode = trie backtracking(keyword, newRow, newCol, nextNode) if newCol == 0: word_square[row] = '' for word in words: if not all([l in trie for l in word]): continue #word_square = [''] * SIZE word_square[0] = word backtracking(word, 1, 0, trie) return ret
true
a114246a34ec769d4250152ec344af9b623b2db5
dodecatheon/UW-Python
/fall2011/week08/decorator.py
1,588
4.21875
4
""" Demonstrate decorators """ # define a function *in a function* and return that function def addn(n): def adder(i): return i + n return adder add2 = addn(2) print add2(1) add3 = addn(3) print add3(1) # pass a function as an argument, use that to define the function you return def odd(i): return i % 2 def even(i): return not odd(i) def sieve(f): def siever(s): return [ x for x in s if f(x)] return siever s = [1,2,3,4] oddsieve = sieve(odd) print oddsieve(s) evensieve = sieve(even) print evensieve(s) # The decorator operator @ abbreviates the preceding pattern # @f; def g means g = f(g) @sieve def osieve(i): return i % 2 print osieve(s) # You can also use a class as a decorator # because classes and objects are callable (via __init__ and __call__) class memoize: """ memoize decorator from avinash.vora http://avinashv.net/2008/04/python-decorators-syntactic-sugar/ """ def __init__(self, function): # runs when memoize class is called self.function = function self.memoized = {} def __call__(self, *args): # runs when memoize instance is called try: return self.memoized[args] except KeyError: self.memoized[args] = self.function(*args) return self.memoized[args] @memoize # same effect as sum2x = memoize(sum2x) def sum2x(n): return sum(2*i for i in xrange(n)) #takes time when n > 10 million # sum2x(100000000) # first time takes > 20 sec, second time very fast
true
a91edc00d15ed9d7bb1e8c647a815d1ba2dbed7a
dodecatheon/UW-Python
/fall2011/week07/bag.py
1,805
4.1875
4
#!/usr/bin/env python """ Write a module bag.py that defines a class named bag. A bag (also called a multiset) is a collection without order (like a set) but with repetition (unlike a set) --- an element can appear one or more times in a bag. Implement bag as a subclass of dictionary where each bag element is a key and its value is an integer that represents its multiplicity (the number of repetitions). For example in b1 = bag({'a':2, 'b':3}), b1 is a bag where 'a' occurs twice (has multiplicity 2) and 'b' occurs three times. Provide a bag union operator + (plus sign) that operates on two bags and returns a third bag, their union. The bag union contains all of the elements of both bags, with their multiplicities added. For example, after b2 = bag({'b':1, 'c':2}), then b1 + b2 == bag({'a':2, 'b':4', 'c':2}) """ class bag(dict): def __repr__(self): return 'bag(%s)' % super(bag,self).__repr__() def __init__(self,data): try: # dict or bag input for k, v in data.iteritems(): self[k] = self.get(k,0) + v except: # basic iterable input, such as list for k in data: self[k] = self.get(k,0) + 1 def __add__(self,other): "This works for adding a list, dict or bag" b = bag(self) for k, v in bag(other).iteritems(): b[k] = b.get(k,0) + v return b if __name__ == '__main__': b1 = bag({'a':2, 'b':3}) b2 = bag({'b':1, 'c':2}) print "Should be b1 + b2 == bag({'a':2, 'b':4', 'c':2})" print b1 + b2 b3 = bag(['b', 'a', 'b', 'a', 'b']) b4 = bag(['c', 'b', 'c']) print "b3 = bag(['b', 'a', 'b', 'a', 'b']) =", b3 print "b4 = bag(['c', 'b', 'c']) =", b4 print "b3 + b4 =", b3 + b4
true
8544be594685311112b0c3c642a6b83431e908d9
vasanwalker/python-
/beginner level/notalpha.py
250
4.25
4
while True: print("Enter '1' for exit.") chy = input("Enter any character: ") if chy == '1': break else: if((chy>='a' and ch<='z') or (chy>='A' and chy<='Z')): print(chy, "is an alphabet.\n") else: print(chy, "is not an alphabet.\n")
false
0fe4e774c9b775be276792a41b4e90c0e9237060
IuliiaKonovalova/python_guess_the_number
/main.py
1,504
4.46875
4
import random def guess(x_number): """ Chooses the random number, checks whether the guess is correct Provides comments to the user which guide them through the choices """ random_number = random.randint(1, x_number) guess = 0 while guess != random_number: guess = int(input(f'Guess a number between 1 and {x_number}: ')) if guess < random_number: if guess in range(random_number - 2, random_number): print('Guess again. A bit low!') elif guess in range (random_number - 3, random_number): print('Guess again. Low!') else: print("Guess again. Too low!") elif guess > random_number: if guess in range(random_number + 1, random_number + 3): print('Guess again! A bit high!') elif guess in range(random_number + 3, random_number + 10): print('Guess again. High!') else: print('Guess again. Too high!') print(f'You got it. Random number was {random_number}') guess(100) def computer_guess(x_for_computer): """ Provides guesses according to the user guidence """ low = 1 high = x_for_computer feedback = '' while feedback != 'c': if low != high: guess = random.randint(low, high) else: guess = low feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)??').lower() if feedback == 'h': high = guess - 1 elif feedback == 'l': low = guess + 1 print(f'Computer guessed correctly, {guess}') # computer_guess(100)
true
ff17585992c582bb291fb976053c786f81b2c5f1
tataurova/lessons-gb-python
/lesson_7/or_true.py
601
4.25
4
# добавление элемента в список # классический способ def add_to_list(input_list=None): if input_list is None: input_list = [] input_list.append(2) return input_list result = add_to_list([0, 1]) print(result) result = add_to_list() print(result) # через or def add_to_list(input_list=None): # используем свойство вместо условия input_list = input_list or [] input_list.append(2) return input_list result = add_to_list([0, 1]) print(result) result = add_to_list() print(result)
false
b9f9a4d114346e84a49ed81e41a374a8cde2a48c
tataurova/lessons-gb-python
/lesson_7/copy_list.py
634
4.34375
4
import copy a = [1, 2, 3] # копия с помощью среза b = a[:] b[1] = 200 print(a) # копия методом copy b = a.copy() b[1] = 200 print(a) # способы не будут работать, если есть вложенные списки a = [1, 2, [1, 2]] b = a[:] b[2][1] = 200 # список a меняется, т к копирование не учитывает вложенность списков print(a) b = a.copy() b[2][1] = 400 print(a) # копирование модулем copy a = [1, 2, [1, 2]] b = copy.deepcopy(a) b[2][1] = 999 print(a) # список не меняется
false
90589f5adbcc22472a88480dbf26d820dd45c559
adlilyna/my-first-python
/basic.py
998
4.34375
4
# Get the player's name with input and store it in the name variable # Greet the player using string concatenation # Print out some steps for player to choose from, for example: # Next steps: 1) Look around 2) Chop down tree 3) Jump # Use an if statement to decide the next steps to print. For example, if they picked 1: # You've spotted a suit of armor! 1) Put it on 2) Ignore it # Do this inside a loop until the user is done with the game name = input('Enter your name: ') print ('Hello and welcome, ' + name) print ('You need to choose steps!') print ('1) Look around') print ('2) Chop down tree') print ('3) Jump') choose_steps = int(input('Choose your steps: ')) if choose_steps == 1: print ('You have spotted a house!') print ('What are you gonna do now?') house = int(input('1) Go into the house 2) Ignore // ')) if house == 1: print ('Lets go!') else: print ('Okay what are you gonna do now?') else: print ('Okay, lets chop down the tree!')
true
1967172f045d9a660d9023d2303a2e1b19b95744
us19861229c/Meu-aprendizado-Python
/CeV - Gustavo Guanabara/exerc072.py
352
4.21875
4
#tupla de zero a vinte (por extenso), usuario escolhe um numero e ele será escrito #ppor extenso numero = ("zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez") cont="" while cont not in range(0,10+1): cont = int(input("Digite um numero entre 0 e 10: ")) print("o numero digitado foi ", numero[cont])
false
0f1591a7b3122faf7e2f5f215b949cac6e2f9c4a
AbooSalmaan/Projects
/Text/fizzbuzz.py
526
4.40625
4
""" This program will print the numbers from 1 to 100. For multiples of three, the program will print "Fizz" instead of the number and "Buzz" if the number is multiples of five. For multiples of both three and five, the program will print "FizzBuzz" """ if __name__ == '__main__': for i in range(1, 101): if(i % 3 == 0): if(i % 5 == 0): print "FizzBuzz" else: print "Fizz" elif(i % 5 == 0): print "Buzz" else: print i
true
0ab1b68f17bd6f88cfae7dcd5e19756b9d34f58f
sadatusa/PCC
/8_11.py
698
4.3125
4
# 8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the # function make_great() with a copy of the list of magicians’ names. Because the # original list will be unchanged, return the new list and store it in a separate list. # Call show_magicians() with each list to show that you have one list of the original # names and one list with the Great added to each magician’s name. magicians_list=['kareem','jhons','michale'] great_magicians=[] def make_great(magicians,greatmagician): for x in range (0,len(magicians)): greatmagician.append('The great '+magicians[x]) make_great(magicians_list,great_magicians) print(magicians_list) print(great_magicians)
true
090f6ccab8656c67e93754069712f89fdad38a5d
sadatusa/PCC
/6_9.py
755
4.59375
5
# 6-9. Favorite Places: Make a dictionary called favorite_places. Think of three # names to use as keys in the dictionary, and store one to three favorite places # for each person. To make this exercise a bit more interesting, ask some friends # to name a few of their favorite places. Loop through the dictionary, and print # each person’s name and their favorite places. aslam=['Karachi','Lahore','Islamabad'] jameel=['Newyork','Washington','Newjersey'] kamal=['Jeddah','Riyadh','Dammam'] favorite_places={'Aslam':aslam,'Jameel':jameel,'Kamal':kamal} for name,favoriteplaces in favorite_places.items(): print(name+' '+'favorite places are ',end='') for favoriteplace in favoriteplaces: print(favoriteplace+', ',end='') print('')
true
1cfcaf1b10e9b39a3ae6ecf420cde59afeaa01c2
sadatusa/PCC
/9_3.py
1,088
4.28125
4
# 9-3. Users: Make a class called User. Create two attributes called first_name # and last_name, and then create several other attributes that are typically stored # in a user profile. Make a method called describe_user() that prints a summary # of the user’s information. Make another method called greet_user() that prints # a personalized greeting to the user. # Create several instances representing different users, and call both methods # for each user. class User(): def __init__(self, first_name, last_name,age,hight,color): self.first_name = first_name self.last_name = last_name self.age=age self.hight=hight self.color=color def describe_user(self): print(self.first_name, self.last_name,self.age,self.hight,self.color) def greet_user(self): print('Welcome '+self.first_name) user_info = User('Sadat', 'Hussain',44,5.8,'white') user2_info=User('Saleem', 'Khan',40,6.2,'pink') print(user_info.describe_user()) print(user_info.greet_user()) print(user2_info.describe_user()) print(user2_info.greet_user())
true