blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
f38d4534d6a5fdb6565f9124eefc8e7cf00e04e5
satyamachani/python-experiments
/guess game.py
896
4.21875
4
import random print("you are going to play guess game with computer") print("rules are as follows") print("computer guess and you too") print("if ur guess equals computer guess") print("you wins") print("maximum guess allowed are 3") print("we are strating game......") print("ready to play with satya's computer") num = 3 print(num,"guesses are left") print("Guess the number between 1 to 10") while True: guess = input() computer = random.randint(1,10) print("you guessed",guess) print("computer guessed",computer) print() if 0<int(guess)<11 and (int(guess) == computer): print("hurray! you wins") break elif num == 1: print("No guesses left\n you loose the game") else: print("sorry guess again") num = num-1 print(num,"guesses left") print("guess the number between 1 to 10")
true
503eb1fb3f378307e6ff0d9a9ccbd191e592d9b3
hugolribeiro/Python3_curso_em_video
/World3/exercise081.py
811
4.21875
4
# Exercise 081: Extracting data from a lista # Make a program that reads several numbers and put them into a list. After that, show: # A) How many numbers were inputted # B) The numbers list, in descending order # C) If the value 5 is in the list numbers_list = [] want_continue = 'Y' while want_continue != 'N': number = int(input('Input here a number: ')) numbers_list.append(number) print(f'The number {number} was add into the list') want_continue = input('Do you want to continue?\n' '[N] to stop the program\n').upper() print(f'You inputted {len(numbers_list)} numbers') print(f'The list in descending order: {sorted(numbers_list, reverse=True)}') if 5 in numbers_list: print('The number 5 is in the list') else: print('The number 5 ins\'t in the list')
true
edaa06ad2bdc494c8011777a3aacf69f5ba2764a
hugolribeiro/Python3_curso_em_video
/World3/exercise096.py
467
4.40625
4
# Objective: Make a program that have a function called Area(). # Receive the dimensions of a rectangular land (width and length) and show its area. # Programmer: Hugo Leça Ribeiro def area(width, length): amount_area = width * length print(f'The area of this land is equal than: {amount_area}m²') width = float(input("Input here the width of this land (in meters): ")) length = float(input("Input here the length of this land (in meters): ")) area(width, length)
true
1f25f848fb152d60b5af77405534750d4c83694c
hugolribeiro/Python3_curso_em_video
/World2/exercise060.py
408
4.3125
4
# Exercise 060: Factorial calculation # Make a program that read any number and show its factorial # Example: 5! = 5 X 4 X 3 X 2 X 1 = 120 number = int(input('Input here a number: ')) factorial = 1 print(f'{number}! = ', end='') for multiply in range(number, 0, -1): factorial = multiply * factorial print(f'{multiply}', end='') print(' X ' if multiply > 1 else ' = ', end='') print(factorial)
true
45a18da87d6d6a4b6d6dc201dbce51a6b44dab87
hugolribeiro/Python3_curso_em_video
/World2/exercise071.py
857
4.21875
4
# Exercise 071: ATM simulator # Make a program that simulates the operation of an ATM. # At the begin, ask to the user what value will be withdraw (an integer number) # and the program will informs how many banknotes of each value will be give. # Observation: Consider that the banking box has these banknotes: R$ 50, R$ 20, R$ 10, R$ 5, R$ 2. # The minimum value to withdraw is R$ 5 c50 = 0 c20 =0 c10 = 0 c5 = 0 c2 = 0 value = 0 while value < 5: value = int(input('Input here value to withdraw: ')) while value % 5 != 0: value -= 2 c2 += 1 c50 = value // 50 value -= c50 * 50 c20 = value // 20 value -= c20 * 20 c10 = value // 10 value -= c10 * 10 c5 = value // 5 value -= c5 * 5 print(f'{c50} banknotes of 50\n' f'{c20} banknotes of 20\n' f'{c10} banknotes of 10\n' f'{c5} banknotes of 5\n' f'{c2} banknotes of 2')
true
63f0901cc32517c7090232184e6179db607d1f87
hugolribeiro/Python3_curso_em_video
/World1/exercise013.py
265
4.125
4
# Exercise 013: Income readjustment # Build an algorithm that read the employee's income and show his new income, with 15% increase. income = float(input(f"Input here the employee's income: ")) new_income = income * 1.15 print(f'The new income is: {new_income}')
true
3127270d8291d1794b18cc66b47a0d547ba9b353
hugolribeiro/Python3_curso_em_video
/World2/exercise052.py
572
4.125
4
# Exercise 052: Prime numbers # Make a program that read an integer number and tell if it is or not a prime number. def verify_prime(num): if num < 2 or (num % 2 == 0 and num != 2): return False else: square_root = int(num ** 0.5) for divisor in range(square_root, 2, -1): if num % divisor == 0: return False return True number = int(input('Input here a number: ')) if verify_prime(number): print(f'The number {number} is a prime number') else: print(f'The number {number} isn\'t a prime number')
true
8fb71045715791f1d73d8394de33b5af4400a102
hugolribeiro/Python3_curso_em_video
/World2/exercise043.py
740
4.625
5
# Exercise 043: body mass index (BMI) # Make a program that read the weight and the height of a person. # Calculate his BMI and show your status, according with the table below: # - Up to 18.5 (not include): Under weight # - Between 18.5 and 25: Ideal weight # - Between 25 and 30: Overweight # - Between 30 and 40: Obesity # - Above than 40: Morbid obesity # Formula: BMI = kg / m² weight = float(input('Input here the weight in kg: ')) height = float(input('Input here the height in meter: ')) bmi = weight / (height ** 2) if bmi < 18.5: print('Under weight') elif 18.5 <= bmi < 25: print('Ideal weight') elif 25 <= bmi < 30: print('Overweight') elif 30 <= bmi < 40: print('Obesity') else: print('Morbid obesity')
true
c99de9678d8cc3cd067ab93f3480a5c75f850bee
hugolribeiro/Python3_curso_em_video
/World3/exercise086.py
510
4.4375
4
# Exercise 086: Matrix in Python # Make a program that create a 3x3 matrix and fill it with inputted values. # At the end, show the matrix with the correct format matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for line in range(0, 3): for column in range(0, 3): matrix[line][column] = int(input(f'Input here a number to line {line} and column {column}: ')) for line in range(0, 3): for column in range(0, 3): print(f'[{matrix[line][column]:^5}]', end='') print()
true
5cad30469285efa036089dd993eaa595bb0ecdf4
as3379/Python_programming
/String_manipulation/reverse_alternate_words.py
629
4.3125
4
def reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique n = len(words) for i in range (0, n): if i%2 !=0: words[i] = words[i][::-1] # Joining the new list of words # to for a new Sentence newSentence = " ".join(words) return newSentence # Driver's Code Sentence = "GeeksforGeeks is good to learn with you" # Calling the reverseWordSentence # Function to get the newSentence print(reverseWordSentence(Sentence))
true
8e37ac3431bffcc74f9c66f16938409ef2277561
as3379/Python_programming
/String_manipulation/middle_char.py
377
4.25
4
"""Print middle character of a string. If middle value has even then print 2 characters Eg: Amazon -->print az """ def middle_char(S): S = S.replace(" ", "") # mid = "" n = len(S) if n%2 ==0: mid = S[n//2 -1]+ S[n//2] else: mid = S[n//2 -1] print(mid) middle_char("Amazon") middle_char("Amazonprime") middle_char("Amazon prime")
true
0d8d1c23ee883c8ecb465b1ea25b9b2bf60bf01f
blueicy/Python-achieve
/00 pylec/01 StartPython/hw_5_2.py
358
4.1875
4
numscore = -1 score = input("Score:") try: numscore = float(score) except : "Input is not a number" if numscore > 1.0 : print("Score is out of range") elif numscore >= 0.9: print("A") elif numscore >= 0.8: print("B") elif numscore >= 0.7: print("C") elif numscore >= 0.6: print("D") elif numscore >= 0.0: print("F") else: print("Not vaild")
true
8954c50cc3a94b3966da8d67efb3359ad57683cc
RomanLopatin/Python
/HW_5/5_1.py
542
4.25
4
"""" Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка. """ with open("my_file_.txt", "w") as my_file_obj: while True: new_str = input("Введите новую строку: ") if new_str != "": my_file_obj.write(new_str+"\n") else: break
false
cc8429fb4b812f7af16b4afd4be2a072be9957d5
RomanLopatin/Python
/HW_3/HW_3.6.py
1,571
4.25
4
""" 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). """ def int_func(input_str): return input_str.capitalize() while True: our_list = input("Введите последовательность слово из маленьких латинских букв, разделяя слова пробелами: ").split() our_str = "".join(our_list) # склеили список в строку без пробелов для проверки символов if our_str.islower() and our_str.isalpha() and our_str.isascii(): # это нижний регистр + это буквы + это латиница break else: print("Ошибка ввода!") for i, el in enumerate(our_list): our_list[i] = int_func(el) print(" ".join(our_list))
false
489259c1f202adff5817dbedde48efeff65f2258
scienceiscool/Permutations
/permutation.py
2,248
4.15625
4
# CS223P - Python Programming # Author Name: Kathy Saad # Project Title: Assignment 6 - Generators and Iterators - Permutations # Project Status: Working # External Resources: # Class notes # https://www.python.org/ class PermutationIterator: def __init__(self, L): self.counter = 0 self.length_for_counter = len(L) - 1 self.true_length = len(L) self.l = L def __iter__(self): return self def __next__(self): for index, element in enumerate(self.l): theRest = self.l[:index] + self.l[index + 1:] print([element] + theRest) print([element] + theRest[::-1]) raise StopIteration() def main(): # NOTE TO SELF: REMOVE TEST LIST CODE BEFORE SUBMITTING numList1 = [1, 2, 3, 4, 5] # keep #numList2 = [1, 2, 3, 4] #numList3 = [1, 2, 3] #numList4 = [1, 2] #numList5 = [1] letterList1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # keep letterList2 = ['b', 'c', 'a'] # keep #letterList3 = ['k', 'y'] #letterList4 = ['x'] print("Permutations of list [1, 2, 3, 4, 5]:") for permutation in PermutationIterator(numList1): print(permutation) #print() #print("Permutations of list [1, 2, 3, 4]:") #for permutation in PermutationIterator(numList2): # print(permutation) #print() #print("Permutations of list [1, 2, 3]:") #for permutation in PermutationIterator(numList3): # print(permutation) #print() #print("Permutations of list [1, 2]:") #for permutation in PermutationIterator(numList4): # print(permutation) #print() #print("Permutations of list [1]:") #for permutation in PermutationIterator(numList5): # print(permutation) print() print("Permutations of list ['a', 'b', 'c', 'd', 'e', 'f', 'g']:") for permutation in PermutationIterator(letterList1): print(permutation) print() print("Permutations of list ['b', 'c', 'a']:") for permutation in PermutationIterator(letterList2): print(permutation) #print() #print("Permutations of list ['k', 'y']:") #for permutation in PermutationIterator(letterList3): # print(permutation) #print() #print("Permutations of list ['x']:") #for permutation in PermutationIterator(letterList4): # print(permutation) if __name__ == "__main__": main()
true
420505fb8d7e2230e8554772d8e60c2efbb83017
kunalprompt/numpy
/numpyArray.py
735
4.4375
4
''' Hello World! http://kunalprompt.github.io Introduction to NumPy Objects ''' print __doc__ from numpy import * lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print "This a Python List of Lists - \n", lst print "Converting this to NumPy Object..." # creating a numpy object (ie. a multidimensional array) num_obj = array(lst) print num_obj print "Type of Numpy Object - "+str(type(num_obj)) print "Number of dimensions or axes this object has are - "+str(num_obj.ndim) print "Data Type of this object - "+str(num_obj.dtype) x=2;y=1 print "Value of element at %d, %d of this numpy object is -"%(x, y), num_obj[x, y] # note under the hood num_obj[x, y] is converted to num_obj.getitem((x,y)) # you can also refernce it as num_obj[(x,y)]
true
37c1c60959104197272a204209bcf432165f2474
mumudexiaomuwu/Python24
/00Python/day11/basic03.py
2,313
4.15625
4
""" Python中的一场处理try-except 1- 多个异常python可以写在同一行,括号包括多个异常,逗号隔开 2- 获取异常的信息描述通过 as e的方式 3- 发生异常执行except,不发生异常执行else,两者对立 """ try: file = open("Test.txt", "r") except (FileNotFoundError, NameError) as e: print("捕获到了异常,异常信息%s, 准备补救工作..." % e) # file = open("Test.txt", "w") except Exception as e: print("捕获到了超级异常") else: print("如果try中的代码不发生异常执行else") finally: print("Finally有没有异常都会执行的") """ 异常嵌套中的传递, 内部的异常搞不定就会传到外边一层去处理 """ try: try: file = open("Test.txt", "r") finally: print("这里没有处理内部的异常") except: print("外部一层捕获到了内部的异常") """ 函数中异常的传递,内部的异常向外传递 """ def fun1(): print(10 / 0) def fun2(): fun1() def fun3(): try: fun2() except: print("在最外层的函数中捕获到了异常") fun3() """ 抛出自定义的异常,需要继承Exception, str方法显示的是信息的描述 1- raise AgeError(age) 关键字进行自定义对象的抛出 2- raise关键字的两个作用a:抛出自定义异常 b:将本异常不处理,进行抛出 """ class AgeError(Exception): # 使用init的方法主要是要age的值, 此方法非必需 def __init__(self, age): self.age = age def __str__(self): return "你输入的年龄有误:age=%d" % self.age class Person(object): def __init__(self, name, age): self.name = name if age <= 0 or age >= 150: raise AgeError(222) else: self.age = age p1 = Person("小明", 222) """ 异常处理中的**不处理,抛出异常给下一层** """ class Test(object): def __init__(self, switch): self.switch = switch def calculate(self, a, b): try: return a / b except Exception as e: if self.switch: print("设置为自动捕获异常,异常如下:%s" % e) else: raise Test(False).calculate(8, 0)
false
10c4c93bfb93b007d3399f4ab25a6911c9a36d71
mumudexiaomuwu/Python24
/00Python/day09/basic04.py
1,825
4.46875
4
""" python中的类和对象, 所有的类的祖先都是object和java是一样的 1- 前两种叫做经典类存在python 2.x中, 最后一种叫做新式类 2- python 2中类并没有父类,自己就是父类 3- 而python3中得class Person(object)存在父类,可以使用根类的方法 """ class Person: pass class Person(): pass class Person(object): pass """ 1- 实例方法的第一个形参是self自身,表示调用该方法的对象,谁调用谁就是self 2- 给一个**对象**添加属性,并不是添加到类中的,有点奇怪 3- 类的方法中,通过self获取对象的属性self.name 4- 重写__init__() 用来给属性添加默认值,避免多个对象对共同的属性name赋值 5- python中不能定义多个构造方法,只能定义一个,不然会报错 6- 因为python对参数的类型没有限制,构造器中参数一般为字典{}用来处理不同数量参数的问题 """ class Hero(object): # python提供的两个下划线的魔法方法,创建该类对象的时候自动调用,类似于构造方法 # def __init__(self): # self.name = "旺财" def __init__(self, age, my_name = "默认的名字"): # 构造方法的参数也和kotlin一样可以默认参数 self.name = my_name self.age = age def move(self): print(id(self)) print("英雄会行走...") def print_info(self): print(self.name) print(self.age) print(self.hp) hero01 = Hero(22) print(id(hero01)) # 打印的id和move方法中的self的id是同一个地址 hero01.move() hero01.name = "英雄名字01" hero01.age = 22 hero01.hp = 4000 hero01.print_info() hero02 = Hero(22) print(hero02.name) hero03 = Hero(18) print(hero03.name) print(hero03.age)
false
1edd03dbe49721b23b8b90bc4e8eb66d4970c666
mumudexiaomuwu/Python24
/00Python/day11/basic01.py
2,716
4.5
4
""" 如果在类的外面取值和修改私有属性的值,需要自己定义get/set方法 """ class Person(object): def __init__(self): self.name = "老王" self.__age = 20 def get_age(self): return self.__age def set_age(self, age): self.__age = age p = Person() print(p.name) p.name = "王五" print(p.name) print(p.get_age()) p.set_age(28) print(p.get_age()) """ 多态,因为python是弱引用类型,并不关注参数的类型,所以需要自己打出obj.eat()的方法 """ """ 1- 实例属性就是对象属性, 和类属性不是一回事 2- 对象创建的属性叫做实例属性, 类中的属性叫做类属性 3- 如果想使用类属性,直接大写Student.num即可, 或者s1.num 4- 但是修改类属性的值只能通过Student.num 5- 类方法需要添加修饰器@classmethod, 每个对象都自动拥有的方法,只有一份的属性和方法 """ class Student(object): # 类属性,每个创建的对象都有这个num的属性,不会为类属性单独的开辟多份内存 # 多个对象共享一份类属性,修改的话,每个对象的num都会更改,全变了 # 如果想在类的外面修改类私有属性,使用类方法 num = 0 __sex = "Male" @classmethod def get_sex(cls): return cls.__sex @classmethod def set_sex(cls, sex): cls.__sex = sex def __init__(self, name, age, country = "中国"): self.name = name self.age = age self.country = country s1 = Student("小明", 22) s2 = Student("小红", 28) s1.city = "石家庄" print(s1.city) # 实例属性 print(Student.num) # 类属性 print(s1.num) Student.num = 200 print(s1.num) print(s2.num) print(Student.get_sex()) Student.set_sex("Female") print(Student.get_sex()) print(s1.get_sex()) s1.set_sex("Male") print(Student.get_sex()) """ 静态方法,并没有self或者cls 类中存在的方法只有三个, 类方法, 对象方法, 静态方法 1- 如果在类的内部想使用self --> 对象方法 2- 如果在类的内部想使用cls --> 类方法 3- 如果在类的内部不使用self和cls --> 静态方法 """ class Teacher(object): __country = "中国" def __init__(self): self.__age = 10 # 类方法-用来读写类属性的 @classmethod def get_country(cls): return cls.__country # 对象方法 def get_age(self): return self.__age # 静态方法- Teacher.say_hello()或者t1.say_hello()都可以访问 @staticmethod def say_hello(): print("Hello Python.") Teacher.say_hello() t1 = Teacher t1.say_hello()
false
251547ce931257c34f2f185c503ff3bf6e4a8c2f
mumudexiaomuwu/Python24
/00Python/day04/basic03.py
1,236
4.375
4
""" help(str) """ help(str) # 查看str数据类的所有方法和说明 help(str.count) # 查看str数据类的某个具体方法,方法说明文档 """ list列表**有序**数据结构,python中的list可以装任何类型的元素在同一个list中 如果遍历list的时候想要获取index,好像只能使用while小于len的方法 """ a_list = [1, 3.14, "hello world", True, [1,2,3] ] b_list = [] c_list = list() print(len(c_list)) # 返回0表示这个list是一个空的list for temp in a_list: print(temp) i = 0 while i < len(a_list): print(a_list[i]) i += 1 """ list添加元素是在原list进行修改的,列表是可变的,和str的操作不同,str是不可变的 list.append -> 追加 list.extend(obj) -> 继承一个可迭代的对象,将obj中的每一个元素拿出来进行追加append list.insert(index, obj) -> 在index的位置上插入一个obj, 如果index越界,不会报错,直接在末尾append """ d_list = [1, 2, 3] d_list.append("4") d_list.extend("abcd") # 字符串本身就是一个可迭代的对象 -> [1, 2, 3, '4', 'a', 'b', 'c', 'd'] d_list.insert(1,"abcd") # [1, 'abcd', 2, 3, '4', 'a', 'b', 'c', 'd'] print(d_list) """ """
false
49694169a4ab556bcd9072ff168c8dd894008455
ffnbh777/Udacity-Adventure-Game
/udacity_game.py
2,680
4.125
4
import time import random import sys def print_pause(message_to_print): print(message_to_print) time.sleep(2) def intro(): print_pause("You find yourself in a dark dungeon.") print_pause("In front of you are two passageways.") print_pause("Which way do you want to go right or left?") def play_again(): user_input = input("Would you like to play again? (y/n)").lower() if user_input == 'y': print_pause("Excellent! Restarting the game ...") choice() elif user_input == 'n': print_pause("Thanks for playing... Goodbye, until we meet again!") sys.exit() else: play_again() def passageways(): monsters = ["Dragon", "Goliath", "Goblin", "Grendel"] print_pause(f"Standing in the cave is {random.choice(monsters)}") fight_or_run = input("Would you like to (1) fight or (2) run away?") if fight_or_run == '1': print_pause("As the Monster moves to attack it saw your sword.") print_pause( "You hold Sword in your hand ready for the attack.") print_pause("Monster saw your Sword and runs away.") print_pause("You have taken care of the Monster. You WON!") play_again() elif fight_or_run == '2': print_pause("You run back into the dungeon.") choice() else: error_input() def passageways2(): print_pause("You have found the treasure!") print_pause("You walk back out to the dungeon.") monsters = ["Dragon", "Goliath", "Goblin", "Grendel"] print_pause(f"Standing in the cave is {random.choice(monsters)}") print_pause("Monster tries to stop you.") print_pause("You outrun the Monster.") print_pause("You took the Monster's treasure") print_pause("You WON!") play_again() choice() def choice(): intro() print_pause("Enter R to go Right.") print_pause("Enter L to go Left.") user_choice = input("What would you like to do?(R/L)").upper() if user_choice == 'R': passageways() elif user_choice == 'L': passageways2() else: error_input() def error_input(): user_choice = input("(Please enter R or L)\n").upper() while True: if user_choice == 'R': choice() elif user_choice == 'L': choice() else: user_choice = input("(Please enter R or L)\n").upper() def error_answer(): user_input = input("Please enter y or n:").lower() while True: while user_input != 'y' or user_input != 'n': user_input = input("Please enter y or n:").lower() def game(): choice() game()
true
30d5b462c8dda72993475a485a3583f4c45fac5f
tkj5008/Luminar_Python_Programs
/Object_Oriented_Programming/Demo5.py
929
4.15625
4
#instance variable- relatedtomethods using self #Static variable related to class # class Student: # def setvalue(self,name,rollno,age,standard): # self.name=name # self.rollno=rollno # self.age=age # self.standard=standard # def printvalue(self): # print("Name",self.name) # print("RollNo.",self.rollno) # print("Age",self.age) # print("Standard",self.standard) # st=Student() # st.setvalue("Thomas",12,19,"X") # st.printvalue() class Student: school="Luminar" def setvalue(self,name,rollno,age): self.name=name self.rollno=rollno self.age=age def printvalue(self): print("Name",self.name) print("RollNo.",self.rollno) print("Age",self.age) print("School",Student.school) st=Student() st.setvalue("Thomas",12,19) st.printvalue() st1=Student() st.setvalue("TOM",12,19) st.printvalue()
false
fc25cd3651f146956a075bc5c258b6181adbcee8
judebattista/CS355_Homework
/hw02/reverseComplement.py
1,980
4.4375
4
# function to find the reverse complement of a DNA strand # pattern: A string representation of DNA consisting of the chars 'A', 'C, 'G', and 'T' # complements: a dictionary translating a nucleotide to its complement # revComp: The pattern's complement, complete with 5' to 3' reversal # We may need to store complement in pattern in order to comply with the book's instructions # However, this makes for much less readable code, so we'll stick with complement as our return value for now def revComp(pattern, complements): comp = [] for ntide in pattern[len(pattern) - 1 : : -1]: comp.append(complements[ntide]) revComp = ''.join(comp) return revComp def simpleReverseComp(pattern, complements): revComp = '' for ntide in reversed(pattern): revComp += complements[ntide] return revComp def mapReverseComp(pattern, complements): mapComp = list(map(lambda ntide: complements[ntide], reversed(pattern))) revComp = ''.join(mapComp) return revComp # function to print the pattern, its reversed string, and its reversed complement # pattern: A string representation of DNA consisting of the chars 'A', 'C, 'G', and 'T' # complements: a dictionary translating a nucleotide to its complement def printComplementDetails(pattern, complements): print('Source: ' + pattern) print('Rev source: ' + pattern[len(pattern)-1::-1]) print('Complement: ' + revComp(pattern, complements)) print('Simple Comp: ' + simpleReverseComp(pattern, complements)) print('Map Comp: ' + mapReverseComp(pattern, complements)) complements = {'A':'T', 'C':'G', 'G':'C', 'T':'A'} source = "ACCGGGTTTT" printComplementDetails(source, complements) with open('reverseComplement.txt', 'r') as infile: text = infile.readline().strip() #print(len(text)) revComp = mapReverseComp(text, complements) #print(len(revComp)) with open('reverseComplementResults.txt', 'w') as outfile: outfile.write(revComp)
true
b78d2fe914cdf429651d076b7627d2daad9269f7
Timeverse/stanCode-Projects
/SC101_Assignment5/largest_digit.py
1,176
4.59375
5
""" File: largest_digit.py Name: ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_largest_digit(281)) # 8 print(find_largest_digit(6)) # 6 print(find_largest_digit(-111)) # 1 print(find_largest_digit(-9453)) # 9 def find_largest_digit(n): """ :param n: This is the integer that will be process to find largest digit :return: The integer representing the largest digit in n """ divisor_counter = 0 largest_n = 0 num_y = 10 if n < 0: n = abs(n) else: n = n return helper(n, largest_n, divisor_counter, num_y) def helper(n, largest_n, divisor_counter, num_y): divisor_counter += 1 if num_y == 0: return largest_n else: # Choose num_x = int(n / (1 * (10 ** (divisor_counter - 1))) % 10) num_y = int(n / (1 * (10 ** divisor_counter)) % 10) if num_x > largest_n: largest_n = num_x # Explore return helper(n, largest_n, divisor_counter, num_y) if __name__ == '__main__': main()
true
4294c826dfd8f6d9bf071505312717642616f2c6
WorkRock/python_lab
/lab5_10~11.py
2,513
4.3125
4
""" 주제 : 좌표 클래스 정의 작성일 : 17. 10. 30. 작성자 : 201632023 이지훈 """ class Coordinate: """ 좌표를 표현하는 클래스 정의 """ def __init__(self, a, b): """ 좌표를 초기화 :param a: x좌표의 값 :param b: y좌표의 값 """ self.x = a self.y = b def prnt(self): """ 출력하는 메소드 :return: 없음 """ print("좌표<"+str(self.x)+", "+str(self.y)+">") def distance(self,other): """ 좌표의 거리값을 계산해 주는 메소드 :param other: 다른 점의 좌표 :return: self와 다른 점의 거리 """ distance = (self.x-other.x)**2 + (self.y - other.y)**2 return distance**0.5 def __str__(self): """ :return: 문자열 """ return "좌표<"+str(self.x)+", "+str(self.y)+">" c1 = Coordinate(2,3) c2 = Coordinate(3,1) print(c1) print(c2) print("두 좌표의 거리 값 : %.2f"%c1.distance(c2)) print("두 좌표의 거리 값 : %.2f"%c2.distance(c1)) #print("두 좌표의 거리 값 : %.2f"%coordinate.distance(c1,c2)) """ 주제 : 분수 작성일 : 17. 11. 01. 작성자 : 201632023 이지훈 """ class fraction: def __init__(self,numer,denom): """ 분수 초기화 :param numer: 분모 :param denom: 분자 """ self.numer = numer self.denom = denom def prnt(self): """ 출력하는 메소드 :return: 없음 """ def __str__(self): """ :return: 문자열 """ return "출력 : "+str(self.denom)+"/"+str(self.numer) def __add__(self,other): """ 두 분수의 분자를 더해주는 메소드 :param other: 더할 분수 :return: 두 분자의 합 """ a = self.numer * other.denom b = self.denom * other.numer c = self.numer * other.numer s = fraction(c,a+b) return s def __sub__(self, other): """ 두 분수의 분자를 더해주는 메소드 :param other: 더할 분수 :return: 두 분자의 합 """ a = self.numer * other.denom b = self.denom * other.numer c = self.numer * other.numer s = fraction(c, a - b) return s c1 = fraction(4,3) c2 = fraction(7,2) #print(c1.add(c2)) #print(c1.minus(c2)) print(c1+c2) print(c1 - c2)
false
7efcb0b3f5aa5622e90423c07dd92952fc3f5c07
TryHarder01/SantaBot
/code/draft_bot_chatting.py
2,639
4.15625
4
""" The conversation logic to get the information from users """ username = 'NAME_GOES_HERE' introduction = "Hello {}, before we start let me check if we've done this before...".format(username) new= """Ok let's do this. I'm going to ask you for three things you like and three things you don't like. Once everyone has done that, I'll mix and match everyone in the company. You'll get matched to somoene in another department, and someone who isn't matched to you.""" dept_string = """First thing I need from you is your department. I'll give you a list of departments and I need you to respond in the exact format so I can match it.""" dept_options = ['Analytics' 'Marketing', 'PD', 'Merchants', 'Accounting', 'CS', 'Tech', 'Purchasing', 'Creative', 'Inbound', 'Outbound', 'Dropship', 'Leadership', 'UX'].sort() dept_choice = "User_submits" dept_correct = "Ok, {}, got it. Let's get to the good stuff.".format(dept_choice) dept_wrong = "Not on my list. Here's the departments you can choose from. Where should I put you?" #add all departments likes_intro = """In three separate messages, send me three things you like. For instance, I like: \n interpreted languages\n pelicans\n peeled potatoes.\n What's the first?""" like_1_response = "like1" likes_2_ask = "Your second like?" like_2_response = "like2" likes_3_ask = "Your third like?" like_3_response = "like3" likes_intro = """In three seperate messages, send me three things you do *not* like. For instance, I do *not* like: \n baths\n playing board games\n iambic pentameter.\n What's one thing you don't like?""" dislike_1_response = "dislike1" likes_2_ask = "Your second dislike?" dislike_2_response = "dislike2" likes_3_ask = "Your third dislike?" dislike_3_response = "dislike3" review= """Whew. Ok. I think I have it, but check this over for me first. You work in {dept_choice}. You like {like_1_response}, {like_2_response}, and {like_3_response}. And you do *not* like {dislike_1_response},{dislike_2_response}, and {dislike_3_response}. Is that right (yes / no).""" review_response = "yes" while review_response.lower() != 'yes': if review_response.lower() == 'no': fix = "ok, which part do you want to edit..." ##allow ways to get into the choices else: unknown = "I don't understand. Please enter yes or no." """ use this to handle timeouts http://stackoverflow.com/questions/492519/timeout-on-a-function-call """
true
c8518987eda51e8866d77f42c7913e2f64bb9d37
tarakaramaraogottapu/CSD-Excercise01
/01_prefix_words.py
1,029
4.34375
4
import unittest question_01 = """ Given a query string s and a list of all possible words, return all words that have s as a prefix. Example 1: Input: s = “de” words = [“dog”, “deal”, “deer”] Output: [“deal”, “deer”] Explanation: Only deal and deer begin with de. Example 2: Input: s = “b” words = [“banana”, “binary”, “carrot”, “bit”, “boar”] Output: [“banana”, “binary”, “bit”, “boar”] Explanation: All these words start with b, except for “carrot”. """ # Implement the below function and run the program def prefix_words(prefix, words): pass class TestPrefixWords(unittest.TestCase): def test_1(self): self.assertEqual(prefix_words( 'de', ['dog', 'deal', 'deer']), ['deal', 'deer']) def test_2(self): self.assertEqual(prefix_words( 'b', ['banana', 'binary', 'carrot', 'bit', 'boar']), ['banana', 'binary', 'bit', 'boar']) if __name__ == '__main__': unittest.main(verbosity=2)
true
fd071f09d7fb9dfb95e9ce399eadc08dedc05f72
pankajanand18/python-tests
/trees/sachin.py
532
4.1875
4
# Question 1: Given a string of words return all words which have their reverse present in the string as ( (word1 , reverseword1 ) , (word2 ,reverseword2) ) # eg . # Input - # Sachin tendulkar is the best tseb eth nihcaS input='Sachin tendulkar is the best tseb eth nihcaS' hash={} word='' for char in input: print char if char == ' ': if len(word) > 0: word_list= hash.get(len(word),[]) word_list.append(word) hash[len(word)]= word_list word='' else: word = word + char; hash[len(word)].append(word) hash
false
1dcba14f0fb6b1e4ec92993a0ad8980fb1588bdf
Puneeth1996/programiz.com
/Python Introduction/Additon with single statement.py
639
4.34375
4
""" # This program adds two numbers num1 = 1.5 num2 = 6.3 # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # Store input numbers num1 = input('Enter first number: ') num2 = input('Enter second number: ') # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) print('The sum is %f' %(float(input('Enter first number: '))+float(input('Enter second number: ')))) """ print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number: '))))
true
332aaf6ab6405d2fdeef7ba789b4736437531b8c
mateo42/Project-Euler
/problem005.py
587
4.15625
4
# smallest positive number that is evenly divisible by all of the numbers from 1 to 20 def multiplesOf20(): '''Yield increasing multiples of 20''' i = 20 while True: yield i i += 20 def divisibleByAll( number ): ''' Checks that arguments is divisible by 3 - 19 ''' # Skip 1, 2, 20 for i in range(3,20): if ( (number % i) != 0): return False return True def findSmallestDivisibleTo20(): '''Loop over multiples of 20, find first one divisible by all numbers up to 20''' for i in multiplesOf20(): if divisibleByAll( i ): return i print findSmallestDivisibleTo20()
true
50d9761e41347ae4992d85276f54ba0a00662c08
Jazaltron10/Python
/Time_Till_Deadline/Time_Till_Deadline.py
556
4.28125
4
from datetime import datetime user_input = input("enter your goal with a deadline separated by colon\n") input_list = user_input.split(":") goal = input_list[0] deadline = input_list[1] deadline_date = datetime.strptime(deadline,"%d/%m/%Y") # calculate how many days from now till deadline today_date = datetime.today() due_date = deadline_date - today_date # due_date_in_days = due_date.days due_date_in_hours = int(due_date.total_seconds()/ 60 /60) print() print(f"Dear user! Time remaining for your goal: {goal} is {due_date_in_hours} hours")
true
ff235c77c3e02717f0aab5ed57005cb826a076a6
GilmendezCR/Python_Fundamentals
/Procesar Cadena de caracters/Ejercicio_2.py
953
4.21875
4
#Ingresar una oración que pueden tener letras tanto en mayúsculas como minúsculas. #Contar la cantidad de vocales. #Crear un segundo string con toda la oración en minúsculas para que sea más fácil disponer la condición que verifica que es una vocal. contadorVocales = 0 oracion = input("Ingrese una oración: ") oracion.count("a") oracion.count("e") oracion.count("i") oracion.count("o") oracion.count("u") oracion.count("A") oracion.count("E") oracion.count("I") oracion.count("O") oracion.count("U") print("La cantidad de vocales es: ", oracion.count("a") + oracion.count("e") + oracion.count("i") + oracion.count("o") + oracion.count("u") + oracion.count("A") + oracion.count("E") + oracion.count("I") + oracion.count("O") + oracion.count("U")) oracion2 = input("Ingrese una oración: ").lower() print("La cantidad de vocales es: ", oracion2.count("a") + oracion2.count("e") + oracion2.count("i") + oracion2.count("o") + oracion2.count("u"))
false
a894c5576be8236857d3c6040c9187fbbe16fa80
GilmendezCR/Python_Fundamentals
/Funciones/Ejercicio_1.py
617
4.15625
4
#Desarrollar un programa que solicite la carga de tres valores y muestre el menor. #Desde el bloque principal del programa llamar 2 veces a dicha función (sin utilizar una estructura repetitiva) def ingresar_valor(): valor1 = int(input("Ingrese un valor: ")) valor2 = int(input("Ingrese un valor: ")) valor3 = int(input("Ingrese un valor: ")) if valor1 < valor2 and valor1 < valor3: print("El menor es: ", valor1) elif valor2 < valor1 and valor2 < valor3: print("El menor es: ", valor2) else: print("El menor es: ", valor3) #main ingresar_valor() ingresar_valor()
false
ddee8e59a44e8f76b83f63ebcc1054c8e6e1d128
EdgarUstian/CSE116-Python
/src/tests/UnitTesting.py
721
4.1875
4
import unittest from lecture import FirstObject class UnitTesting(unittest.TestCase): def test_shipping_cost(self): small_weights = [15.0, 10.0, 20.0, 25.0, 10.0] large_weights = [45.0, 30.1, 30.0, 55.0] def compute_shipping_cost(weight): if weight < 30: return 5.0 else: return 5.0 + (weight - 30.0) * 0.25 for small_weight in small_weights: self.assertTrue(FirstObject.computeShippingCost( small_weight) == compute_shipping_cost( small_weight), small_weight) for large_weight in large_weights: self.assertTrue(FirstObject.computeShippingCost( large_weight) == compute_shipping_cost( large_weight), large_weight) if __name__ == '__main__': unittest.main()
true
d311cb7a2bd31e9cd658714257c7db218e429a59
code-rejoice/Learn-With-Examples-Python
/Examples/4_functions.py
1,294
4.375
4
#tutorials 4: functions print( "-->examples to define functions\n" ) x = str(input("enter an alphabet: \n")) print ("entered alphabet is ",x) def vowelTest(alphabet): vow=['a','e','i','o','u'] if any(alphabet in s for s in vow) : print("TEST PASS: the given alphabet is a vowel") else: print("TEST FAILED: the given alphabet is NOT a vowel") print("calling function test(alphabet) \n") vowelTest(x.lower()) # second method to call a function print("\n--> second method to call a function-->") y = str(input("\nenter second alphabet: \n")) print ("entered alphabet is ",y) vowelTestSecond=vowelTest(y.lower()) vowelTestSecond #third method to cal a function def vowelTestThird(alphabet,PASS="TEST PASS: the given alphabet is a vowel", FAIL="TEST FAILED: the given alphabet is NOT a vowel"): vow=['a','e','i','o','u'] if any(alphabet in s for s in vow) : print(PASS) else: print(FAIL) print("\n--> third method to call a function-->") z = str(input("\nenter third alphabet: \n")) print ("entered alphabet is ",z) vowelTestThird(z.lower()) vowelTestThird(z.lower(),"\nfunction with optional param called: " "RESULT PASS: try with 25 other alphabets!", "\nfunction with optional param called: " "FAIL: dont worry! you have 25 more alphabets to test!") #TO BE CONTINUED
false
0768f554f6d4780360f4cf27f7fdc3f4734a1f4b
rishav-karanjit/Udemy-Python-Basic
/6. Project 1 - Basic Calculator/1. Getting the data.py
465
4.4375
4
# input() -> Takes user input in the form of string a = int(input("Enter a integer:")) #We have changed string to integer because operations like addition cannot be performed in string b = int(input("Enter a integer:")) sign = input("Enter \n + for addition \n - for substraction \n * for multiplication \n / for division\n") #No need to convert sign variable to integer because we don't expect integer in sign print("a =",a) print("b =",b) print("sign =",sign)
true
e128fc066b44c825fd4ad8e0c38afacc931b385d
massadraza/Python-Learning
/defualt_Values_for_arguements.py
282
4.1875
4
def get_age(age = "Unknown"): if age is "13<": age = 'kid' elif age is "13>": age = 'teen' elif age is '18>': age = 'adult' print (age) get_age('13<') get_age('13>') get_age('18>') get_age() # Learning about defualt Values for arguements
false
504e771762dc1227fab5e0d4572629c1e7a5cbcd
MattSokol79/Python_Control_Flow
/loops.py
824
4.375
4
# Loops for loop and while loop # for loop is used to iterate through the data 1 by 1 for example # Syntax for variable name in name_of_data collection_variable shopping_list = ['eggs', 'milk', 'supermalt'] print(shopping_list) for item in shopping_list: if item == 'milk': print(item) sparta_user_details = { 'first_name' : 'Charlie', 'last_name' : 'Shelby', 'dob' : '22/10/1997', 'address' : '74 Privet Drive', 'course' : 'DevOps', 'grades' : ['A*', 'A', 'A'], 'hobbies' : ['running', 'reading', 'hunting'] } # To print keys and values use a for loop for i, j in sparta_user_details.items(): if isinstance(j, list): print(f"Key: {i}") for k in j: print(f"List Value: {k}") else: print(f"Key: {i}, Value: {j}")
true
db08593250bf45ccc385036980ef67711cb3bf87
wonkim0512/BDP
/week2/palindrome.py
249
4.3125
4
# palindrome checker def palindrome(): string = raw_input("Enter the sentence what you want to chech palindrome:") if string == string[-1::-1]: print "It is palindrome!" else: print "It is not palindrome" palindrome()
false
2365ccf635085dfa2e38e28d80aa7a1811eb0279
Ch-sriram/python-advanced-concepts
/functional-programming/exercise_2.py
405
4.1875
4
# Small exercises on lambda expressions # Square each element in the list using lambda expression my_list = [5, 4, 3] print(list(map(lambda item: item ** 2, my_list))) # Sort the following list on the basis of the 2nd element in the tuple my_list = [(0, 2), (4, 3), (9, 9), (10, -1)] print(sorted(my_list, key=lambda tup: tup[1])) ''' Output: ------ [25, 16, 9] [(10, -1), (0, 2), (4, 3), (9, 9)] '''
true
0dda899681dd50663c3aa5a81c3ef00a1df6f090
Ch-sriram/python-advanced-concepts
/functional-programming/reduce.py
1,061
4.125
4
''' The reduce() function isn't provided by python directly. reduce() function is present inside the functools package, from which we import the reduce() function. In the functools library, we have functional tools that we can use to work with functions and callable objects. ''' from functools import reduce # syntax for reduce: reduce(function, iterable[, init_value_of_the_internal_acc]) # The reduce function has an accumulator that it takes as the # first parameter and the next parameter is the item from the # iterable. The value of accumulator by default is 0. # whatever we return from the function is stored in the # accumulator parameter, and this is the main reason why we # use the reduce() function. def accumulator(acc, item): return acc + item my_list = [1, 2, 3] print(reduce(accumulator, my_list)) # same as -> reduce(accumulator, my_list, 0) print(reduce(accumulator, my_list, 10)) # 16 # reduce() is really powerful and under the hood, map() and # filter() functions actually use the reduce() method ''' Output: ------ 6 '''
true
795e15a99a91d2857fbdfab497ecaccd1789c0e8
ilarysz/python_course_projects
/data_structures/3_stack/linkedstack.py
920
4.28125
4
from linkedlist import LinkedList class LinkedStack: """ This class is a stack wrapper around a LinkedList. """ def __init__(self): self.__linked_list = LinkedList() def push(self, node): """ Add a node to the start of the linked list property. :param node: The Node to add :return: None """ self.__linked_list.add_start_to_list(node) def pop(self): """ Remove a node from the start of the linked list, and return the removed node. :return: Node, the last node of the linked list after being removed. """ return self.__linked_list.remove_start_from_list() def print_details(self): self.__linked_list.print_list() def __len__(self): """ Return the amount of Nodes in the linked list. :return: """ return self.__linked_list.size()
true
91f4b5659ced240b326e011c4228713a8fd378c4
github-hewei/Python3_study
/2/5.面向对象.py
787
4.21875
4
# 面向过程 # 创建一个苹果 apple = {} apple['name'] = '苹果' apple['color'] = '红色' apple['price'] = 10 print('我吃了一个%s'%apple['name']) # 创建一个香蕉 banana = {} banana['name'] = '香蕉' banana['color'] = '黄色' banana['price'] = 20 print('我吃了一个%s'%banana['name']) # 面向对象 class food: name = '' color = '' price = 0 def __init__(self, name, color, price): self.name = name self.color = color self.price = price return None def eat(self): print('我吃了一个%s的%s'%(self.color, self.name)) return None # 创建一个苹果对象 apple = food('苹果', '红色', 100) apple.eat() # 创建一个香蕉对象 banana = food('香蕉', '黄色', 200) banana.eat()
false
60ce10d064bf776b47d4e35da055b4a88d2a88aa
likhi-23/DSA-Algorithms
/Data Structures/linked_queue.py
1,828
4.1875
4
#Linked Queue class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.tail=None def enqueue(self, data): if self.tail is None: self.head =Node(data) self.tail =self.head else: self.tail.next = Node(data) self.tail = self.tail.next def dequeue(self): if self.head is None: print("Queue Underflow") else: print("Element removed from the queue is ", self.head.data) self.head = self.head.next def first(self): return self.head.data def size(self): temp=self.head count=0 while temp is not None: count=count+1 temp=temp.next return count def isEmpty(self): if self.head is None: return True else: return False def printqueue(self): print("Queue elements are:") temp=self.head while temp is not None: print(temp.data,end="->") temp=temp.next if __name__=='__main__': queue = Queue() print("Queue operations") queue.enqueue(24) queue.enqueue(55) queue.enqueue(68) queue.enqueue(47) queue.enqueue(61) queue.enqueue(72) queue.printqueue() print("\nFirst element is ",queue.first()) print("Size of the queue is ",queue.size()) queue.dequeue() queue.dequeue() print("After applying dequeue() two times") print("First element is ",queue.first()) queue.printqueue() print("\nQueue is empty:",queue.isEmpty()) queue.dequeue() queue.dequeue() queue.dequeue() print("After applying dequeue() three times") print("Size of the queue is ",queue.size()) queue.printqueue() queue.dequeue() print("\nQueue is empty:",queue.isEmpty()) queue.dequeue()
true
91c9488189f2895212594e1834cb54f5de713b8e
lpjacob/RPN-Calculator
/operand_queue.py
1,025
4.15625
4
""" Program to perform demonstrate a static queue in Python by ljacob1@canterbury.kent.sch.uk Purpose: to demonstrate queue operation, Limitations: WIP - not currently fully tested """ """global variables""" queue = [] maxSize = 5 #constant to set max queue size tailPointer = 0 def queueSize(): global queue return len(queue) def enqueue(item): """add an item to the tail of the queue if its not full""" global queue, maxSize, tailPointer if tailPointer < maxSize: queue.append(item) tailPointer print("queue containts", queue) else: print("queue full") def dequeue(): global queue, maxSize, headPointer, tailPointer removedItem = None if len(queue)>0: removedItem = queue.pop(0) print("queue containts", queue) else: print("Queue Empty!") return removedItem if __name__ =="__main__": enqueue("+") enqueue("*") print(dequeue()) enqueue("-") print(dequeue()) print(dequeue()) print(dequeue())
true
8cfc47ff3793abb4c6cac760607941d198c3064d
ayushi710/basic-python-program
/pattern1.py
253
4.125
4
# using for loop for i in range(6): for j in range(i): print("*",end=" ") print("\r") print("\n") # using while loop i = 1 while i <= 6: j = 1 while j <= i: print("* ",end="") j = j+1 i = i+1 print("\r")
false
91bf3c7be3b61637fa8b66c891a5c3d26fb713f8
zhangqunshi/common-utils
/python/file/remove_duplicate_line.py
607
4.1875
4
# coding: utf8 # # Remove the duplicate line of a file # import sys def remove_duplicate_line(filename): exist_lines = list() with open(filename) as f: for line in f.readlines(): line = line.strip() if not line: continue if line not in exist_lines: exist_lines.append(line) print(line) if __name__ == "__main__": if (not sys.argv) or (len(sys.argv) != 2): print("Usage: python %s <file> " % __file__) sys.exit(1) filename = sys.argv[1] remove_duplicate_line(filename)
true
64b82c06f17926340b3f49e8fe8ccc27f716f367
robeertgr/Geek_University_Python_Secao_5
/estruturas_logicas_and_or_not_is.py
686
4.15625
4
""" Estruturas lógicas: and (e), or (ou), not (não) e is (é). Operadores unários: - not Operadores binários: - and, or, is # Regras de funcionamento # Para o 'and', ambos os valores precisam ser True # Para o 'or', um ou outro valor precisa ser True # Para o 'not', o valor do booleano é invertido """ ativo = True logado = True """ if ativo and logado: print("Bem vindo usuário.") else: print("Usuário inativo no sistema.") """ """" if not ativo: print("Você precisa ativar sua conta.") else: print("Bem vindo usuário.") print(not True) """ if ativo is False: print("Você precisa ativar sua conta.") else: print("Bem vindo usuário.")
false
78123433f18d7959d1f7f264e85c4afd964cb878
coala/workshops
/2016_07_03_doctesting_in_python_lasse/sum.py
320
4.3125
4
def sum(*args): """ Sums up all the arguments: >>> sum(1, 2.5, 3) 6.5 If you don’t provide any arguments, it’ll return 0: >>> sum() 0 :param args: Any numbers to sum up. :return: The sum of all the given """ return args[0] + sum(*args[1:]) if len(args) > 0 else 0
true
15b5608a5d690e4fbc40285ea65c94a81195f624
dhruvilthakkar/Dhruv_Algorithm_and_Games
/check_prime.py
267
4.15625
4
#!/usr/bin/env python from __future__ import print_function def check_prime(num): for i in range(2,num): if num % i == 0: print('Number is not prime') break print('Number is prime') num = input('Enter number to check for: ') check_prime(num)
true
29b21b246bd6eadf38f3e71b23d61a5f4590c05f
Alireza-Helali/Design-Patterns
/ProtoType_p2.py
1,500
4.125
4
from copy import deepcopy """ ProtoType: prototype is creational design pattern that lets you copy existing objects without making your code dependant on your classes """ class Address: def __init__(self, street, building, city): self.street = street self.building = building self.city = city def __str__(self): return f'{self.street}, {self.building}, {self.city}' class Employee: def __init__(self, name, address): self.name = name self.address = address def __str__(self): return f'{self.name} works at {self.address}' class EmployeeFactory: main_office_employee = Employee('', Address('sheykh bahayee', 'mapsa', 'tehran')) aux_office_employee = Employee('', Address('sohrevardi', 'mofid', 'tehran')) @staticmethod def __new_employee(proto, name, city): result = deepcopy(proto) result.name = name result.address.city = city return result @staticmethod def new_main_office_employee(name, city): return EmployeeFactory.__new_employee( EmployeeFactory.main_office_employee, name, city) @staticmethod def new_aux_office_employee(name, city): return EmployeeFactory.__new_employee( EmployeeFactory.aux_office_employee, name, city ) p1 = EmployeeFactory.new_main_office_employee('alireza', 'isfahan') p2 = EmployeeFactory.new_main_office_employee('faezeh', 'tabriz') print(p1) print(p2)
true
5acdaf70d6cb94d97a315d255ca6a1db1e027c44
Alireza-Helali/Design-Patterns
/Interface_Segregation_principle.py
2,207
4.3125
4
# Interface Segregation Principle """ The idea of interface segregation principle is that you dont really want to stick too many elements or too many methods in to an interface. """ from abc import ABC, abstractmethod class Machine(ABC): @abstractmethod def printer(self, document): pass @abstractmethod def fax(self, document): pass @abstractmethod def scan(self, document): pass class MultiFunctionPrinter(Machine): def printer(self, document): print(f'print {document}') def fax(self, document): print(f'faxing {document}') def scan(self, document): print(f'scanning {document}') class OldFashionPrinter(Machine): """THe problem with this class is old fashion printer doesn't support fax and scanning and client instantiate this class see's fax and scan and assume that this machine support this features""" def printer(self, document): print('print document') def fax(self, document): pass # old fashion printer don't have this feature def scan(self, document): pass # old fashion printer don't have this feature """ So instead of having one class and all the methods in it we are going to break that class to smaller classes. in this way machines will have the exact feature that they should had. """ class Printer(ABC): @abstractmethod def print(self, document): pass class Fax(ABC): @abstractmethod def fax(self, document): pass class Scanner(ABC): def scan(self, document): pass class MyCopier(Printer): def print(self, document): print(f'print {document}') class PhotoCopier(Printer, Scanner): def print(self, photo): print(f'print {photo}') def scan(self, photo): print(f'print {photo}') class MultiFunctionMachine(Scanner, Fax, ABC): @abstractmethod def fax(self, document): pass @abstractmethod def scan(self, document): pass class MultiFunctionDevice(MultiFunctionMachine): def fax(self, document): print(f'faxing {document}') def scan(self, document): print(f'scanning {document}')
true
e49b2f20b098d8119943430968da3d841376642c
sarwar1227/Stone-Paper-Scissors-E-Game
/stone_paper_scissors E-Game.py
2,659
4.15625
4
'''Stone Paper Scissors E-Game by SARWAR ALI(github.com/sarwar1227) using Python Technologies Required To Run this Code : Pyhton(32/64 bit) version 2/3+ INSTRUCTIONS TO PLAY THIS GAME : 1.Computer Randomly chose between ston/paper/scissors 2.You are asked to chose your option 3.Based on some camparisons Winner of the game is decided GOOD LUCK FOR THE GAME !!''' import random,os,sys name=input("Enter Your Name : ") choices=['stone','paper','scissors'] def display(): print("Hello",name,",Welcome To Stone Paper Scissors Game") comp_choice=random.choice(choices) try: x=int(input("Choices Available\n1.Stone\n2.Paper\n3.Scissors\nEnter Your Choice:")) except ValueError: print("Only integer Value Allowed !!") input() play_again() if (x==1): user_choice='stone' elif (x==2): user_choice='paper' elif (x==3): user_choice='scissors' else: print("Invalid Choice") if (comp_choice=='stone' and user_choice=='scissors') or (comp_choice=='paper' and user_choice=='stone') or (comp_choice=='scissors' and user_choice=='paper'): print("Computer Choice:",comp_choice,"\n",name,"Choice:",user_choice,"\nBad Luck....Computer Wins !!") if comp_choice=='stone': print("Computer's Stone Crushed Your Scissors !!") elif comp_choice=='paper': print("Computer's Paper Blocked Your Stone") elif comp_choice=='scissors': print("Computer's Scissors Cut Down Your Paper") input() play_again() elif (user_choice=='stone' and comp_choice=='scissors') or (user_choice=='paper' and comp_choice=='stone') or (user_choice=='scissors' and comp_choice=='paper'): print("Computer Choice:",comp_choice,"\n",name,"Choice:",user_choice,"\nCongratulations ",name,"!! You Won the Game !!") if user_choice=='stone': print("Your Stone Crushed Computer's Scissors !!") elif user_choice=='paper': print("Your Paper Blocked Computer's Stone") elif user_choice=='scissors': print("Your Scissors Cut Down Computer's Paper") input() play_again() def play_again(): ch=input("Want to play again? (y/Y) for Yes (n/N) for No:") if ch in ['y','Y']: os.system("cls") display() elif ch in ['n','N']: print("Thanks For Playing...The Game!!\nPress Any Key To End...........") input() sys.exit("Thank For Playing !!") elif ch not in ['y','Y','n','N']: print("Invalid Input") play_again() display()
true
c5bf8c4f132f30281414a6ea88f67ff977c14131
MarianaMedeiros/python-basics
/part14_args_kwargs.py
1,956
4.75
5
""" args e kwargs """ """ Digamos que queremos criar uma função de ordem alta que tem como entrada uma função f e retorna uma função nova que retorna duas vezes o valor de f para qualquer entrada: """ def doubler(f): def g(x): return 2 * f(x) return g """ isto funciona em alguns casos: """ def f1(x): return x + 1 g = doubler(f1) print(g(3)) # 8 ( == (3 + 1) * 2 ) print(g(-1)) # 0 ( == (-1 + 1) * 2 ) """ No entando, ele falha com funções que possuem mais de um único argumento: """ def f2(x, y): return x + y g = doubler(f2) #print(g(1,2)) #TypeError: g() pega exatamente 1 argumento (2 dados) """ O que precisamos é de alguma maneira de especificar uma função que leva argumentos arbitrários. Podemos fazer isso com a descompactação de argumentos e um pouco de mágica:""" def magic(*args, **kwargs): print("unnamed args: ", args) print("keyword args: ", kwargs) magic(1, 2, key="word", key2="word2") #imprime: # unnamed args: (1, 2) # keyword args: {'key': 'word', 'key2': 'word2'} """ Ou seja, quando definimos uma função como essa, args é uma tupla dos seus argumentos sem nome e kwargs é um dict dos seus argumentos com nome. Funciona da forma contrária também, se você quiser usar uma list (ou tuple) e dict para fornecer argumentos para uma função: """ def other_way_magic(x, y, z): return x + y + z x_y_list = [1, 2] z_dict = {"z": 3} print(other_way_magic(*x_y_list, **z_dict)) # 6 """ Você poderia fazer todos os tipos de truques com isso; apenas usaremos para produzir outras funçẽs de ordem alta cujas entradas podem aceitar argumentos arbitrários: """ def doubler_correct(f): """ funciona, não importa que tipo de entradas f espera =) """ def g(*args, **kwargs): """ quaisquer argumentos com os quais g é fornecido, os passa para f """ return 2 * f(*args, **kwargs) return g g = doubler_correct(f2) print(g(1, 2)) # 6
false
d23a81e251ccfb2000f3de8ac0e93db194e08bee
shasha9/30-days-of-code-hackerrank
/Day_04_ClassVSInstance.py
1,345
4.21875
4
#Task # Write a person class with an instance variable age and a constructor that takes an integer initialAge as a parameter. #The constructor must assign initialAge to age after confirming the argument past as initialAge is not negative; #if a negative argument is passed past as initilAge, the constructor should set age 20 to 0 and print "age is not valid setting age to 0" #In addition you must write the following instance methods: #yearPasses() should increase the age instance variable by 1 #amIOld() should perform the following conditional actions: #if age<13 print "you are young" #if age<=13 and age<18 print "you are a teenager" otherwise print "you are old". class Person: age=0 def __init__(self,initialAge): # Add some more code to run some checks on initialAge if initialAge < 0: print ("Age is not valid, setting age to 0.") else: self.age=initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if self.age < 13: print ("You are young.") elif self.age >= 13 and self.age < 18: print ("You are a teenager.") else: print ("You are old.") def yearPasses(self): # Increment the age of the person in here self.age=self.age+ 1
true
7373b562b5e59201e6ffdcdde140e33dba3ce468
thiteixeira/Python
/Sum_Avg_Variance_StdDeviation.py
898
4.21875
4
#!/usr/bin/env python ''' Compute the Sum, Average, Variance, Std Deviation of a list ''' grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(grades): total = 0 for grade in grades: total += grade return total def grades_average(grades): sum_of_grades = grades_sum(grades) average = sum_of_grades / float(len(grades)) return average def grades_variance(scores): variance = 0.0 average = grades_average(scores) for score in scores: variance += (average - score) ** 2.0 return variance / float(len(scores)) def grades_std_deviation(variance): return variance ** 0.5 print(grades) print('Sum of grades: ' + str(grades_sum(grades))) print('Average: ' + str(grades_average(grades))) print('Variance: ' + str(grades_variance(grades))) print('Std: ' + str(grades_std_deviation(grades_variance(grades))))
true
caeb99fe34437b5d5adc1c31cad03bbc30e31e35
ASHOK6266/fita-python
/w3resource/python3/List/exercise.py
1,614
4.34375
4
''' 1. Write a Python program to sum all the items in a list. list_values = [2,4,5,6] index = 0 while index < len(list_values): print(list_values[index]) index += 1 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 2. Write a Python program to multiplies all the items in a list. 3. Write a Python program to get the largest number from a list. lis = [2,7,8,89,78,98,87,34] large = max(lis) print(large) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. #HOW TO FIND THE LENGTH sample = ['abc', 'xyz', 'aba', '1221','1','121'] # x[0] = a empty = [] #empty2 =[] #empty2.extend() for x in sample: if len(x) >= 2 and x[0] == x[-1]: empty.append(x) #empty2.extend(list(x)) # The return format will be in the form of list print(len(empty) 7. Write a Python program to remove duplicates from a list sampleList = ['1','ak','ak','1','5'] tup = ('1','2') se = {'1','55','65'} list1 = [] list2 = [] list1.extend(tup) list1.extend(se) # Always should use append list2.append(tup) print(list2) dict3 = {'as': 33, 'ak': 33, 'an': 33} for k,v in dict3.items(): #print(k) print(dict3.values()) '''
true
7b8cbe2a5228cc3153d40bfeaf976cd1f8857f42
PatrickPitts/Brainworms
/lab2/SeasonsAndDays.py
1,526
4.40625
4
# Author : John Patrick Pitts # Date : June 21, 2021 # File : SeasonsAndDays.py # imports essential libraries import sys # gets data input from the user day_num = eval(input("Enter a number between 1 and 7: ")) season = input("Enter a season: ") day = "" month = "" # lists to check against for type of season spring = ["spring", "Spring", "SPRING"] summer = ["summer", "Summer", "SUMMER"] fall = ["fall", "Fall", "FALL"] winter = ["winter", "Winter", "WINTER"] # assigns values to 'day' based on the value of 'day_num' # exits the script early if input is bad if day_num == 1: day = "Monday" elif day_num == 2: day = "Tuesday" elif day_num == 3: day = "Wednesday" elif day_num == 4: day = "Thursday" elif day_num == 5: day = "Friday" elif day_num == 6: day = "Saturday" elif day_num == 7: day = "Sunday" else: sys.exit() # Assigns a value to 'month' based on 'season' and 'day_num' # exits the script if input is bad if season in spring: month = "March" elif season in winter: month = "December" elif season in fall: month = "September" elif season in summer: if day_num <= 3: month = "June" else: month = "July" else: sys.exit() # prints data to user print("The day is {day}, which day number {day_num}.".format(day=day, day_num=day_num)) print("The month is {month} which is in the {season}".format(month=month, season=season)) # prints extra data to user based on 'season' and 'day_num' if season in summer and day_num == 6: print("Go swimming!")
true
fac443035144eb723c6df6a82fa4405079c49b10
Ewa-Gruba/Building_AI
/Scripts/C3E15_Nearest_Neighbor.py
947
4.15625
4
import math import random import numpy as np import io from io import StringIO import numpy as np x_train = np.random.rand(10, 3) # generate 10 random vectors of dimension 3 x_test = np.random.rand(3) # generate one more random vector of the same dimension def dist(a, b): sum = 0 for ai, bi in zip(a, b): sum = sum + (ai - bi)**2 return np.sqrt(sum) def nearest(x_train, x_test): nearest = -1 ite = -1 min_distance = np.Inf # add a loop here that goes through all the vectors in x_train and finds the one that # is nearest to x_test. return the index (between 0, ..., len(x_train)-1) of the nearest # neighbor for train_item in x_train: distance = dist(x_test, train_item) ite = ite + 1 if distance < min_distance: min_distance=distance nearest=ite print(nearest) nearest(x_train, x_test)
true
7bf4d9a3ac26769a211fe336c56d5cef6c0e0522
willamesalmeida/Maratona-Datascience
/Semana 1 - O poderoso Python/fase 2 - Exercicios/Estruruda de Decisão/Exercicio 2.py
285
4.28125
4
# 2 - Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. valor = float(input("Forneça um valor e direi se é positivo ou negativo: ")) if valor < 0: print("O valor fornecido é negativo! ") else: print("O valor fornecido é positivo! ")
false
8044c59728a243d5ba9e974e0a8c62c3dd9cf750
ingehol/RomanNumerals
/main.py
2,205
4.21875
4
# Function for turning integers into roman numerals. # Creating lists with integers and the corresponding roman numerals. integers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] romans = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] def int_to_roman(val): i = 12 roman_from_number = "" # while-loop that runs as long as value is greater than 0. while val > 0: # for-loop to see if the value can be divided with the current integer value of i. for _ in range(val // integers[i]): # adds the character corresponding to the current integer to the string then subtracts # it from the overall value (the input) roman_from_number += romans[i] val -= integers[i] i -= 1 return roman_from_number # Roman numerals to integers # Dictionary trans = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_int(numeral): num_from_roman = 0 # while-loop that runs as long as the length of numeral is more than 0. while len(numeral) > 0: # After that, it checks if length of the input is greater than 1, and if the next character is equal to # 5x or 10x the value of the current one if len(numeral) > 1 and trans[numeral[1]] in (trans[numeral[0]] * 5, trans[numeral[0]] * 10): # if the next character is greater, you want to subtract the one in front of it. add = trans[numeral[1]] - trans[numeral[0]] numeral = numeral[2:] else: # else it adds the value corresponding to the character. add = trans[numeral[0]] numeral = numeral[1:] num_from_roman += add return num_from_roman # Printing out to see that it works. print(int_to_roman(1994)) print(roman_to_int("MCMXCIV")) # Prints out 1-3999 in both roman numerals and the corresponding integers def up_to_3999(): for i in range(1, 4000): # converts value of i to roman numerals roman = int_to_roman(i) # converts the roman numerals back to an integer integer = roman_to_int(roman) # prints the values print(roman, integer) up_to_3999()
true
10cc4bf9eb93419251371f45e589c194f7cdd2f4
SeanIvy/Learning-Python
/ex6 (2).py
2,000
4.25
4
# --------------------------------- # Header # --------------------------------- # LPTHW - Exercise 6 # Sean Ivy - 050912 # Exercise 6 - Strings and Text # --------------------------------- # Start Code # --------------------------------- # Setting up Variables # --------------------------------- x = "There are %d types of people." % 10 # String within a string. x sets up the variable "There are %d types of people." %d calling a decimal string, so Python is looking for the string to be a number. binary = "binary" # variable binary, calling string "binary". This is showing how double quotes makes it a string. do_not = "don't" # Reinforcing the message from line 17. This time in the form of a contraction. y = "Those who know %s and those who %s." % (binary, do_not) # now 2 strings within a string. y sets up the variable "Those who know %s (string call) and those who %s (another string call)." Line 19 shows how to call multiple variables into the same string. # Using the Variables # --------------------------------- print x print y print "I said: %r." % x # Talk to steve about the use of %r here instead of %s. print "I also said: '%s' ." % y # Just a call back to the variable y, with 2 additional strings inserted into this string. # Setting up more Variables # --------------------------------- hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" # I believe %r is used here because the string will call back to a function call (False) instead of a string? # Using more Variables # --------------------------------- print joke_evaluation % hilarious # Printing the variable joke_evaluation, and setting up what string the %r in 'joke_evaluation' is calling. # Last Variable setup and use # --------------------------------- w = "This is the left side of..." e = "a string with a right side." print w + e # Line 47 is what I call a 'knot' as it ties two strings together. # --------------------------------- # End Code # ---------------------------------
true
abb45bb26b7448d89575f90cc770b5e34fdc1135
NoeNeira/practicaPython
/Guia_1/Ejercicio10.py
562
4.28125
4
"""Escribir un programa que almacene todas las letras del abecedario y luego elimine las vocales y nos devuelva una lista sin las vocales, sin modificar la original """ abecedario = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "ñ", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] vocales = ["a", "e", "e", "o", "u"] nuevoAbecedario = [] # for letra in abecedario: # print(letra) for letra in abecedario: if letra not in vocales: nuevoAbecedario.append(letra) print(nuevoAbecedario)
false
6b6b490f63b1be54482cd36444e3c88e5bb461a9
NoeNeira/practicaPython
/Guia_2/Ejercicio1.py
662
4.40625
4
""" Pedir al usuario que ingrese un mensaje cualquiera, si el mensaje tiene más de 100 caracteres imprimirlo por pantalla, si tiene entre 50 y 100 caracteres imprimirlo al revés, si no se cumple ninguna de las opciones anteriores, por pantalla devolver un mensaje que diga "su mensaje es demasiado corto" """ texto = input("Por favor ingrese un texto") if len(texto) >= 100: print(texto) elif 50 <= len(texto) and len(texto) < 100: print(texto[::-1]) else: print("Su mensaje es demasiado corto") # str(a[::-1])) # Return the slice of the string that starts at the end and steps backward one element at a time # mensaje[start:stop:step]
false
770edf3dc3dbde450b0c82e276193f413a633732
aidenyan12/LPTHW
/EX36/ex36.py
2,848
4.15625
4
from sys import exit def cave(): print "You're in a cave, a dragon is living inside to safeguard the magic sword" print "You need to take the sword as a weapon to kill the evil king to safe the country" print "You can choose 'sing' to make the dragon fall alseep or 'fight' with the dragon" action = raw_input("> ") if action == 'sing': print "The dragon fell asleep, you stole the sword and leave!" secret_maze() elif action == 'fight': print "The dragon cuts you into pieces, you're fail..." dead() else: print "Please choose 'sing' or 'fight'" def secret_maze(): print "Welcome to the secret maze!" print "You have to go in right direction to walk through the maze then enter the king's castle " print "There's a crossroad in front of you, you will turn 'left', 'right' or 'say WTF' " loop = False while True: action = raw_input("> ") if action == 'left': print "Wow! The dragon woke up and robbed the sword back to the cave, You go back to cave!!!" cave() elif action == 'right': print "OH! NO! You were caught up and killed by the soiders " dead() elif action == 'say WTF': print "Thant's the magic word for oppeing the entrence of the castle, you directly skip the maze!" castle() else: print "Please choose 'left', 'right' and 'say WTF'. " loop = True def castle(): print "Welcome to the castle, the evil king has been waiting you for a loooooog time." print "The king has a gun and he's going to shoot you ..." print "Input 'skip' to escape the bullets or 'grasp' to catch all the bullets. " catch_bullet = False while True: action = raw_input("> ") if action == 'skip': print " That's cool ~" print " You used your sword to take down the head of evil king. Congratulation!" exit(0) elif action == 'grasp' and not catch_bullet: print "Too many bullets, you can't catch them all, you are dead." dead() elif action == 'grasp' and catch_bullet: print "Fantastic ! You just killed the King with your sword. Congratulation!" catch_bullet = True exit(0) else: print "I got no idea what that means." def dead(): count() print "You're dead. Donate $10 to UNICEF to play again." print "'Yes' or 'No' for donation" donation = False while True: action = raw_input ("> ") if action == 'Yes': start() elif action =='No': print "Bye~" exit(0) else: print "I got no idea what that means." donation = True def start(): print "Please pick a name for your character: 'Lucy' or 'Kevin'." action = raw_input("> ") if action == 'Lucy': print "In fact I think Kevin sounds better, Please restart from Kevin XD" start() elif action == 'Kevin': cave() def count(): i = 0 numbers = [] while i < 101: numbers.append(i) i = i + 10 print numbers, " percent of HP has recovered. " start()
true
eff4b958a0918618ab71b8d275fe0b2b10792fb4
Sayan725/Sayan725
/say.py
261
4.21875
4
num1 = int(input('Enter first number: ')) num2 = int(input('Enter second number: ')) op = input('Enter Operator') if op == '+': print(num1+num2) if op == '-': print(num1-num2) if op == '*': print(num1*num2) if op == '/': print(num1/num2)
false
07265f21311c4a90056ddf0f4c7458cfdae4e880
DokiStar/my-lpthw-lib
/ex11.py
719
4.21875
4
print("How old are you?", end=' ') # input默认返回字符串类型 age = input() print("How tall are you?", end=' ') height = input() print("How much do you weight?", end=' ') weight = input() print(f"So, you're {age} old, {height} tall and {weight} heavy.") # 更多输入 str = input("Input some text here: ") str2 = input("more things here: ") print("The text you input is", str + str2) # 类似代码 name = input("Your name: ") univiersity = input("Your university: ") print("Hello,", name, "\nyour university is", univiersity) # input转换为数字,使用int()强制转换 num1 = int(input("Input a number here: ")) num2 = int(input("Input another number here: ")) print("num1 + num2 =", num1 + num2)
true
7032001cac6b18552bb161bb3c07f55961cc8230
greenfox-zerda-lasers/matheb
/week-03/day-2/36.py
243
4.25
4
numbers = [3, 4, 5, 6, 7] # write a function that reverses a list def rev(numbers): newlist = [] for i in range(len(numbers)-1, -1, -1): print(numbers[i]) newlist.append(numbers[i]) print(newlist) rev(numbers)
true
cf934c557b66a540408af48e1c5ebb3dcc0ea7e1
andyyu/coding-problems
/maximum_product_of_three.py
1,811
4.125
4
# Andy Yu ''' Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. Difficulty: Easy Problem solutions: This problem would be very trivial if not for the possibility of negative integers. We know that besides the obvious choice of (the product of the 3 largest numbers), we must also consider the scenario of (the product of the two smallest (negative) numbers, and the largest positive number). We can simply consider both scenarios in one pass, keeping track of the two most negative numbers and the three most positive numbers. O(n) time O(1) space ''' def maximumProduct(nums): largest = [float('-inf')] # largest 3, populate with default value so it's not an empty list smallest = [float('inf')] # smallest 2 for num in nums: if num > largest[-1]: # maintain last in list as the smallest of the largest 3 if len(largest) == 3: # if already 3 numbers, delete one to make room for the new del largest[-1] largest.append(num) largest.sort(reverse=True) if num < smallest[-1]: # maintain last in list as the larger of the two if len(smallest) == 2: del smallest[-1] smallest.append(num) smallest.sort() return max(reduce(lambda x, y: x * y, largest, 1), largest[0]*smallest[1]*smallest[0]) # pick the greater of the two scenarios # Note: the above reduce + lambda was for fun, largest[2]*largest[1]*largest[0] would work just as well. if __name__ == '__main__': print maximumProduct([5, 2, -10, -6, 3])
true
c47c78d8b585483eac06ee47a9c55b02b22bb741
andyyu/coding-problems
/is_palindrome.py
686
4.21875
4
# Andy Yu ''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. -------------------------------------------------------------------------------- Difficulty: Easy Solution notes: O(n) time O(1) space ''' def isPalindrome(s): return ''.join(c for c in s.lower() if c.isalnum()) == ''.join(c for c in s[::-1].lower() if c.isalnum())
true
99cbb8dac0fe03bad60919a4ebfcf3be8e5e434a
andyyu/coding-problems
/string_permutation.py
315
4.15625
4
# Andy Yu ''' Print all permutations of a string. Difficulty: Easy Solution notes: O(n*n!) time O(1) space ''' def permutate(string, prefix = ''): if (len(string) == 0): print prefix else: for char in string: permutate(string[:string.index(char)] + string[string.index(char)+1:], prefix + char)
true
b648720e20cae1330c7a094599027bcf991b58ed
andyyu/coding-problems
/is_anagram.py
701
4.125
4
# Andy Yu ''' Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case? Difficult: Easy Solution Notes: O(n) time O(1) space ''' def is_anagram(s, t): letter_dict = {} for letter in s: letter_dict[letter] = letter_dict.get(letter, 0) + 1 for letter in t: letter_dict[letter] = letter_dict.get(letter, 0) - 1 for val in letter_dict.values(): if val != 0: return False return True
true
830c75cf9be01d0b3dbdf8ccf275d5f5aab9a000
andyyu/coding-problems
/invert_binary_tree.py
1,293
4.21875
4
# Andy Yu ''' Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None Difficulty: Easy Solution notes: My first iteration looked something like this - def invert_tree(root): if not root: return None else: temp_left = root.left root.left = invert_tree(root.right) root.right = invert_tree(temp_left) return root After some optimization, we end up with a concise 3 line solution! Note: if we are seeking optimal performance over code brevity, then we should add more "checks". if not root: return None should always be checked for each node. also check things like if not root.left and not root.right: return root if root.right / root.left: root.left/right = invert_tree(root.right) This way our code will only attempt to call invert_tree when possible / needed. This will increase performance (not by much, but if you're really trying to squeeze every bit of speed) O(n) time O(1) space ''' def invert_tree(root): if root: root.left, root.right = invert_tree(root.right), invert_tree(root.left) return root
true
b79af958a03cd31deaf3d794f18fb4eea8f8dafa
andyyu/coding-problems
/last_word_length.py
1,001
4.15625
4
# Andy Yu ''' Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. Difficulty: Easy Solution notes: Take care to note the case where the string is something like "apple orange ". This should return the length of 'orange' (6), but if you simply split using ' ' as a delimiter and return the length of [-1] of that list, it'll incorrectly return 0. An even shorter solution taking advantage of Python's built in whitespace stripping is def length_of_last_word(s): return len(s.rstrip(' ').split(' ')[-1]) O(n) time O(1) space ''' def length_of_last_word(s): word_list = s.split(' ') no_blanks = [word for word in word_list if word != ''] if len(no_blanks) > 0: return len(no_blanks[-1]) else: return 0
true
9fc1ffb05b7a6892d43c8909a37a26e99abed9fc
errorport/makker_python
/makker_python_00.py
2,164
4.28125
4
# Fibonacci számok generálása pythonnal # Az alábbi példakód segítségével egy N elemű fibonacci számsort generálhaunk. # 01 Az első példában csak egy for ciklus használatával tesszük ezt. print("Példa 01.") N=10 n_1 = n_2 = 1 for i in range(N): actual_number = n_1 + n_2 n_1 = n_2 n_2 = actual_number print(actual_number) print("-- Futás vége.") # 02 Amásodik példában a fenti kódot egy függvénybe ágyazva, a for ciklust megelőző beállításokat is elvégezzük, így egy program lefutása alatt az adott függvény tetszőleges számbna hívható. print("Példa 02.") def print_fibonacci(N): print("-- Függvényhívás: print_fibonacci(N)\nElemszám:",N) n_1 = n_2 = 1 for i in range(N): actual_number = n_1 + n_2 n_1 = n_2 n_2 = actual_number print(actual_number) print("-- Futás vége.") # itt történik a fenti függvény hívása. print_fibonacci(5) print_fibonacci(10) # 03 A harmadik példában nem kiiratjuk az értékeket, hanem elmentjük egy vektorban print("Példa 03.") def get_fibonacci_temporary(N): print("-- Függvényhívás: get_fibonacci(N)\nElemszám:",N) vector = [] n_1 = n_2 = 1 for i in range(N): actual_number = n_1 + n_2 n_1 = n_2 n_2 = actual_number vector.append(actual_number) print("-- Futás vége.") return vector #visszaadjuk a számsort egy vektorban # nincs kimenet, hiszen csak egy függvényt hoztunk létre, nem futtattuk le azt. # 04 Egy kicsit csinosítva (refactor) a kódot, elhagyjuk az n_1 és n_2 változók használatát. print("Példa 04.") def get_fibonacci(N): print("-- Függvényhívás: get_fibonacci(N)\nElemszám:",N) vector = [1, 1] for i in range(N): actual_number = vector[i] + vector[i+1] vector.append(actual_number) print("-- Futás vége.") return vector #visszaadjuk a számsort egy vektorban print(get_fibonacci(10)) # 05 Kiírjuk a generált számsor 5. és 8. elemét print("* Figyeljük meg, hogy a kimeneten milyen sorrendben jelennek meg a szövegek! *") print("Az 5. elem:", get_fibonacci(10)[4]) #0-tól indul a tömbök indexelése, így a 4. index az 5. elemet jelenti print("Az 8. elem:", get_fibonacci(10)[7])
false
9bef8335c8629608d0982148e814acfed3bab9f0
BelfastTechTraining/python
/examples/mymodule.py
865
4.15625
4
def sum_numeric_list(nums): """ Accepts a list of numeric values. Returns the sum of the elements. """ sum = 0 for item in nums: sum += item return sum def prune_dict(dict, keys_to_remove): """ Accepts a dict to priune and a list of keys to remove. Matching keys are deleted and rmainders returned. """ pruned_dict = {} for key in dict.keys(): if key not in keys_to_remove: pruned_dict[key] = dict[key] return pruned_dict if __name__ == '__main__': test_ints = [1, 2, 3, 4, 5] print('The sum of {0} is {1}'.format(test_ints, sum_numeric_list(test_ints))) test_dict = {'Tom': 'The First', 'Dick': 'The Second', 'Harry': 'The Third'} pruned_dict = prune_dict(test_dict, 'Tom') print('Stripping \'Tom\' from {0} gives us {1}'.format(test_dict, pruned_dict))
true
b36f2f7a5bc5cc1dd1bc500bfe4c45d1f34f547f
pdaplyn/adventOfCode2018
/solutions/day1.py
1,326
4.1875
4
""" >>> test = ["+1", "+1", "+1"] >>> calc_frequency(test) [0, 1, 2, 3] >>> test = ["+1", "+1", "-2"] >>> calc_frequency(test) [0, 1, 2, 0] >>> test = ["-1", "-2", "-3"] >>> calc_frequency(test) [0, -1, -3, -6] >>> test = ["+1", "-2", "+3", "+1"] >>> calc_frequency(test) [0, 1, -1, 2, 3] >>> find_first_repeated( test ) 2 """ from advent_util import read_file def calc_frequency(input_changes): changes = [int(x) for x in input_changes] frequency = 0 frequencies = [ ] frequencies.append(frequency) for change in changes: frequency += change frequencies.append(frequency) return frequencies def find_first_repeated(input_changes): changes = [int(x) for x in input_changes] frequency = 0 frequencies = { str(frequency): 1 } while 1: for change in changes: frequency += change if str(frequency) in frequencies: return frequency frequencies[str(frequency)] = 1 input_changes = read_file("../inputs/input1.txt") frequency_results = calc_frequency(input_changes) print("Final frequency is ", frequency_results[-1]) first_repeated = find_first_repeated(input_changes) print("First repeated frequency is ", first_repeated) if __name__ == "__main__": import doctest doctest.testmod()
true
7b81131365a385f8ec425940868509c4729ad1dc
danielbrock4/election_analysis_tom
/practice_examples_files/test.py
1,313
4.34375
4
# F STRINGS my_votes = () my_votes = int(input("How many votes did you get in the election")) total_votes =int(input('What is the total number of votes')) print(f"I recieved {my_votes / total_votes * 100} % of the total votes") counties = {} counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222} for county, voters in counties_dict.items(): print(county + " county has " + str(voters) + " registered voters.") for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") counties = {} counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222} for county, voters in counties_dict.items(): print(county + " county has " + str(voters) + " registered voters.") for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") candidate_votes = int(input("How many votes did the candidate get in the election? ")) total_votes = int(input("What is the total number of votes in the election? ")) message_to_candidate = ( f"You recieved {candidate_votes} number of votes." f"The total number of votes n the election was {total_votes}." f"You recieved {candidate_votes / total_votes * 100:.2f}% of the total number of votes") print(message_to_candidate)
false
b9ce5e24adecc9b4795c536dc833a0cfd8699d1a
BaggyKimono/pythonfoundationswow
/02 Printpractice.py
956
4.5625
5
""" title: Printpractice author: Ally date: 11/26/18 10:36 AM """ print("hello world") #new line print("hello world\nhell is other people") #end a print statement with a thingy print("newline", end = "-") #tabbed characters print("Testing, testing\t1\t2\t3...") print("Testing, testing\n\t1\n\t\t2\n\t\t\t3...") #Comments ''' This is an example of a multi-line comment in python. If you have a lot to say about how the program runs you can put a block of comments like so! ''' #a function def somefunc(): """ This function does xyz :return: """ #a typical way to describe a detail of a function def greeting(name, year): """ Greet the user with a friendly hello and inform them of the year :param name: a string that stores the users name :param year: an integer that stores the current year :return: the concatenated string """ return "Hello from the other side," + name + "! It is " + str(year)
true
2a5b009c76623d935619a982b43a244fff186646
marri88/python-base
/FILES/prob3.py
721
4.3125
4
# Создайте программу, которая считает из файла текст, # и если в тексте содержится буква “w”, # то выведет на экран “Да, в тексте есть w”, # иначе - “Нет, в тексте нет w”. # Подсказка: используйте ключевое слово in. h = open('/home/aimira/python/python3/week2files/text.txt', 'r') if 'w' in h.read() : print('Да, в тексте есть w') else: print('Нет, в тексте нет w') h.close() # with open('text.txt', 'r') as f: # if t in f: # print('Да, в тексте есть w') # else: # print('Нет, в тексте нет w')
false
9a9809371f87dc2cff66822fb73be8650bf2a972
marri88/python-base
/FILES/prob7.py
900
4.125
4
# Напишите программу которая спрашивает от пользователя 2 вещи: # 1.Путь до картинки которую нужно изменить. # 2.Путь до картинки НА которую нужно изменить. # Если оба пути существуют перепишите первую картинку на вторую, если нет скажите пользователю какой картинке не существует. q = input('Путь до картинки которую нужно изменит: ') w = input('Путь до картинки НА которую нужно изменить: ') x = '/home/aimira/python/python3/week2files/p.png' y = '/home/aimira/python/python3/week2files/s.png' if q == x and w == y: x = y print(x) else: print('такой картины не существует')
false
3802ff2190f66bfe3cb233429ade648bb7ecbffb
marri88/python-base
/FUNCTION1/prob3.py
1,299
4.34375
4
# Создайте функцию сложения, затем функцию вычитания двух чисел... # Создайте 3-ю функцию которая вызывает первые 2 внутри себя. # def plus(a,b): # print(a + b) # def minus(a,b): # print(a - b) # def umnojenie(a,b): # print(a * b) # def delenie(a,b): # print(a / b) # def otvet(a,b): # plus(a,b) # minus(a,b) # umnojenie(a,b) # delenie(a,b) # #вести значение a и b # otvet(150,150) #version 1 # def sum(a,b): # print(a+b) # def minus(a,b): # print(a-b) # def minusplus(): # sum(2,4) # minus(5,1) # minusplus() #version 2 # def calculate(): # operation=input("'+' or '-'") # number_1 = int(input("First number: ")) # number_2 = int(input("Second number: ")) # if operation == "+" : # print("{} + {} = ".format(number_1, number_2)) # print(number_1 + number_2) # elif operation == "-" : # print("{} - {} = ".format(number_1, number_2)) # print(number_1 - number_2) # calculate() #version 3 # a=int(input("vvedite a")) # b=int(input("vvedite b")) def f1(a,b): a+b def f2(a,b): a-b def f3(a,b): if a <=10: f1(a,b) else: f2(a,b) c = f3(5,2) print(c)
false
fb77c633d7e76d980de7db18abd7251447286de3
marri88/python-base
/IF_ELIF_ELSE/prob11.py
309
4.125
4
a=10 b=5 if a>0 and b>0: print("положительный") '''У вас есть переменные a=10 и b=5 Напишите условие которое проверяет, являются ли ваши переменные положительными числами(только один if)'''
false
b2b874aabe434bbc8001adca9ad7c70407f290e0
TarasovaYuliya/Python
/lectures/lecture02/While2.py
454
4.53125
5
# Задача: поиск натуральных чисел, результат возведения двойки в которые меньше ста x = 1 y = 2 ** x while y < 100: # проверка, не превышает ли степень 100 print(y) # вывод текущей степени двойки x += 1 # увеличение показателя y = 2 ** x # расчет следующей степени 2
false
4ba9bb1961d7dfd94f6019cda03c0fa31c0a0a96
ysr20/comp110-fa20-lab02
/draw_polygon.py
601
4.6875
5
""" Module: draw_polygon Program to draw a regular polygon based on user's input. """ import turtle # create a turtle and set the pen color duzzy = turtle.Turtle() duzzy.pencolor("red") # asks user for the length of the pentagon go_forward=int(input("Enter a length for the pentagon: ")) #asks user for number of sides in polygon side_number=int(input("Choose number of sides: ")) #draw polygon for i in range(side_number): duzzy.forward(go_forward) duzzy.left(360/side_number) # keep the turtle window open until we click on it turtle_window = turtle.Screen() turtle_window.exitonclick()
true
0d6fbc8b255a676dbc6b6da8608eee3367615187
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/WEBEU3-PY1/guessing.py
1,080
4.3125
4
## guessing game where user thinks of a number between 1 and 100 ## and the program tries to guess it ## print the rules of the game print("Think of a number between 1 and 100, and I will guess it.") print("You have to tell me if my guess is less than, greater than or equal to your number.") # set a sentinal value to exit loop correct = False # set the top and bottom bounds top = 100 bottom = 1 ## REPL ## continue looping until a condition is false while not correct: ## have the computer guess the number guess = (top + bottom) // 2 ## print our some prompt print(f"I am guessing it is {guess}") ## take input from user result = input("Less, Greater, or Equal? ").lower() result = result[0] ## evaluate input if result == 'l': top = guess - 1 elif result == 'g': bottom = guess + 1 elif result == 'e': correct = True else: print("Please enter either less, greater or equal") if top == bottom: guess = top correct = True ## print result print(f'\nIt is {guess}!\n')
true
da2734b97e7b3b1449ed1688e1406e4c62e2e726
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/WEBEU3-PY1/day1.py
1,819
4.15625
4
# This is a comment # lets print a string print("Hello, World!") # variables name = "Tom" age = 40 print("Hello, " + name) # f strings name = "Bob" print(f"Hello, {name}") # collections # create an empty list? lst1 = [] # lst1 = list() # create a list with numbers 1, 2, 3, 4, 5 lst2 = [1, 2, 3, 4, 5] # add an element 24 to lst1 lst1.append(24) # print all values in lst2 for n in lst2: print(n) for (i, n) in enumerate(lst2): print(f"Element {i} is {n}") # while loop i = 0 while i < len(lst2): print(lst2[i]) i += 1 # List Comprehensions # Create a new list containing the squares of all values in 'numbers' numbers = [1, 2, 3, 4, 5] print(numbers) squares = [n**2 for n in numbers] print(squares) squares = [num * num for num in numbers] squares = [1, 4, 9, 16, 25] print(squares) squares = [] for num in numbers: squares.append( num * num ) print(squares) # Filtering with a list comprehension # create a new list of even numbers using the values of the numbers list as inputs numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [n for n in numbers if n % 2 == 0] print(evens) evens = [] for n in numbers: if n % 2 == 0: evens.append(n) print(evens) # create a new list containing only the names that start with 's' make sure they are capitalized (regardless of their original case) names = ['Patrick', 'Melquisedeque', 'Bob', 'steve', 'Sam', 'frank', 'shawn'] s_names = [name.capitalize() for name in names if name[0].lower() == 's'] print(s_names) # Dictionaries # Create a new dictionary d1 = dict() d1 = {} d2 = { 'name': 'Tom', 'age': 40 } # access an element via its key print(d2['name']) # iterate over dict for key in d2: print(f'{key} is {d2[key]}') for (k, v) in d2.items(): print(k) print(v)
true
665e20a76c940043340a84f48abec890420458e0
App-Dev-League/intro-python-course-jul-2020
/Session7/NestedLoops/main.py
279
4.1875
4
#Nested Loops for i in range(5): for j in range(5): print(f"The value of i is {i} and the value of j is {j}") #Nested lists and loops table = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(table) for row in table: print(row) for col in row: print(col)
true
30238131f2827d86fe4f530b1c7b39600c2dbdc4
App-Dev-League/intro-python-course-jul-2020
/Session2/DataTypes/strings.py
473
4.1875
4
#Strings name = "Krish" print(name) print(type(name)) #Indexing and Slicing print(name[0]) print(name[4]) print(name[2:4]) #get characters from 2 to 4 (not included) print(name[-1]) #gets last index print(name[-2]) #gets second to last index print(name[:]) #gets whole string #Length print(len(name)) #Common String methods print(name.index("K")) print(name.replace("Krish", "Bob")) #these give copies and does not modify name print(name.lower()) print(name.upper())
true
7aa74118c759dff5f3ac767deaf623dfcae7b411
Yesidh/holbertonschool-web_back_end
/0x00-python_variable_annotations/5-sum_list.py
516
4.28125
4
#!/usr/bin/env python3 """ =============================================================================== a type-annotated function sum_list which takes a list input_list of floats as argument and returns their sum as a float. =============================================================================== """ from typing import List def sum_list(input_list: List[float]) -> float: """ :param input_list: list with float elements :return: the sum of its elements """ return sum(input_list)
true
6b04ab4f3a44d03cf78390e3f85deeb8af7c0cc6
DikranHachikyan/CPYT210409-PLDA
/ex55.5.py
669
4.15625
4
# 1. дефиниция на клас class Point: # Конструктор на класа def __init__(self): print('Point Ctor') # данни класа self.x = 20 self.y = 30 # Методи на класа def draw(self): print(f'draw point at: ({self.x},{self.y})') if __name__ == '__main__': # 2. декларация на променлива от типа # клас - Point, обект - p, p1 p = Point() p1 = Point() p1.x = 2 p1.y = 4 print(f'Point:({p.x}, {p.y})') print(f'Point 1:({p1.x}, {p1.y})') p.draw() p1.draw() print('--- ---')
false
6e74663f896df96e049596bcd6c2962c7a5b3767
hombreamarillo/aprendo_python
/01-FuncionesBasicos.py
942
4.28125
4
# Repaso de el tema de Funciones """ este block de trabajo es para aprender todo sobre lso metodos en python ya que estory aprendiedo a usar este en programación orientada a objetos """ print("Comensamos con el uso de Funciones") divisas = {"PEN": 3.256, "MXN": 20, "PESO": 3745.41} def definir_tipo_cambio(tipo_moneda, valor_cambio): divisas[tipo_moneda] = valor_cambio return def convertir(monto_inicial, tipo_moneda="PESO"): valor = divisas.get(tipo_moneda) monto_final = monto_inicial * valor return monto_final print("Ingrese la moneada y el valor del cambio separados por (,)") texto = str(input()).split(",") moneda = texto[0] valor_cambio = float(texto[1]) definir_tipo_cambio(moneda, valor_cambio) print("Ingrese el monto de Dinero a convertir de " + moneda + " a USD") monto = float(input()) resultado = convertir(monto, moneda) print(str(monto) + " " + str(moneda) + " en USD es " + str(resultado))
false
d0c5db82d901898df3259ef51bcfc03de773eeee
PatrickJCorbett/MSDS-Bootcamp-Module-5
/module5_python.py
2,777
4.34375
4
#first just a test, print "hello world" print("hello world") ##Exercise 1: print the time #import the datetime function from the datetime package from datetime import datetime #put the current time into a variable now = datetime.now() #print the current time print(now) ##Exercise 2: simple stopwatch #Create the stopwatch as a function #import the time package, needed to perform a time delay import time def Stopwatch(seconds): #Set the Start_Time before waiting Start = datetime.now() #wait the number of seconds defined by the seconds argument time.sleep(seconds) End = datetime.now() return(Start, End) #Run Stopwatch for 10 seconds and store the output in End_Time Start_Time, End_Time = Stopwatch(10) print(Start_Time) print(End_Time) #Calculate the time elapsed in the stopwatch. Should be equal to the seconds argument used, plus a couple milliseconds Elapsed = End_Time - Start_Time print(Elapsed) ##Exercise 3: Print a word provided by the user def printword(): word = input("Enter word: ") print(word) printword() ##Exercise 4: Ask for user input and validate that it is a word #First, will need a dictionary of words to validate against. Can use the nltk library (natural language toolkit) import nltk nltk.download('words') from nltk.corpus import words #'words' is a corpus, use set to convert to a list. Set converts any iterable (which a corpus is) to a sequence english_words = set(words.words()) #define function to ask for user input, check if it is in english_words, and return the outcome def uservalidate(): #ask user for input word = input("Enter input: ") #convert to lowercase to match the english_words format word_lower = word.lower() #if statement: if word_lower is part of the list, say so, otherwise say it isn't if word_lower in english_words: print("{} is an English word!".format(word)) else: print("{} is not an English word...".format(word)) uservalidate() ##Exercise 5: Print list of user inputs #function to ask user for num_inputs number of words and then print them all def userlist(num_inputs): #initialize final list of user inputs as a blank list userinputs = [] #for loop for user to input num_inputs number of inputs for i in range(0, num_inputs): #this range is used because Python is zero-indexed #ask the user to put in word i (I use i + 1 because Python is zero indexed but it sounds better to ask "enter word 1" than "enter word 0") word = input("Enter Word {}:".format(i + 1)) #use the .append method on the userinputs list to add word i userinputs.append(word) for i in range(0, num_inputs): print(userinputs[i]) #Test with three inputs (I used "here" "we" "go") userlist(3)
true
da4610110e6e7e580e52700b9fbe42c6f6fa0a19
Nirvighan/Python-C100-Project-
/ATM.py
1,231
4.125
4
# CREATE THE CLASS class ATM(object): #CREATE __INIT__ FUNCTION #IT IS SAME LIKE CONSTRUCTO IN JAVA def __init__(self,name,age,cardNumber,PIN,TotalAmount): #USE SELF #IT IS SAME LIKE THIS IN JAVA self.name = name self.age = age self.cardNumber = cardNumber self.PIN = PIN self.TotalAmount = TotalAmount #CREATE SOME FUNCTIONS def EnterCardNumber(self): print("ENTER CARD NUMBER") def EnterPIN(self): print("ENTER PIN") def TotalBalance(self): print("RS. 500000") def Withdraw(self): print("AMOUNT WITHDRAW SUCCESSFUL") def Add(self): print("AMOUNT ADDED SUCESSFULLY") #CREATE SOME OBJECTS AND CALL THE CLASS FUNCTIONS #SHOW THE FUNCTIONS USING PRINT person1 = ATM("RAHUL ARORA",34,"1576XXXXXX98","2*****9","$80,000") print(person1.EnterCardNumber()) print(person1.EnterPIN()) print(person1.TotalBalance()) print(person1.Withdraw()) print(person1.Add()) person2 = ATM("GEORGE SUTHERLAND",22,"2400XXXXXX89","6********2","$44,000") print(person2.EnterCardNumber()) print(person2.EnterPIN()) print(person2.TotalBalance()) print(person2.Withdraw()) print(person2.Add())
true
057ed18abae64e416e94891e2c1bdb530ff20db9
jigsaw2212/Understanding-Regular-Expressions
/RedEx_findall.py
971
4.6875
5
#findall() function for regular expressions finds all the matches of the desrired pattern in a string, and returns them as a list of strings #findall automatically does the iteration import re #Suppose we have a list with many email addresses str = 'purple alice-b@google.com, blah monkey bob@abc.com blah dishwasher' emails=[] emails = re.findall(r'[\w.-]+@[\w.-]+', str) print emails #How about :- emails = re.findall(r'([\w.-]+)@([\w.-]+)',str) #Will return tuples for name in emails: print name[0] #to access the part one of each tuple print name[1] #t0 access part 2 of each tuple #Will give an output like:- #('alice-b', 'google.com') #('bob', 'abc.com') #---------------------------------------------------------------- #Just something I discovered while fooling around in Python, probably the easiest way of pattern searching. Yet to explore this fully. if 'c' in 'abcdecf': print 'hello' #WORKS! Python, you are magic! *_*
true
893b3c73e03bb2d07fd0d2b6fa1da8cf1b8dd6ef
vanigupta20024/Programming-Challenges
/CaesarCipher.py
1,468
4.40625
4
''' Caesar cipher: Encryption technique also called the shift cipher. Each letter is shifted with respect to a key value entered. ''' print("Enter 0 for encryption and 1 for decryption:") n = int(input()) enc_text = "" print("Enter the input string: ", end = "") text = input() print("Enter key: ", end = "") key = int(input()) if n == 0: # encryption process for index in range(len(text)): # checking if element is an alphabet if text[index].isalpha(): if text[index].isupper(): temp = (ord(text[index]) - ord('A') + key) % 26 + ord('A') enc_text += chr(temp) elif text[index].islower(): temp = (ord(text[index]) - ord('a') + key) % 26 + ord('a') enc_text += chr(temp) else: # if not alphabet, simply append without changes enc_text += text[index] print("Old text: {0}\nEncrypted text: {1}".format(text, enc_text)) if n == 1: # decryption process for index in range(len(text)): # checking if element is an alphabet if text[index].isalpha(): if text[index].isupper(): temp = (ord(text[index]) - ord('A') - key) if temp < 0: temp += 26 temp += ord('A') enc_text += chr(temp) elif text[index].islower(): temp = (ord(text[index]) - ord('a') - key) if temp < 0: temp += 26 temp += ord('a') enc_text += chr(temp) else: # if not alphabet, simply append without changes enc_text += text[index] print("Old text: {0}\nDecrypted text: {1}".format(text, enc_text))
true
05bed03f2a6c548af9c820ec4872c7ec36c168e8
vanigupta20024/Programming-Challenges
/FindHighestAltitude.py
684
4.125
4
''' There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. Example 1: Input: gain = [-5,1,5,0,-7] Output: 1 Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. ''' class Solution: def largestAltitude(self, gain: List[int]) -> int: for i in range(1, len(gain)): gain[i] += gain[i - 1] if max(gain) < 0: return 0 return max(gain)
true
de4d4235835ca1b871af439494367b2119c909d9
vanigupta20024/Programming-Challenges
/ReshapeTheMatrix.py
1,279
4.34375
4
''' You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Example 2: Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] ''' class Solution: def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]: num_of_rows = len(nums) num_of_columns = len(nums[0]) if num_of_rows * num_of_columns != r * c: return nums matrix = [] row = col = 0 for row_index in range(r): temp = [] for col_index in range(c): if col >= num_of_columns: col = 0 row += 1 num = nums[row][col] col += 1 temp.append(num) matrix.append(temp) return matrix
true
a64ffa6636d8f087557f9acb8ebe9c08c98226d6
vanigupta20024/Programming-Challenges
/RevVowelsOfString.py
625
4.15625
4
''' Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases. Example 1: Input: s = "hello" Output: "holle" ''' class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] s = list(s) l, h = 0, len(s) - 1 while l < h: if s[l] not in vowels: l += 1 elif s[h] not in vowels: h -= 1 else: s[l], s[h] = s[h], s[l] l += 1 h -= 1 return "".join(s)
true
98054d8c3947eca001b99d37f491cc0205878bf9
corvolino/estudo-de-python
/Atividades-Estrutura-Sequencial/atividade11.py
738
4.28125
4
''' Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo. ''' numero1 = int(input("\nInforme o primeiro número: ")) numero2 = int(input("Informe o segundo número: ")) numero3 = float(input("Informe o terceiro número: ")) primeiro = (pow(numero1, 2)) * (numero2 / 2) segundo = (pow(numero1, 3)) + (pow(numero3, 3)) terceiro = pow(numero3, 3) print("\nProduto do dobro do primeiro com metade do segundo = {:.2f}".format(primeiro)) print("Soma do triplo do primeiro com o terceiro = {}".format(segundo)) print("Terceiro elevado ao cubo = {:.2f}".format(terceiro))
false