blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e4b5f7e681c9d120db28b00022e9a90d36bf3014
ruthiler/Python_Exercicios
/Desafio081.py
778
4.15625
4
# Desafio 081: Crie um programa que vai ler vários números # e colocar em uma lista. Depois disso, mostre: # A) Quantos números foram digitados. # B) A lista de valores, ordenada de forma decrescente. # C) Se o valor 5 foi digitado e está ou não na lista. lista = [] while True: num = int(input('Digite um numero: ')) lista.append(num) cont = ' ' while cont not in 'SsNn': cont = str(input('Deseja Continuar? [S/N] ')).strip().upper()[0] if cont in 'Nn': break print('~' * 50) print('Você digitou {} números.'.format(len(lista))) lista.sort(reverse=True) print('Os valores em ordem descrescente são {}'.format(lista)) if 5 in lista: print('O número 5 esta na lista!') else: print('O número 5 não foi encontrado na lista!')
false
ae1562f866cb8c54589f22867ba55c460fde26b3
keshavsingh4522/Data-Structure-and-Algorithm
/prefix infix postfix/prefix_to_postfix.py
689
4.21875
4
''' Algorith: - Read the Prefix expression in reverse order (from right to left) - If the symbol is an operand, then push it onto the Stack - If the symbol is an operator, then pop two operands from the Stack - Create a string by concatenating the two operands and the operator after them. - string = operand1 + operand2 + operator - And push the resultant string back to Stack - Repeat the above steps until end of Prefix expression. ''' prefix=input('Enter Prefix Operation: ') operators='-+/*%^' postfix='' stack=[] for i in prefix[::-1]: if i in operators: x1=stack.pop() x2=stack.pop() stack.append(x1+x2+i) else: stack.append(i) print(*stack)
true
561ee4fb8b21c6eb2b2a3e0d9faab32145c58318
jain7727/html
/2nd largest.py
278
4.25
4
num1=int(input("enter the first no")) num2=int(input("enter the second no")) num3=int(input("enter the third no")) print(num1,num2,num3) if(num1>num2>num3): print("2nd largest no is ", num2) elif(num2>num3>num1): print("2nd largest no is ", num3) else: print(num1)
true
aeacf45d361391794fdb3966e1a5ee11942601cc
Christasen/CSCI1133_FALL2017
/lab2/olympics.py
598
4.4375
4
import turtle turtle.pensize(10) def drawcircle(radius): turtle.circle(radius) radius1 = int(input("Enter the radius of the circle: ")) turtle.color("black") drawcircle(radius1) turtle.color("red") turtle.penup() turtle.forward(128) turtle.pendown() drawcircle(radius1) turtle.color("blue") turtle.penup() turtle.backward(256) turtle.pendown() drawcircle(radius1) turtle.color("green") turtle.penup() turtle.forward(150) turtle.right(90) turtle.pendown() drawcircle(radius1) turtle.color("yellow") turtle.penup() turtle.left(120) turtle.backward(87) turtle.pendown() drawcircle(radius1)
false
ce82b959a4c69edd5f154945200738d35e89461f
delroy2826/Programs_MasterBranch
/Iterator.py
419
4.125
4
#1 l=[1,2,3,4,5] a=iter(l) print(next(a)) print(next(a)) #2 l=[1,2,3,4,5] a=iter(l) print(*a) #3 l=[1,2,3,4,5] a=iter(l) for i in range(len(l)): print(next(a)) #4 l=[1,2,3,4,5,6] a=iter(l) while True: try: print(next(a)) except Exception: break #5 l=[1,2,3,4,5,6] a=iter(l) for i in l: print(2**next(a)) #6 a = iter(int,2) print(next(a)) print(next(a)) print(next(a)) print(next(a))
false
18d1349155c4a17df235d6ef2a6adbaefd711cf8
delroy2826/Programs_MasterBranch
/regular_expression_excercise.py
2,675
4.59375
5
#1 Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9). import re def check(str1): match = pattern.search(str1) return not bool(match) pattern = re.compile(r'[^\w+]') str1 = "delro3y1229" print(check(str1)) str1 = "delro#3y1229" print(check(str1)) #Solution from web import re def is_allowed_specific_char(string): charRe = re.compile(r'[^a-zA-Z0-9.]') string = charRe.search(string) return not bool(string) print(is_allowed_specific_char("ABCDEFabcdef123450")) print(is_allowed_specific_char("*&%@#!}{")) #2 Write a Python program that matches a string that has an (a ) followed by (zero or more b's) import re str1 = "abbc" pattern = re.compile(r'ab*') match = pattern.finditer(str1) for i in match: print(i) import re def check(str1): pattern=r'ab*' if re.search(pattern,str1): print("Found Match") else: print("Not Found Match") check("ab") check("cb") check("abbbbb") check("abbwww") #3 Write a Python program that matches a string that has an (a) followed by (one or more b's) import re str1 = "abcs" pattern = re.compile(r'ab+') match = pattern.finditer(str1) for i in match: print(i) import re def check(str1): pattern = r'ab+' if re.search(pattern,str1): print("Found Match") else: print("Not Found") check("ab") check("cb") check("abbbbb") check("a") #4 Write a Python program that matches a string that has an a followed by zero or one 'b' import re def check(str1): pattern = re.compile(r'ab?') if re.search(pattern,str1): print("Match") else: print("No Match") l = ['ab','abc','abbc','aabbc','qwe'] for i in l: check(i) #5 Write a Python program that matches a string that has an a followed by three 'b' import re def check(str1): pattern = re.compile(r'ab{3,}') if re.search(pattern,str1): print("Match") else: print("No Match") l = ['ab','abbb','aabbbbbc','aabbbc','qwe'] for i in l: check(i) #6 Write a Python program that matches a string that has an a followed by two to three 'b' import re def check(str1): pattern = re.compile(r'ab{2,3}?') if re.search(pattern,str1): print("Match") else: print("No Match") l = ['ab','abbb','aabbbbbc','aabbbc','qwe'] for i in l: check(i) #7 Write a Python program to find sequences of lowercase letters joined with a underscore. import re def check(str1): pattern = re.compile(r'^[a-z]+_[a-z]+$') if re.search(pattern,str1): print("Match") else: print("No Match") l = ['aab_cbbbc','aab_Abbbc','Aaab_abbbc'] for i in l: check(i)
true
685b6d24ea305987969e83fd0c892c1a4c81c730
delroy2826/Programs_MasterBranch
/pynative10.py
781
4.21875
4
#Question 10: Given a two list of ints create a third list such that should #contain only odd numbers from the first list and even numbers from the second list def merge_even_odd(listOne,listTwo): l=[] for i in listOne: if i%2!=0: l.append(i) for i in listTwo: if i%2==0: l.append(i) return l listOne = [10, 20, 23, 11, 17] listTwo = [13, 43, 24, 36, 12] print(merge_even_odd(listOne,listTwo)) '''l = [i for i in listOne if i%2!=0] l2 = [i for i in listTwo if i%2==0] print(l+l2)''' listOne = [10, 20, 23, 11, 17] listTwo = [13, 43, 24, 36, 12] new_list = [] for i in range(len(listOne)): if listOne[i]%2!=0: new_list.append(listOne[i]) if listTwo[i]%2==0: new_list.append(listTwo[i]) print(new_list)
false
bb4387856d4d8d6e7d993d228cd87988a69ad828
delroy2826/Programs_MasterBranch
/Encapsulation.py
1,787
4.125
4
#1 class Student(): def __init__(self): self.name=input("Enter The Name:") self.__grade = "A+" def display(self): print("Name: {} ".format(self.name)) print("Grade: {}".format(self.__grade)) s=Student() s.display() #2 class Student(): def __init__(self,__grade): self.name=input("Enter The Name:") self.__grade = "A+" def display(self): print("Name: {} ".format(self.name)) print("Grade: {}".format(self.__grade)) s=Student("B+") s.display() #3 class Student(): def __init__(self): self.name=input("Enter The Name:") self.__grade = "A+" def display(self): print("Name: {} ".format(self.name)) print("Grade: {}".format(self.__grade)) def change(self): self.__grade="B+" s=Student() s.change() s.display() #4 class Product(): def __init__(self): self.__price = 1000 def selling(self): print("Selling Price: ",self.__price) def change(self): self.__price=int(input()) p=Product() p.selling() #5 class Product(): def __init__(self): self.__price = 1000 def selling(self): print("Selling Price: ",self.__price) def change(self): self.__price=int(input()) p=Product() p.change() p.selling() #6 class Product(): def __init__(self): self.price = 1000 def selling(self): print("Selling Price: ",self.price) def change(self): self.price=int(input()) p=Product() p.price="800" p.selling() #8 class Product(): __price = 100 def __init__(self): self.__price = int(input()) def selling(self): print("Selling Price: ",Product.__price) def change(self): self.price=int(input()) p=Product() p.__price="800" p.selling()
false
d4352cfdd84a15f13d8c17ce5e69d6f20b0d3952
delroy2826/Programs_MasterBranch
/pynativedatastruct5.py
277
4.21875
4
#Given a two list of equal size create a set such that it shows the element from both lists in the pair firstList = [1, 2, 3, 4, 5] secondList = [10, 20, 30, 40, 50] new_list = [] for i in range(len(firstList)): new_list.append((firstList[i],secondList[i])) print(new_list)
true
7df218023262b52b2f34d6fc0700debb4579b7e7
samirdave1992/Learn-Python-3-the-hard-way
/Dictionaries.py
1,073
4.25
4
person={'name':'Noma','Age': 37,'height':5*12+5 } print(person['name']) print(person['Age']) person['city']="DFW" print(person['city']) print(person) ##Lets do some dictionaries for states states={ 'Oregon':'OR', 'Florida':'FL', 'Texas':'TX', 'California':'CA', 'New York':'NY' } #Cities cities={ 'CA':'San Francisco', 'TX':'Dallas', 'OR':'Portland' } #adding some cities cities['NY']='New York' cities['FL']='Florida' print('--' * 10) print("TX State had: ", cities['TX']) print("OR State had: ", cities['OR']) print("Florida state is abbrevated as : ", states['Florida']) print("New York state is abbrevated as : ", states['New York']) #Print using loops print('--' * 10) for states,abbrev in list(states.items()): print(f"State {states} is abbrevated as {abbrev}") for abbrev,cities in list(cities.items()): print(f"{abbrev} has the city {cities}") print('--' * 10) for states,abbrev in list(states.items()): print(f"state {states} is as {abbrev}") print(f"and has city {cities[abbrev]}")
false
a47908baf91fad4982439dfd1c66059761aa92e4
catliaw/hb_coding_challenges
/concatlists.py
1,054
4.59375
5
"""Given two lists, concatenate the second list at the end of the first. For example, given ``[1, 2]`` and ``[3, 4]``:: >>> concat_lists([1, 2], [3, 4]) [1, 2, 3, 4] It should work if either list is empty:: >>> concat_lists([], [1, 2]) [1, 2] >>> concat_lists([1, 2], []) [1, 2] >>> concat_lists([], []) [] """ def concat_lists(list1, list2): """Combine lists.""" # can create new list that is first list, then loop through 2nd list # and append on each item in 2nd list, ### actually can just loop through 2nd list and append to first list. ### do not need 3rd list. # but can just combine using the + operator, which combines sequences ### this is probably doing the same thing as looping through 2nd list, ### append to 1st list under the hood. for item in list2: list1.append(item) return list1 # return list1 + list2 if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. GO YOU!\n"
true
fb218791404f9ab8db796661c91e1ab0097af097
yu-shin/yu-shin.github.io
/downloads/code/LeetCode/Array-Introduction/q977_MergeSort.py
1,533
4.5
4
# Python3 program to Sort square of the numbers of the array # function to sort array after doing squares of elements def sortSquares(arr, n): # first dived array into part negative and positive K = 0 for K in range(n): if (arr[K] >= 0 ): break # Now do the same process that we learn # in merge sort to merge to two sorted array # here both two half are sorted and we traverse # first half in reverse meaner because # first half contain negative element i = K - 1 # Initial index of first half j = K # Initial index of second half ind = 0 # Initial index of temp array # store sorted array temp = [0]*n while (i >= 0 and j < n): if (arr[i] * arr[i] < arr[j] * arr[j]): temp[ind] = arr[i] * arr[i] i -= 1 else: temp[ind] = arr[j] * arr[j] j += 1 ind += 1 ''' Copy the remaining elements of first half ''' while (i >= 0): temp[ind] = arr[i] * arr[i] i -= 1 ind += 1 ''' Copy the remaining elements of second half ''' while (j < n): temp[ind] = arr[j] * arr[j] j += 1 ind += 1 # copy 'temp' array into original array for i in range(n): arr[i] = temp[i] # Driver code arr = [-6, -3, -1, 2, 4, 5 ] n = len(arr) print("Before sort ") for i in range(n): print(arr[i], end =" " ) sortSquares(arr, n) print("\nAfter Sort ") for i in range(n): print(arr[i], end =" " )
true
f063661003366dcd4a6038aecd597fe3376daf88
PrithviSathish/School-Projects
/AscendingOrder.py
745
4.21875
4
num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) num3 = int(input("Enter num3: ")) if num1 < num2: if num1 < num3: print(num1, end=" << ") if num2 < num3: print(num2, end=" << ") print(num3) else: print(num3, end= " << ") print(num2) else: print(num3, end=" << ") print(num1, end=" << ") print(num2) else: if num2 < num3: print(num2, end=" << ") if num1 < num3: print(num1, end=" << ") print(num3) else: print(num3, end=" << ") print(num1) else: print(num3, end=" << ") print(num2, end=" << ") print(num1) print()
false
ae8a8fe70d16bd05d33c7f85b399699f737c2cba
PrithviSathish/School-Projects
/LargestNumber.py
292
4.21875
4
x = float(input("Enter the value of x: ")) y = float(input("Enter the value of y: ")) z = float(input("Enter the value of z: ")) if x > y and x > z: print("x is the greatest number") elif y > x and y > z: print("Y is the greatest number") else: print("z is the greatest number")
false
fb9f96fd4b3a3becd84531f4d07748c13bf6706d
kawing-ho/pl2py-ass1
/test01.py
268
4.53125
5
#!/usr/bin/python3 # Use of "#" character in code to mimic comments for x in range(0,5): print("This line does't have any hash characters :)") #for now print("but this one does! #whatcouldgowrong ? ") #what happens here ? print("I love '#'s") and exit(ord('#'))
true
71b552431f56fea84e1062924a6c1782449fe976
PrechyDev/Zuri
/budget.py
1,882
4.1875
4
class Budget: ''' The Budget class creates budget instances for various categories. A user can add funds, withdraw funds and calculate the balance in each category A user can also transfer funds between categories. ''' ##total balance for all categories total_balance = 0 @classmethod def net_balance(cls): print(f'The net balance of your budgets is {cls.total_balance}') def __init__(self, category): self.name = category self.balance = 0 def deposit(self): amount = int(input(f'How much do you want to deposit for {self.name}\n')) self.balance += amount Budget.total_balance += amount print(f'Your current budget for {self.name} is {self.balance} ') def withdraw(self): amount = int(input(f'How much do you want to withdraw from your {self.name} account?\n')) self.balance -= amount Budget.total_balance -= amount print(f'You just withdrew {amount}, you have {self.balance} left in your {self.name} account') def transfer(self, other): amount = int(input(f'How much do you want to transfer to your {other.name} account?\n')) self.balance -= amount other.balance += amount print('Transfer successful!') print(f'You have left in {self.balance} in your {self.name} account and {other.balance} in your {other.name} account') def check_balance(self): print(f'You have {self.balance} remaining in your {self.name} account') ## categories #food = Budget('Food') #transport = Budget('Transportation') #clothing = Budget('Clothing') #entertain = Budget('Entertainment') #bills = Budget('Bills') #rent = Budget('Rent') #other = Budget('Others') ##tests #food.deposit() #food.withdraw() #food.check_balance() #bills.deposit() #Budget.net_balance() #food.transfer(rent)
true
c6d42c4b71ff23b766ba511a8d808176b33dc442
sebdelas/Alyra-Excercice-1.1.3
/1.1.3.py
570
4.1875
4
#!/usr/bin/env python3 def is_palindrome(mot): inverse = ''; for i in reversed(range(0,len(mot))): if (mot[i] != " "): inverse = inverse + mot[i] saisie_sans_espace = mot.replace(" ", "") if (inverse == saisie_sans_espace): return True else: return False saisie = input("Saisissez un mot ou une phrase, le programme va vérifier si c'est un palindrome : ") if (is_palindrome(saisie)): print ("Le mot ou phrase saisi est un palindrome") else: print ("Le mot ou phrase saisi n'est pas un palindrome")
false
d30896b9eb8a8bf8f73d05439906a5fd1a5c1973
Weyinmik/pythonDjangoJourney
/dataTypeNumbers.py
581
4.21875
4
""" We have integers and floats """ a = 14 print(a) b = 4 print(b) print(a + b) # print addition of a and b, 18. print(a - b) # print subtraction of a and b, 10. print(a * b) # print multiplication of a and b, 56. print(a / b) # print division of a and b in the complete decimal format, -3.5. print(a // b) # print division of a and b but ignores everything after the decimal point, -3. print(a % b) # Only print the remainder value as a result of the division, -2. print(2+10*10+3) #Result:105 print(5 + 20 / 4 * 2 - 7) #Rsult:8.0
true
f7e5cd52ac7324617717081db83c6b849f5fab32
katecpp/PythonExercises
/24_tic_tac_toe_1.py
546
4.125
4
#! python3 def readInteger(): value = "" while value.isdigit() == False: value = input("The size of the board: ") if value.isdigit() == False: print("This is not a number!") return int(value) def printHorizontal(size): print(size * " ---") def printVertical(size): print((size + 1) * "| ") def drawBoard(size): for i in range(size): printHorizontal(size) printVertical(size) printHorizontal(size) if __name__=="__main__": size = readInteger() drawBoard(size)
true
c6ff43950f21b27f9c3dd61cf3d6840748ad2864
katecpp/PythonExercises
/11_check_primality.py
515
4.21875
4
#! python3 import math def readInteger(): value = "" while value.isdigit() == False: value = input("Check primality of number: ") if value.isdigit() == False: print("This is not a number!") return int(value) def isPrime(number): upperBound = int(math.sqrt(number)) for d in range(2, upperBound+1): if number % d == 0: return False return True value = readInteger() print(str(value) + (" is " if isPrime(value) else " is not ") + "prime")
true
d849a589929e610b588067d845bfcf182ca5b3b5
Legoota/PythonAlgorithmTraining
/Sorts/mergesort.py
572
4.125
4
def mergesort(array): if len(array) < 2: return array center = len(array)//2 left, right = array[:center], array[center:] left = mergesort(left) right = mergesort(right) return mergelists(left, right) def mergelists(left, right): result = [] while len(left) > 0 and len(right) > 0: if(left[0] <= right[0]): result.append(left.pop(0)) else: result.append(right.pop(0)) while left: result.append(left.pop(0)) while right: result.append(right.pop(0)) return result
true
1a76893e4c43f750bc68c1f023c65f013a919035
muslinovsultan/ekzamen
/zadachi.py
2,291
4.21875
4
class CoffeeMachine: def __init__(self, milk,coffee,sugar): self.milk = milk self.coffee = coffee self.sugar = sugar def make_coffee(self,milk,coffee,sugar): if milk > self.milk and coffee > self.coffee and sugar > self.sugar: min = milk - self.milk min2 = coffee - self.coffee min3 = sugar - self.sugar print(f"Не достаточно \n молока-{min}\n кофе-{min2}\n сахара-{min3}") elif milk > self.milk and coffee > self.coffee and sugar < self.sugar: min = milk - self.milk min2 = coffee - self.coffee print(f"Не достаточно молока-{min} и кофе-{min2}") elif milk > self.milk and coffee < self.coffee and sugar > self.sugar: min = milk - self.milk min2 = coffee - self.coffee print(f"Не достаточно молока-{min} и сахара-{min2}") elif milk < self.milk and coffee > self.coffee and sugar > self.sugar: min = sugar - self.sugar min2 = coffee - self.coffee print(f"Не не достаточно кофе-{coffee} и сахара-{sugar}") elif milk > self.milk and coffee < self.coffee and sugar < self.sugar: min = milk - self.milk print(f"Не достаточно молока-{min}") elif milk < self.milk and coffee > self.coffee and sugar < self.sugar: min = coffee - self.coffee print(f"Не достаточно кофе-{min}") elif milk < self.milk and coffee < self.coffee and sugar > self.sugar: min = sugar - self.sugar print(f"Не достаточно сахара-{min}") elif milk < self.milk and coffee < self.coffee and sugar < self.sugar: self.__substract_milk(milk) self.__substract_coffee(coffee) self.__subtsract_sugar(sugar) print(f"Кофе готов \nмолока-{self.milk}\nкофе-{self.coffee}\nсахара{self.sugar}") def __substract_milk(self,milk): self.milk -= milk def __substract_coffee(self,coffee): self.coffee -= coffee def __subtsract_sugar(self,sugar): self.sugar -= sugar def main(): coffemachine = CoffeeMachine(1000,1000,1000) coffemachine.make_coffee(1111,2222,3333) if __name__ == "__main__": main() def main(): coffemachine = CoffeeMachine(1000,1000,1000) coffemachine.make_coffee(222,444,666) if __name__ == "__main__": main()
false
8d42b48047fa49b956547b36a0ac234fe73a79e6
tlima1011/python3-curso-em-video
/ex063.py
624
4.1875
4
from ex063_fibonacci_packages import fibo_while, fibo_for print('-=' * 10) print(' FIBONACCI VS. 1.0') print('-=' * 10) while True: n1 = n3 = 0 n2 = 1 termos = int(input('Quantos termos: ')) op = int(input('''[ 1 ] - FIBONACCI COM FOR [ 2 ] - FIBONACCI COM WHILE [ 3 ] - SAIR Opção.: ''')) if op == 1: print(fibo_for(n1, n2, n3, termos)) elif op == 2: print(fibo_while(n1, n2, n3, termos)) elif op == 3: print('Saindo do programa') break else: print('Tenve novamente..., opção inváldia') print('FIM')
false
58451f498859eb61cd3e28d95915567432396483
avigautam-329/Interview-Preparation
/OS/SemaphoreBasics.py
842
4.15625
4
from threading import Thread, Semaphore import time # creating semaphore instance to define the number of threads that can run at once. obj = Semaphore(3) def display(name): # THis is where the thread acquire's the lock and the value of semaphore will decrease by 1. obj.acquire() for i in range(3): print("Hello from {}".format(name)) time.sleep(1) obj.release() t1 = Thread(target = display, args = ("Thread 1",)) t2 = Thread(target = display, args = ("Thread 2",)) t3 = Thread(target = display, args = ("Thread 3",)) t4 = Thread(target = display, args = ("Thread 4",)) t5 = Thread(target = display, args = ("Thread 5",)) t6 = Thread(target = display, args = ("Thread 6",)) t1.start() t2.start() t3.start() t4.start() t5.start() t6.start() # join() is not needed as we are not making a main function
true
839181892842d62b803ab6040c89f29a2718514e
chuducthang77/Summer_code
/front-end/python/project301.py
1,158
4.15625
4
#Project 301: Banking App #Class Based # Withdraw and Deposit # Write the transaction to a python file class Bank: def __init__(self, init=0): self.balance = init def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount account = Bank() while True: action = input("What action do you want to take - deposit (d) or withdraw (w): ") if action == 'd': amount = input('Enter amount you want to deposit: ') try: amount = float(amount) except: print("Not a proper amount") continue account.deposit(amount) with open('account.txt', 'a') as file: file.write(f"Deposit: {amount}\n") print(account.balance) elif action == 'w': amount = input('Enter amount you want to withdraw: ') try: amount = float(amount) except: print("Not a proper amount") continue account.withdraw(amount) with open('account.txt', 'a') as file: file.write(f"Withdraw: {amount}\n") print(account.balance)
true
798f3df4e5b30737ace8d3071d048a59745494e8
bjchu5/pythonSort
/insertionsort.py
1,848
4.5
4
def insertionsort_method1(aList): """ This is a Insertion Sort algorithm :param n: size of the list :param temp: temporarily stores value in the list to swap later on :param aList: An unsorted list :return: A sorted ist :precondition: An unsorted list :Complexity: Best Case is O(N), Worst Case is O(N^2) because this algorithm is able to exit the while loop early if it nearly sorted, insertion sort starts sorting from the beginning towards the end, so if one of the value in the list is bigger than the temporary value, it can exit early (assuming this is a true insertion sort algorithm). The worst case happens when the algorithm is sorted in reverse, the entire list will compare and swap. :Stability: Insertion sort is a stable sorting algorithm because the algorithm only swaps the compared value with the value before it and will not swap the position of similar value, making it unable to break the relative order. """ n = len(aList) for i in range(1, n): temp = aList[i] k = i - 1 while(k >= 0 and aList[k] > temp): aList[k+1] = aList[k] k-=1 aList[k+1] = temp def insertionsort_method2(aList): n = len(aList) for i in range(1, n): k = i-1 while k >= 0 and aList[k] > aList[k+1]: aList[k] , aList[k+1] = aList[k+1] , aList[k] k-=1 if __name__ == ("__main__"): list1 = [12, 44, 6, 7, 19, 4, 10, 18] list2 = [12, 44, 6, 7, 19, 4, 10, 18] insertionsort_method1(list1) insertionsort_method2(list2) print("Method 1: ", list1) print("Method 2: ", list2)
true
760aed2a0b0d6f2e8bdbaa3007527905670290f4
erichuang2015/PythonNotes
/code/023_常用模块/作业1.py
1,216
4.21875
4
# -*- coding: utf-8 -*- # @Time : 2020/1/5 15:33 # @Author : 童庆 # @FileName : 作业1.py # @Software : PyCharm import random # 数字验证码 def code(n=6): s = '' for i in range(n): num = random.randint(0,9) s += str(num) return s print(code(4)) print(code()) # 数字和字母验证码 def code(n=6): s = '' for i in range(n): # 生成随机的字母,数字各一个,再随机抽取 num = str(random.randint(0,9)) alpha_upper = chr(random.randint(65,90)) # 大写范围 小写从97开始 alpha_lower = chr(random.randint(97,122)) res = random.choice([num,alpha_upper,alpha_lower]) s += res return s print(code(4)) print(code()) # 前两个功能合并 def code(n=6, alpha=True): s = '' for i in range(n): # 生成随机的字母,数字各一个,再随机抽取 res = str(random.randint(0,9)) if alpha: alpha_upper = chr(random.randint(65,90)) # 大写范围 小写从97开始 alpha_lower = chr(random.randint(97,122)) res = random.choice([res,alpha_upper,alpha_lower]) s += res return s print(code(4)) print(code())
false
ed571b223307d9ccf5f43fcc1d1aa0469c213bbf
Dongmo12/full-stack-projects
/Week 5 - OOP/Day 3/exercises.py
666
4.34375
4
''' Exercise 1 : Built-In Functions Python has many built-in functions, and if you do not know how to use it, you can read document online. But Python has a built-in document function for every built-in functions. Write a program to print some Python built-in functions documents, such as abs(), int(), raw_input(). And add documentation for your own function ''' class Functions: '''This is great''' def raw_input(self): '''This is for raw_input''' def absolutes(self): '''This for abs operations''' def integers(self): '''This is for integers''' obj1 = Functions() raw_in = obj1.raw_input() print(Functions.__doc__)
true
fcb2f3f5194583a7162a38322303ab2945c8de79
Dongmo12/full-stack-projects
/Week 4 Python and web programming/Day 2/exercises.py
1,705
4.5
4
''' Exercise 1 : Favorite Numbers Create a set called my_fav_numbers with your favorites numbers. Add two new numbers to it. Remove the last one. Create a set called friend_fav_numbers with your friend’s favorites numbers. Concatenate my_fav_numbers and friend_fav_numbers to our_fav_numbers. # Solution my_fav_numbers = {12,16,20} print(my_fav_numbers) my_fav_numbers.add(30) print(my_fav_numbers) my_fav_numbers.add(15) print(my_fav_numbers) my_fav_numbers.pop() print(my_fav_numbers) my_fav_numbers.pop() print(my_fav_numbers) friend_fav_numbers = {"jeff","jose","Armand"} our_fav_numbers = my_fav_numbers.union(friend_fav_numbers) print(our_fav_numbers) ''' ''' Exercise 2: Tuple Given a tuple with integers is it possible to add more integers to the tuple? Answer: It would not be possible to add because a tuple is a collection which is ordered and unchangeable. ''' ''' Use a for loop to print the numbers from 1 to 20, inclusive. # Solution for num in range(1,21): print(num) ''' ''' Exercise 4: Floats Recap – What is a float? What is the difference between an integer and a float? Can you think of another way of generating a sequence of floats? Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence. #Solution float represent real numbers and are written with a decimal point dividing the integer and fractional parts. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed. ''' list = list(range(1,6) ) for x in list: print(x) x = x+0.5 print(x)
true
790e8b58ab3d9178d1468041d9f77b17c63fa8c1
Dongmo12/full-stack-projects
/Week 4 Python and web programming/Day 1/exercises.py
2,370
4.5
4
''' Exercise 4 : Your Computer Brand Create a variable called computer_brand that contains the brand of your computer. Insert and print the above variable in a sentence,like "I have a razer computer". # Solution computer_brand = "msi" print('I have a {} computer'.format(computer_brand)) ''' ''' Exercise 5: Your Information Create a variable called name, and give it your name as a value (text) Create a variable called age, and give it your age as a value (number) Create a variable called shoe_size, and give it your shoe size as a value Create a variable called info. Its value should be an interesting sentence about yourself, including your name, age, and shoe size. Use the variables you created earlier. Have your code print the info message. Run your code #Solution name = "jeff" age = 32 shoe_size = 40 info = "My name is {} and I am {} year old. My shoe size is {}. I can't change so just accept me as I am." print(info.format(name,age,shoe_size)) ''' ''' Exercise 6: Odd Or Even Write a script that asks the user for a number and determines whether this number is odd or even #solution val = int(input('Please, enter your name: ')) if val%2==0: print('{} is even'.format(val)) else: print('{} is odd'.format(val)) ''' ''' Exercise 7 : What’s Your Name ? Write a script that asks the user for his name and determines whether or not you have the same name, print out a funny message based on the outcome #Solution myName = 'Alexandra'.lower() userName = input("Please, enter your name:").lower() if userName==myName: print('{} we have the same name.'.format(userName)) else: print('{} sorry but we don t have the same name.'.format(userName)) ''' ''' Exercise 8 : Tall Enough To Ride A Roller Coaster Write a script that will ask the user for their height in inches, print a message if they can ride a roller coaster or not based on if they are taller than 145cm Please note that the input is in inches and you’re calculating vs cm, you’ll need to convert your data accordingly # Solution inches = int(input("Please enter your height in inches: ")) convert = int(inches*2.54) val = 145 if convert>val: print("You entered {} and you are {} cm so you can ride a roller coaster".format(inches, convert)) else: print("You entered {} and you are {} cm so you can't ride a roller coaster".format(inches, convert)) '''
true
edfcc0b98db78aa300f6cf4a804757129cf53321
harasees-singh/Notes
/Searching/Binary_Search_Bisect.py
947
4.125
4
import bisect # time complexities of bisect left and right are O(logn) li = [8, 10, 45, 46, 47, 45, 42, 12] index_where_x_should_be_inserted_is = bisect.bisect_right(li, 13) # 2 returned index_where_x_should_be_inserted_is = bisect.bisect_left(li, 46) # 4 returned print(index_where_x_should_be_inserted_is) print(bisect.bisect_right([2,6,3,8,4,7,9,4,6,1], 5)) # it returns 5 or in other words 5 should be inserted between 4 and 7 # seems like it starts checking from the center # note if list is not sorted then it will still work sorted_list = [1, 2, 2, 3, 4, 5, 6] print(bisect.bisect_right(sorted_list, 2), bisect.bisect_left(sorted_list, 2)) # note: you can get the count of 2 from the above info provided by the right and left bisect # since right bisect returns 3 and left one returns 1 it means there are 3-1 = 2 number of 2s present already in the list
true
c3231050b14c3767a075b52879b77843b9d4ce93
ericzhai918/Python
/LXF_Python/Function_test/func_positional_para.py
282
4.125
4
# 计算x的平方 def power(x): return x * x print(power(2)) # 如果要计算x的三次方,四次方呢?x*x*x,x*x*x*x这样显然很冗余 def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(5,2)) print(power(5,3))
false
7d19e951c93430142e5c3da607063dc5da602fb3
Deepak3211/python-_refresher
/assignment.py
1,058
4.21875
4
#Question 1 x=['Python','Java','Ruby'] x #Question 2 x=['Python','Java','Ruby'] y=['c++','c','php'] x+y #Question 3 x=['Deepak','Deepak','Rohan','Ayush'] x.count('Deepak') #Question 4 x=['Deepak','Deepak','Rohan','Ayush'] x.sort() x #Question 5 x=['Deepak','Deepak','Rohan','Ayush'] x.sort() x y=['Surya','Rock','Punk','Akki'] y.sort() y x+y #Question 6 numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 print("Number of even numbers :",count_even) print("Number of odd numbers :",count_odd) #Question 7 def Reverse(tuples): new_tup = tuples[::-1] return new_tup tuples = ('z','a','d','f','g','e','e','k') print(Reverse(tuples)) #Question 8 def daku(tuple): length = len(tuple) print("Largest element is:", tuple[length-1]) print("Smallest element is:", tuple[0]) tuple=[12, 45, 2, 41, 31, 10, 8, 6, 4] Largest = find_len(tuple) #Question 9 x='daku' x.upper() #Question 10 "9625657805".isdigit() #Question 11 x='Hello World' x.replace('World','Daku')
false
62b6bcd482dd774b75a816056a21247487f32b86
maindolaamit/tutorials
/python/Beginer/higher_lower_guess_game.py
1,519
4.3125
4
""" A sample game to guess a number between 1 and 100 """ import random rules = """ ========================================================================================================= = Hi, Below are the rules of the game !!!! = = 1. At the Start of the game, Program will take a random number between 1 and 100. = = 2. Then program will ask player to guess the number. You have to input the number you have guessed. = = 3. Program will then show you the results, if your guess is higher or lower. = ========================================================================================================= """ message = {'success': 'Congratulations !!!, You have guess it right', 'high': 'You have guessed a higher value.', 'low': 'Oops !! You have guess a lower value'} end_credits = """ Thanks for Playing !!! """ # Display the rules print rules play = input("Press 1 to Play the game\n") # Continue playing till user gives the input while play == 1: num = random.randint(1, 100) guess = input("\tEnter the number you have guessed : \t") msg = "\tProgram's Number : {} ,".format(num) if guess < num: print msg + message['low'] elif guess > num: print msg + message['high'] else: print msg + message['success'] # Check with User if he wants to play again play = input("\n\tPress 1 to Play again.\t") print(end_credits)
true
ecf870ac240d1faf8202039bcc235bdb14bb8440
vsandadi/dna_sequence_design
/generating_dna_sequences.py
2,007
4.28125
4
''' Function to generate DNA sequences for each bit string. ''' #initial_sequence = 'ATTCCGAGA' #mutation_list = [(2, 'T', 'C'), (4, 'C', 'A')] #bitstring = ['101', '100'] def generating_sequences(initial_sequence, mutation_list, bitstring): ''' Inputs: initial_sequence as a string of DNA bases mutation_list as list of tuples of mutation site (int), intial base (str), and mutation (str) bitstring as list of multiple strings of bits Returns: the list of final sequences ''' #Element is one bistring in the list bitstring final_sequence_list = [] for element in bitstring: #Raise AssertionError for invalid length of bitstring assert len(mutation_list) >= len(element), 'Number of mutations has to be greater than or equal to length of bitstring.' #Turning string inputs into lists for mutability sequence_list = list(str(initial_sequence)) #Sorting mutation_list by numerical order of mutation placement to match up to correct bitstring value mutation_list = sorted(mutation_list, key=lambda x: x[0]) #Zipping will pair each element of an index together #First bitstring will pair with first tuple #Mutation will iterate through each tuple in zip #Bit will iterate through each bitstring value for mutation,bit in zip(mutation_list, element): #Unwrapping elements in each tuple #Underscore indicates that variable (the original base) will not be needed mutation_position, _ , final_base = mutation if bit == '1': sequence_list[mutation_position] = final_base #Combines mutated DNA bases from list into a string new_sequence = "".join(sequence_list) final_sequence_list.append(new_sequence) return final_sequence_list
true
c94e9353f23c7b746c123d928db75e5474b1ca57
janetschel/exercises
/week_01/01_input-output/04_circle_circumference-and-surface-area.py
356
4.25
4
""" Schreibt ein Programm, welches den Umfang und den Flächeninhalt eines Kreises berechnet. Der Benutzer gibt den Radius an. """ PI = 3.141592653589793 radiusInput = input("Radius: ") radius = float(radiusInput) circumference = 2 * PI * radius surfaceArea = PI * radius ** 2 print(f"Umfang: {circumference}") print(f"Flächeninhalt: {surfaceArea}")
false
aa4d1e8e167031b5cf5637c76e25cc61e82a5fb0
r0ckyyr0cks/PycharmProjects
/Automation/PythonCode/LoopSyntax1.py
252
4.21875
4
# For loop with final range for i in range(10): print(i) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") # For loop with user input num = input("Please enter a number => ") for i in range(int(num)): print(i)
false
ac5f3db25ad77c00c62db5f2c7852e08a6f41fee
Tomaltach/Tutorials
/Python/Algorithms/find_peak.py
1,192
4.125
4
#demonstrate how to use a class with Tkinter class Application: """ Algorithms """ def __init__(self): """ Initialize the Program """ self.get_input() def get_input(self): """ Get user input """ input = raw_input('Enter numbers to be put into array using , to seperate numbers: ') self.numbers = map(int, input.split(',')) for i in range(0,len(self.numbers)): print self.numbers[i] self.find_peak_left_to_right(i) self.find_peak_center() def find_peak_left_to_right(self, i): """ Find the peak of an array """ print "->", i, "<-" if i == 0: if self.numbers[i] >= self.numbers[i+1]: print "First Peak Found!" elif i == len(self.numbers)-1: if self.numbers[i] >= self.numbers[i-1]: print "Last Peak Found!" else: if self.numbers[i] >= self.numbers[i-1] and self.numbers[i] >= self.numbers[i+1]: print "Peak Found!" def find_peak_center(self): """ Find the peak of an array """ if self.numbers(len(self.numbers)/2) > self.numbers(len(self.numbers)/2+1): print "left" elif self.numbers(len(self.numbers)/2) < self.numbers(len(self.numbers)/2+1): print "right" else: print "peak found" app = Application()
false
7562da63409e44a8a4a77032f0ad5a2bb611b1ca
summitkumarsharma/pythontutorials
/tut21.py
1,003
4.65625
5
# operators in python # 1.Arithmetic operators # 2.Assignment operators # 3.Comparison operators # 4.logical operators # 5.Identity operators # 6.Membership operators # 7.Bitwise operators # 1.Arithmetic operators # print("5 + 6 is =", 5+6) # print("5 - 6 is =", 5-6) # print("5 * 6 is =", 5*6) # print("5 / 6 is =", 5/6) # print("5 ** 3 is =", 5**3) # print("5 % 2 is =", 5%2) # print("5 // 6 is =", 15//6) # 2.Assignment operators x = 5 # print(x) x += 7 # x-=7 x*=7 x/=7 x%=7 # print(x) # 3.Comparison operators # i = 5 # print(i == 5) # print(i <= 5) # print(i >= 5) # print(i < 5) # print(i > 5) # print(i != 5) # 4.logical operators a = True b = False # print(a and b) # print(a or b) # print(a && b) - wrong # print(a || b) - wrong # 5.Identity operators a = True b = False # print(a is b) # print(a is not b) # 6.Membership operators list = [1, 2, 3, 4, 5] # print(1 in list) # print(2 not in list) # 7.Bitwise operators # 0-00 # 1-01 # 2-10 # 3-11 print(0 & 1) print(0 | 2)
false
18b3a779a6f144bf679eb47b8438b997e87f04ba
summitkumarsharma/pythontutorials
/tut28.py
752
4.1875
4
# file handling - write operation # f = open("test-write.txt", "w") # content = "To write to an existing file, you must add a parameter to the open()function" \ # "\n1.a - Append - will append to the end of the file \n2.w - Write - will overwrite any existing content" # no_of_chars = f.write(content) # print("File content is written ") # print("Number of Characters written - ", no_of_chars) # f.close() # # # f = open("test-write.txt", "a") # content = "\n3.r - open the file in read mode - default mode \n" \ # "4.w - open the file in write mode\n5.x - create file if not exits" # f.write(content) # print("content is appended") # f.close() f = open("test-write.txt", "r+") print(f.read()) f.write("\nEnd of file") f.close()
true
f07bddfa311a3cf735afe4d7e7f139a0bbe94c6c
KiikiTinna/Python_programming_exercises
/41to45.py
1,684
4.15625
4
#Question 41: Create a function that takes a word from user and translates it using a dictionary of three words, #returning a message when the word is not in the dict, # considering user may enter different letter cases d = dict(weather = "clima", earth = "terra", rain = "chuva") #Question 42: Print out the text of this file www.pythonhow.com/data/universe.txt. #Count how many a the text file has #Question 43:Create a script that let the user type in a search term and opens and search on the browser for that term on Google #Question 44: Plot the data in the file provided through the URL http://www.pythonhow.com/data/sampledata.txt #Question 45: Create a script that gets user's age and returns year of birth #Answers #Q41: #def vocabulary(word): # try: # return d[word] # except KeyError: # return "That word does not exist." #word = input("Enter word: ").lower() #print(vocabulary(word)) #Q42: #import requests #response = requests.get("http://www.pythonhow.com/data/universe.txt") #text = response.text #print(text) #count_a = text.count("a") #print(count_a) #Q43: #import webbrowser #query = input("Enter your Google query: ") #url = "https://www.google.com/?gws_rd=cr,ssl&ei=NCZFWIOJN8yMsgHCyLV4&fg=1#q=%s" % str(query) #webbrowser.open_new(url) #Q44: #import pandas #import pylab as plt #data = pandas.read_csv("http://www.pythonhow.com/data/sampledata.txt") #data.plot(x='x', y='y', kind='scatter') #plt.show() #Q45: #from datetime import datetime #age = int(input("What's your age? ")) #year_birth = datetime.now().year - age #print("You were born back in %s" % year_birth)
true
e33098027d5d81e360ab6bfa59e21518b60fafb5
simarjeetsingh/Python
/Ejercicios Python/ej_06.py
780
4.34375
4
'''Escribe un programa que pida por teclado dos valores de tipo numérico que se han de guardar en sendas variables. ¿Qué instrucciones habría que utilizar para intercambiar su contenido? (es necesario utilizar una variable auxiliar). Para comprobar que el algoritmo ideado es correcto, muestra en pantalla el contenido de las variables una vez leídas, y vuelve a mostrar su contenido una vez hayas intercambiado sus valores.''' variableA = int(input("Introduzca un número: ")) variableB = int(input("Introduzca otro número: ")) print("Los números introducidos son: ", variableA ,'y',variableB) variableAux = variableA variableA = variableB variableB = variableAux print ("Los números intercambiados son: ", variableA, 'y', variableB)
false
b3a98b16474442b4f12dc647514db6fd9b80f63e
1Magnus/pythonProject19_07_2021
/lesson_3/hw_5.py
644
4.25
4
# В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. import random def rand_mass(N): a = [0] * N for i in range(N): a[i] = random.randint(-99, 99) return a def main(): N = 10 a = rand_mass(N) print(a) b = [] for i in a: if i < 0: b.append(i) print(f'Максимальное отрицательное цисло - {max(b)} и его положение в масиве - {a.index(max((b))) + 1}') if __name__ == '__main__': main()
false
b878710a1e80355e01500b6a10601bf03f8c4f8b
LuckyDima/Geekbrains_DB_0607
/GeekBrains_local/Основы языка Python. Интерактивный курс/05 Модули и библиотеки/Lesson2.py
844
4.15625
4
# 2: Создайте модуль. В нем создайте функцию, которая принимает список и возвращает из него случайный элемент. # Если список пустой функция должна вернуть None. Проверьте работу функций в этом же модуле. # Примечание: Список для проверки введите вручную. Или возьмите этот: [1, 2, 3, 4] from random import choice, randint def rand_request(user_list=[i * randint(1, 100) for i in (range(randint(0, 5))) if i > 0]): if user_list: print(f'Random element is:', choice(user_list), '\nFull list:', user_list) else: print('None') if __name__ == '__main__': rand_request() rand_request([1, 2, 3, 4])
false
c65bc508a10563fa6a391cdfdd1997db19569b7a
bsamaha/hackerrank_coding_challenges
/Sock Merchant.py
761
4.125
4
# %% from collections import defaultdict # Complete the sockMerchant function below. def sockMerchant(n, ar): """[Find how many pairs can be made from a list of integers] Args: n ([int]): [nymber of socks] ar ([list of integers]): [inventory of socks] Returns: [type]: [description] """ sock_dict = defaultdict(int) # For each sock (val) in the sock inventory add one to the value count creating a dictionary for val in ar: sock_dict[val] += 1 print(sock_dict) # initialize counter cnt = 0 # Divide item count by 2 discarding remainders to get number of pairs possible for pair in sock_dict.values(): cnt += pair // 2 # Return the answer return cnt
true
e064d9a951cc77879be234b921f3712a4782652e
jz1611/python-codewars
/squareDigits.py
377
4.1875
4
# Welcome. In this kata, you are asked to square every digit of a number. # For example, if we run 9119 through the function, 811181 will come out, # because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): new = [] for num in list(str(num)): new.append(str(int(num) * int(num))) return int(''.join(new))
true
ed043fea8d74a1f790a593901cc0a3f516935329
cuongnb14/python-design-pattern
/sourcecode/data_structure/queue.py
1,126
4.125
4
class Node: data = None next = None def __init__(self, data=None): self.data = data class Queue: def __init__(self): self.length = 0 self.head = None self.last = None def is_empty(self): return self.length == 0 def push(self, node): if not isinstance(node, Node): node = Node(node) if not self.head: self.head = node if self.last: self.last.next = node self.last = node self.length += 1 def pop(self): if self.length > 0: result = self.head self.head = self.head.next if self.length == 1: self.last = None self.length -= 1 return result else: return None def print(self): cursor = self.head while cursor: print(cursor.data) cursor = cursor.next q = Queue() n1 = Node(1) n2 = Node(2) n3 = Node(3) q.push(n1) q.push(n2) q.push(n3) q.push(4) q.push(5) q.push(6) q.print() print(q.pop().data) print(q.pop().data) q.print()
false
d75bbaf6a902034ade93a755ce5762091a2f2532
driscolllu17/csf_prog_labs
/hw2.py
2,408
4.375
4
# Name: Joseph Barnes # Evergreen Login: barjos05 # Computer Science Foundations # Homework 2 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. #Name: Joseph Barnes # Evergreen Login: barjos05 # Computer Science Foundations ### ### Problem 1 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 1 solution follows:" import hw2_test n = hw2_test.n sum = 0 i = 0 while i <= n : sum = sum + i print sum i = i + 1 ##I added 1 to n in order for the program to print all the numbers ##up to 100. ### Problem 2 # DO NOT CHANGE THE FOLLOWING LINE print "Problem 2 solution follows:" n=10 for i in range(n+1): if i > 0: print 1.0/i ### ### Problem 3 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 3 solution follows:" n = 10 triangular = 0 for i in range(n): triangular = n * (n+1) / 2 print "Triangular number", n, "via loop:", triangular print "Triangular number", n, "via formula:", n * (n+1) / 2 ### ### Problem 4 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 4 solution follows:" n = 10 product = 1 for i in range(n): product = product * (i + 1) print "factorial=",product ### ### Problem 5 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 5 solution follows:" n = 10 numlines = n for i in range(n): print 'factorial of', n, '=' n = n-1 product = 1 for i in range(n+1): product = product * (i + 1) print product ### ### Problem 6 ### # DO NOT CHANGE THE FOLLOWING LINE print "Problem 6 solution follows:" n = 10 recip = 0 for i in range(n): if i > 0: recip = (1.0/i) + recip print recip ### ### Collaboration ### # For this assignment I did not use any collaborators. However I did use the text # a good deal in order to complete this assignment. ### ### Reflection ### # This assignment has taken me some time because I thought I had submitted an updated copy to my git hub repository. # I have made the corrections a second time. Initially I was having trouble with figuring out how to get parts two and six to output decimal reciprocals. # I thought that this was a good assignment and that it contained everything that was necessary to complete the assignment.
true
498852c54abdaf2be80bfe67dc88c0490f5a8ae1
chrisalexman/google-it-automation-with-python
/Crash Course in Python/Week_2/main.py
2,822
4.1875
4
# Data Types x = 2.5 print(type(x)) print("\n") # Expressions length = 10 width = 5 area = length * width print(area) print("\n") # Expressions, Numbers, and Type Conversions print(7 + 8.5) # implicit conversion print("a" + "b" + "c") print("\n") base = 6 height = 3 area = (base * height) / 2 print("Area: " + str(area)) # explicit conversion print("\n") total = 2048 + 4357 + 97658 + 125 + 8 files = 5 average = total / files print("The average size is:" + str(average)) print("\n") bill = 47.28 tip = bill * 0.15 total = bill + tip share = total / 2 print("Each person needs to pay: " + str(share)) print("\n") # Defining Functions def greeting(name, dept): print("Welcome, " + name) print("You are part of " + dept) greeting("Chris", "Parks Dept") result = greeting("Andrew", "IT Dept") print(result) print("\n") def get_seconds(hours, minutes, seconds): return 3600 * hours + 60 * minutes + seconds amount_a = get_seconds(2, 30, 0) amount_b = get_seconds(0, 45, 15) result = amount_a + amount_b print(result) print("\n") def area_triangle(base, height): return (base * height) / 2 area_a = area_triangle(5, 4) area_b = area_triangle(7, 3) the_sum = area_a + area_b print("Sum is: " + str(the_sum)) print("\n") def convert_seconds(sec): hours = sec // 3600 minutes = (sec - hours * 3600) // 60 remaining_seconds = sec - hours * 3600 - minutes * 60 return hours, minutes, remaining_seconds hours, minutes, seconds = convert_seconds(5000) print(hours, minutes, seconds) print("\n") # Code Style # 1. Self-Documenting: easy to read, understand # 2. Refactoring: clear intent # 3. Comment def circle_area(radius): pi = 3.14 area = pi * (radius ** 2) print(area) circle_area(5) print("\n") # Conditionals # operations print(10 > 1) print("cat" == "dog") print(1 != 2) # print(1 < "1") # error here # keywords: and or not print(1 == "1") print("cat" > "Cat") print("Yellow" > "Cyan" and "Brown" > "Magenta") # alphabetical for strings, (T and F) print(25 > 50 or 1 != 2) print(not 42 == "Answer") print("\n") # branching def hint_username(username): if len(username) < 3: print("Invalid username. Must be at least 3 characters long.") elif len(username) > 15: print("Invalid username. Must be at most 15 characters long.") else: print("Valid username.") hint_username("Al") hint_username("Edward") hint_username("abcdefghijlmnopq") print("\n") def is_even(num): if num % 2 == 0: return True return False result = is_even(3) print(result) result = is_even(4) print(result) print("\n") # Module print("big" > "small") def thesum(x, y): return x + y print(thesum(thesum(1, 2), thesum(3, 4))) print((10 >= 5*2) and (10 <= 5*2))
true
d7d25a4d0eed0b020901a5cad860743b4ad24396
sam23456/pythonclassfiles
/list data type.py
856
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[2]: course = ['linux','python','aws','devops','sql'] # In[3]: print(course) # In[ ]: # In[ ]: # In[5]: #indexing # In[6]: print(course[3]) # In[7]: print(course[3].title()) # In[8]: course.append('linux') # In[9]: print(course) # In[10]: course.insert(5,'server') # In[11]: print(course) # In[12]: course[6] = 'cloud' # In[13]: print(course) # In[15]: del course['5','6'] # In[16]: del course[5] # In[17]: print(course) # In[18]: x = course.pop() # In[19]: print(course) # In[20]: print(x) # In[ ]: # In[ ]: # Difference between 'del' and 'pop' -----> del is used to delete an element permenently where as pop will be deleted tempororly that is shared in separate variable like x,y,z,...
false
cf2ed5f62e36f00f2f5dead043ceec03a21a5ab3
AlexFeeley/RummyAIBot
/tests/test_card.py
2,223
4.21875
4
import unittest from src.card import * # Tests the card class using standard unit tests # from src.card import Card class TestCard(unittest.TestCase): # Tests constructor returns valid suit and number of card created def test_constructor(self): card = Card("Hearts", 3) self.assertEqual(card.get_suit(), 'Hearts', "Card constructor did not create a card of the correct suit") self.assertEqual(card.get_number(), 3, "Card constructor did not create a card of the correct number") # Tests constructor throws correct errors for invalid card construction def test_constructor_bounds(self): with self.assertRaises(ValueError): Card("Hello World", 2) with self.assertRaises(ValueError): Card("Hearts", 0) with self.assertRaises(ValueError): Card("Hearts", 20) # Find correct syntax for comparing namedtuples # def test_get_card(self): # card = Card("Hearts", 3) # self.assertIsInstance(card.get_card(), Card()) # Tests correct suit is returned def test_getSuit(self): card = Card("Hearts", 3) self.assertEqual(card.get_suit(), "Hearts", "Get suit returned the wrong suit") self.assertNotEqual(card.get_suit(), "Spades", "Get suit returned the wrong suit") # Tests corect number is returned def test_getNumber(self): card = Card("Hearts", 3) self.assertEqual(card.get_number(), 3, "Get number returned the wrong number") self.assertNotEqual(card.get_number(), 10, "Get number returned the wrong number") # Tests == for two equal cards def test_equals_true(self): card1 = Card("Hearts", 3) card2 = Card("Hearts", 3) self.assertTrue(card1 == card2, "Equals operator did not return true for equal cards") # Tests == for two unequal cards def test_equals_false(self): card1 = Card("Hearts", 3) card2 = Card("Spades", 3) card3 = Card("Hearts", 4) self.assertFalse(card1 == card2, "Equals operator did not return false for cards with different numbers") self.assertFalse(card1 == card3, "Equals operator did not return false for cards with different suits")
true
de7296225ab80c6c325bd91d83eae0610115b263
kvraiden/Simple-Python-Projects
/T3.py
266
4.21875
4
print('This a program to find area of a triangle') #The formulae is 1/2 h*b h = float(input("Enter the height of the triangle: ")) b = float(input("Enter the base of the triangle: ")) area = 1/2*h*b print("The area of given triangle is %0.2f" % (area)+" unit.")
true
b50f2c051b7ae0506cbc6f8a414d943ab3a20c51
tristandaly/CS50
/PSET6/mario/more/mario.py
727
4.1875
4
from cs50 import get_int def main(): # Begin loop - continues until a number from 1-8 is entered while True: Height = get_int("Height: ") if Height >= 1 and Height <= 8: break # Based on height, spaces are added to the equivalent of height - 1, subtracting with each row from the top # Same rule applies to hash symbols, only one is added with each line # Double-space is added at the end of each pyramid-half (after hash is printed) before right side is printed with same formula for i in range(Height): print(" "*(Height-i-1), end="") print("#"*(i+1), end="") print(" ", end="") print("#"*(i+1)) if __name__ == "__main__": main()
true
c8646e494885027bdf3819d0773b1ebb698db0a1
fatih-iver/Daily-Coding-Interview-Solutions
/Question #7 - Facebook.py
951
4.21875
4
""" This problem was asked by Facebook. Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. """ def decode(cipher): length = len(cipher) if length == 0: return 1 elif length == 1: return decode(cipher[1:]) else: f2d = int(cipher[:2]) if f2d < 27: return decode(cipher[1:]) + decode(cipher[2:]) return decode(cipher[1:]) def decode2(cipher, N, index = 0): if N - index == 0: return 1 elif N - index == 1: return decode2(cipher, N, index + 1) else: f2d = int(cipher[:2]) if f2d < 27: return decode2(cipher, N, index + 1) + decode2(cipher, N, index+2) return decode2(cipher, N, index + 1) print(decode("111")) print(decode2("111", 3))
true
3e3f17c7877bf2001a9de9d48ca4b9652648bc1f
natepill/problem-solving
/PracticePython/Fibonacci.py
490
4.25
4
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. # (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers # in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) def Fibonnaci(number):
true
013df573816baa9cf6c821223de06b773fbe8d1f
ricardosmotta/python_faculdade
/aulapratica4_ex1.py
1,085
4.15625
4
op = input('Qual operação você deseja realizar? + , - , * ou / : ') if (op == '+') or (op == '-') or (op == '*') or (op == '/'): v1 = int(input('Digite um valor inteiro: ')) v2 = int(input('Digite outro valor inteiro: ')) while op != 's': if (op == '+'): res = v1 + v2 print('Resultado da soma entre {} e {} é: {}'.format(v1, v2, res)) elif (op == '-'): res = v1 - v2 print('Resultado da subtração entre {} e {} é: {}'.format(v1, v2, res)) elif (op == '*'): res = v1 * v2 print('Resultado da multiplicação entre {} e {} é: {}'.format(v1, v2, res)) elif (op == '/'): res = v1 / v2 print('Resultado da divisão entre {} e {} é: {:.2f}'.format(v1, v2, res)) else: print('Opção inválida.') op = input('Qual operação você deseja realizar? + , - , * ou / : ') if (op == '+') or (op == '-') or (op == '*') or (op == '/'): v1 = int(input('Digite um valor inteiro: ')) v2 = int(input('Digite outro valor inteiro: ')) print('Encerrando programa...')
false
56b407e19a71898f123b688c28d8e5e85cef69ca
ricardosmotta/python_faculdade
/aula3_exercicio4.py
836
4.125
4
print('[ 1 ] Maçã') print('[ 2 ] Laranja') print('[ 3 ] Banana') prod = int(input('Qual dos produtos acima você deseja? ')) while prod != 1 and prod != 2 and prod != 3: print('Escolha um valor válido!!!') prod = int(input('Qual dos produtos acima você deseja? ')) if prod == 1 or prod == 2 or prod == 3: qtde = int(input('Qual a quantidade: ')) if prod == 1: pagar = qtde * 2.30 print('Você comprou {} maçãs e o total a pagar é R${}'.format(qtde, pagar)) else: if prod == 2: pagar = qtde * 3.50 print('Você comprou {} laranjas e o total a pagar é R${}'.format(qtde, pagar)) else: if prod == 3: pagar = qtde * 1.99 print('Você comprou {} bananas e o total a pagar é R${}'.format(qtde, pagar))
false
5e37fb9cff13522653e0e9006951e0db5839e259
aarontinn13/Winter-Quarter-History
/Homework2/problem6.py
938
4.3125
4
def palindrome_tester(phrase): #takes raw phrase and removes all spaces phrase_without_spaces = phrase.replace(' ', '') #takes phrase and removes all special characters AND numbers phrase_alpha_numeric = ''.join(i for i in phrase_without_spaces if i.isalpha()) #takes phrase and transforms all upper case to lower case phrase_all_lower_case = phrase_alpha_numeric.lower() #incase my string was only numbers and special characters, I have a check. if phrase_all_lower_case == '': print'This is not a palindrome.' #Final check to see if forward step is the same as reverse step. else: if phrase_all_lower_case == phrase_all_lower_case[::-1]: print'This is a palindrome.\n' else: print'This is not a palindrome.\n' #no loop since any 'break command' could be an input string = raw_input('What is your word or phrase? ') palindrome_tester(str(string))
true
bf26a7742b55fa080d22c1fadffccbf21ae9ce34
aarontinn13/Winter-Quarter-History
/Homework3/problem7.py
1,088
4.28125
4
def centered_average_with_iteration(nums): #sort list first nums = sorted(nums) if len(nums) > 2: #remove last element nums.remove(nums[-1]) #remove first element nums.remove(nums[0]) #create total total = 0.0 #iterate through and add all remaining in the list for i in nums: total += i #take the total and divide by the length of list average = ((total) / (len(nums))) return float(average) else: return 'please enter at least three numbers in the list' print(centered_average_with_iteration([1,2,3,4,5])) def centered_average(nums): #sort list first nums = sorted(nums) if len(nums) > 2: #removing last element nums.remove(nums[-1]) #removing first element nums.remove(nums[0]) #taking sum of numbers and dividing by elements average = sum(nums) / len(nums) return float(average) else: return 'please enter at least three numbers in the list' print(centered_average([3,4,5]))
true
4d80546ca7dfd20737f12f2dfddf3f9a0b5db00b
nip009/2048
/twentyfortyeight.py
2,776
4.125
4
# Link to the problem: https://open.kattis.com/problems/2048 def printArr(grid): for i in range(len(grid)): row = "" for j in range(len(grid[i])): if(j != 3): row += str(grid[i][j]) + " " else: row += str(grid[i][j]) print(row) def transpose(l1): ''' Takes a 2d list (a list of lists) and returns the transpose of that 2d list. ''' l2 = [] for i in range(len(l1[0])): row = [] for item in l1: row.append(item[i]) l2.append(row) return l2 def sortNonZeroValuesToTheRightAndMerge(grid): ''' Sort non-zero values to the right side, and zeros to the left. Merge once afterwards. As an example, the row [2, 0, 2, 0] will be sorted to [0, 0, 2, 2] and then merged to be [0, 0, 0, 4]. ''' for i in range(len(grid)): for j, _ in reversed(list(enumerate(grid[i]))): # Move numbers not equal to zero over to the right side. grid[i].sort(key=lambda x: x != 0) if(grid[i][j] == 0): continue if(j > 0 and grid[i][j-1] == grid[i][j]): grid[i][j-1] *= 2 grid[i][j] = 0 return grid def sortNonZeroValuesToTheLeftAndMerge(grid): ''' Sort non-zero values to the left, and zeros to the right. Merge once afterwards. As an example, the row [0, 2, 2, 0] will be sorted to [2, 2, 0, 0] and then merged to be [4, 0, 0, 0]. ''' for i in range(len(grid)): for j in range(len(grid[i])): grid[i].sort(key=lambda x: x != 0, reverse=True) if(grid[i][j] == 0): continue if(j > 0 and grid[i][j-1] == grid[i][j]): # 2 2 0 0 -> 4 0 0 0 grid[i][j-1] *= 2 grid[i][j] = 0 return grid def goLeft(grid): grid = sortNonZeroValuesToTheLeftAndMerge(grid) return grid def goRight(grid): grid = sortNonZeroValuesToTheRightAndMerge(grid) return grid def goUp(grid): grid = transpose(grid) grid = sortNonZeroValuesToTheLeftAndMerge(grid) grid = transpose(grid) return grid def goDown(grid): grid = transpose(grid) grid = sortNonZeroValuesToTheRightAndMerge(grid) grid = transpose(grid) return grid def runGame(move): global grid if move == 0: # left return goLeft(grid) elif move == 1: # up return goUp(grid) elif move == 2: # right return goRight(grid) elif(move == 3): # down return goDown(grid) grid = [[0 for i in range(4)] for j in range(4)] for i in range(4): inp = input().split(" ") for j in range(4): grid[i][j] = int(inp[j]) move = int(input()) grid = runGame(move) printArr(grid)
true
00656448d492d437654d9bc7a513a5239b26e04b
vinny0965/phyton
/1P/meuprojeto/Atividades 1VA/Nova Aula/Correção 1VA/resolucao prova - parte 2 - A vigança.py
2,216
4.21875
4
#Q8 #23 lista = [1,2,3,55,66,77,88,-1,-2,-3] #lista = [-1, -2, -3, -4, -5] """ #Retornar o maior elemento maior = lista[0] for numero in lista : if (numero > maior) : maior = numero print (f"Maior número:{maior}") #Forma alternativa de resolução #print (max(lista)) #Retornar a soma soma = 0 for numero in lista : soma += numero print (f"Soma:{soma}") #Forma alternativa de resolução #print (sum(lista)) """ """ #Número de ocorrências do primeiro elemento da lista count = 0 for numero in lista : if (lista[0] == numero): count += 1 print (f"Quantidade de ocorrências do primeiro elemento:{count}") #Forma alternativa de resolução #print(lista.count(lista[0])) #Média dos elementos media = 0 for numero in lista: media += numero media = media/len(lista) print (f"Média dos números:{media}") #Soma dos elementos negativos somaNegativos = 0 for numero in lista: if (numero < 0) : somaNegativos += numero print (f"Soma elementos negativos:{somaNegativos}") #Qual o valor mais próximo da média proximo = lista[0] diferenca = media for numero in lista: subtracao = media - numero if (subtracao < 0): subtracao = subtracao * -1 print (media, numero, subtracao, diferenca) if (subtracao < diferenca): diferenca = subtracao proximo = numero print (f"Valor mais próximo:{proximo}") """ #Q9 quantidade = int(input("Digite a quantidade de usuários")) dicionario = {} usuarioMaisVelho = 0 maiorIdade = -1 for i in range(quantidade): print (f"Informações usuário #{i}") nome = input("Digite o nome:") idade = int(input("Digite o idade:")) cpf = int(input("Digite o cpf (apenas os números):")) telefone = input("Digite o número de telefone:") dicionario[cpf] = [nome, idade, cpf, telefone] if idade > maiorIdade : maiorIdade = idade usuarioMaisVelho = cpf lista = dicionario[usuarioMaisVelho] print ("Nome do usuário mais velho:" + lista[0]) print ("Idade do usuário mais velho:" + lista[1]) print ("Cpf do usuário mais velho:" + lista[2]) print ("telefone do usuário mais velho:" + lista[3])
false
41e11c5c0c449e131862c3ec423137bd9ce619b8
Yun-Su/python
/PythonApplication1/PythonApplication1/匿名函数.py
679
4.1875
4
#python 使用 lambda 来创建匿名函数。 #所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。 #lambda的主体是一个表达式,而不是一个代码块。 #仅仅能在lambda表达式中封装有限的逻辑进去。 #lambda 函数拥有自己的命名空间, #不能访问自己参数列表之外或全局命名空间里的参数。 #虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数, #后者的目的是调用小函数时不占用栈内存从而增加运行效率 sum = lambda a,b: a + b #调用sum() print ("相加后的值为 : ", sum( 10, 20 )) print ("相加后的值为 : ", sum( 20, 20 ))
false
e3ce4ff4dff53081b377cee46412ea42365651fa
digvijaybhakuni/python-playground
/pyListDictionaries/ch1-list.py
2,221
4.1875
4
numbers = [5, 6, 7, 8] print "Adding the numbers at indices 0 and 2..." print numbers[0] + numbers[2] print "Adding the numbers at indices 1 and 3..." print numbers[1] + numbers[3] """ Replace in Place """ zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] # Last night our zoo's sloth brutally attacked #the poor tiger and ate it whole. # The ferocious sloth has been replaced by a friendly hyena. zoo_animals[2] = "hyena" # What shall fill the void left by our dear departed tiger? zoo_animals[3] = "sloth" """ Lenght and append """ suitcase = [] suitcase.append("sunglasses") # Your code here! suitcase.append("watch") suitcase.append("shoes") suitcase.append("pants") list_length = len(suitcase) # Set this to the length of suitcase print "There are %d items in the suitcase." % (list_length) print suitcase """ List Slicing """ suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"] first = suitcase[0:2] # The first and second items (index zero and one) middle = suitcase[2:4] # Third and fourth items (index two and three) last = suitcase[4:6] # The last two items (index four and five) print first print middle print last """ Slicings Lists and String """ animals = "catdogfrog" cat = animals[:3] # The first three characters of animals dog = animals[3:6] # The fourth through sixth characters frog = animals[6:] # From the seventh character to the end """ Maintaining Orders """ animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" animals.insert(duck_index, "cobra") print animals # Observe what prints after the insert operation """ For One and all """ my_list = [1,9,3,8,5,7] for number in my_list: print number, " = ", number * 2 """ More with 'For' """ start_list = [5, 3, 1, 2, 4] square_list = [] for x in start_list: square_list.append(x ** 2) square_list.sort() start_list.sort() print start_list print square_list """ How to remove """ backpack = ['xylophone', 'dagger', 'tent', 'bread loaf'] backpack.remove("dagger")
true
52c0773a6f69824b10bfe91e91d21acb1154012b
pmcollins757/check_sudoku
/check_sudoku.py
2,091
4.1875
4
# -*- coding: utf-8 -*- """ Author: Patrick Collins """ # Sudoku puzzle solution checker that takes as input # a square list of lists representing an n x n # sudoku puzzle solution and returns the boolean # True if the input is a valid # sudoku square solution and returns the boolean False # otherwise. # A valid sudoku square solution satisfies these # two properties: # 1. Each column of the square contains # each of the whole numbers from 1 to n exactly once. # 2. Each row of the square contains each # of the whole numbers from 1 to n exactly once. # Assuming the the input is square and contains at # least one row and one column. correct = [[1,2,3], [2,3,1], [3,1,2]] incorrect = [[1,2,3,4], [2,3,1,3], [3,1,2,3], [4,4,4,4]] incorrect2 = [[1,2,3,4], [2,3,1,4], [4,1,2,3], [3,4,1,2]] incorrect3 = [[1,2,3,4,5], [2,3,1,5,6], [4,5,2,1,3], [3,4,5,2,1], [5,6,4,3,2]] incorrect4 = [['a','b','c'], ['b','c','a'], ['c','a','b']] incorrect5 = [ [1, 1.5], [1.5, 1]] incorrect6 = [[0,1,2], [2,0,1], [1,2,0]] def check_sudoku(puzzle): sqr_size = len(puzzle) column_puzzle = zip(*puzzle) for row in puzzle: for x in row: if not isinstance(x, int) or x > sqr_size or x < 1: return False if sum(row) != sum(set(row)): return False for column in column_puzzle: if sum(column) != sum(set(column)): return False return True print check_sudoku(correct), "True" #>>> True print check_sudoku(incorrect), "False" #>>> False print check_sudoku(incorrect2), "False2" #>>> False print check_sudoku(incorrect3), "False3" #>>> False print check_sudoku(incorrect4), "False4" #>>> False print check_sudoku(incorrect5), "False5" #>>> False print check_sudoku(incorrect6), "False6" #>>> False
true
60950955c5fcd3bc7a7410b78c3be383feb7e9ed
marcotello/PythonPractices
/Recursion/palindrome.py
1,696
4.4375
4
def reverse_string(input): """ Return reversed input string Examples: reverse_string("abc") returns "cba" Args: input(str): string to be reversed Returns: a string that is the reverse of input """ # TODO: Write your recursive string reverser solution here if len(input) == 0: return "" else: first_char = input[0] the_rest = slice(1, None) sub_string = input[the_rest] reversed_substring = reverse_string(sub_string) return reversed_substring + first_char def is_palindrome(input): """ Return True if input is palindrome, False otherwise. Args: input(str): input to be checked if it is palindrome """ # TODO: Write your recursive palindrome checker here reversed_str = reverse_string(input) if reversed_str == input: return True else: return False ''' # Solution def is_palindrome(input): """ Return True if input is palindrome, False otherwise. Args: input(str): input to be checked if it is palindrome """ if len(input) <= 1: return True else: first_char = input[0] last_char = input[-1] # sub_input is input with first and last char removed sub_input = input[1:-1] return (first_char == last_char) and is_palindrome(sub_input) ''' # Test Cases print ("Pass" if (is_palindrome("")) else "Fail") print ("Pass" if (is_palindrome("a")) else "Fail") print ("Pass" if (is_palindrome("madam")) else "Fail") print ("Pass" if (is_palindrome("abba")) else "Fail") print ("Pass" if not (is_palindrome("Udacity")) else "Fail")
true
a26b16019c44c2ff2ea44916bcc3fa66a62a826e
marcotello/PythonPractices
/P0/Task1.py
2,427
4.3125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ def get_unique_numbers(numbers, numbers_set): """ This function returns a set of unique numbers INPUT: numbers: a list of numbers with the following format on each element ["number1", "number 2" ... more elements]. numbers_set: the set where the unique numbers are stored. RETURN: a set with unique numbers. """ # iterating the list to get the numbers - O(n) # this has a complexity of O(n), because it is iterating over the whole list. for number in numbers: # getting the fist element of each record and storing it on the Set - O(1) numbers_set.add(number[0]) # getting the second element of each record and storing it on the Set - O(1) numbers_set.add(number[1]) # returning the set of unique numbers - O(1) return numbers_set def main(): # I have chosen set as my data collection because for this problem the order doesn't matter. Set holds unique hashable object like strings. # Creating the set - O(1) numbers_set = set() # calling get_unique_numbers function - O(n) numbers_set = get_unique_numbers(calls, numbers_set) # calling get_unique_numbers function - O(n) numbers_set = get_unique_numbers(texts, numbers_set) # printing the len of the set - O(3) print("There are {} different telephone numbers in the records.".format(len(numbers_set))) if __name__ == "__main__": main() """ # UNIT TESTING # get_unique_numbers test test_list1 = [["(022)39006198", "98440 65896"], ["90087 42537", "(080)35121497"], ["(044)30727085", "90087 42537"], ["90087 42537", "(022)39006198"]] assert(len(get_unique_numbers(test_list1, set())) == 5) test_list2 = [["(022)39006198", "98440 65896"], ["(022)39006198", "98440 65896"], ["98440 65896", "(022)39006198"], ["98440 65896", "(022)39006198"]] assert(len(get_unique_numbers(test_list2, set())) == 2) print("test for get_unique_numbers passed") """
true
2252d7e3ea30fe49636bbeeb50f6c3b3c7fdf80d
marcotello/PythonPractices
/DataStrucutures/Linked_lists/flattening_linked_list.py
1,622
4.125
4
# Use this class as the nodes in your linked list class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self, head): self.head = head def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next is not None: node = node.next node.next = Node(value) def to_list(linked_list, lst): node = linked_list.head while node: lst.append(node.value) node = node.next return lst def merge(list1, list2): # TODO: Implement this function so that it merges the two linked lists in a single, sorted linked list. temp_list = [] # merged_list = None temp_list = to_list(list1, temp_list) temp_list = to_list(list2, temp_list) temp_list.sort() llist = LinkedList(Node(temp_list[0])) index = 1 while index < len(temp_list): llist.append(temp_list[index]) return llist class NestedLinkedList(LinkedList): def flatten(self): # TODO: Implement this method to flatten the linked list in ascending sorted order. # First Test scenario linked_list = LinkedList(Node(1)) linked_list.append(3) linked_list.append(5) nested_linked_list = NestedLinkedList(Node(linked_list)) second_linked_list = LinkedList(Node(2)) second_linked_list.append(4) nested_linked_list.append(Node(second_linked_list)) merge(linked_list, second_linked_list)
true
1543e31bbe36f352dd18b284bd9fc688332e9486
LucasBeeman/Whats-for-dinner
/dinner.py
1,446
4.40625
4
import random ethnicity = [0, 1, 2, 3] type_choice = -1 user_choice = input("Which ethnnic resturaunt would you like to eat at? Italian(1), Indian(2), Chinese(3), Middle Eastern(4), Don't know(5)") #if the user pick I dont know, the code will pick one for them through randomness if user_choice.strip() == "5": type_choice = random.choice(ethnicity) #change "ethnicity" to a string stating what the ethnicity is, this is for the print later on. add a list of at least 3 rasturants of that ethnicity if type_choice == 0 or user_choice.strip() == "1": ethnicity = "italian" place = ["Bruno Bros", "Belleria", "Bella Napoli"] elif type_choice == 1 or user_choice.strip() == "2": ethnicity = "Indian" place = ["Cafe India", "Bombay Curry and Grill", "Kabab and Curry"] elif type_choice == 2 or user_choice.strip() == "3": ethnicity = "Chinese" place = ["Main Moon", "Hunan Express", "Imperial Graden"] elif type_choice == 3 or user_choice.strip() == "4": ethnicity = "Middle Eastern" place = ["Zenobia", "Ghossain's", "sauceino"] #error handeling else: print("ERROR") #if the user said that they don't know, state what ethnicity the resturant is if type_choice is not -1: print("your ethnicity is", ethnicity) #prints the random reasturaunt from the list of 3 resturants, then prints it out place_choice = random.choice(place) print("your going to", str(place_choice) + "!")
true
9f60c2a26e4ea5bf41c310598568ea0b532c167b
Rajeshinu/bitrm11
/4.Stringcount.py
231
4.25
4
"""Write a program that asks the user for a string and returns an estimate of how many words are in the string""" string=input("Please enter the string to count the number of words in the string\n") c=string.count(" ") print(c+1)
true
42bd0e1748a8964afe699112c9d63bc45cd421f3
Rajeshinu/bitrm11
/8.Numbersformat.py
347
4.125
4
"""Write a program that asks the user for a large integer and inserts commas into it according to the standard American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be 1,000,000""" intnum=int(input(print("Please enter the large integer number : "))) fnum=format((intnum),',d') print(fnum)
true
50531ecdd319b058d9c2fe98b17a76a1392f85bf
Aqib04/tathastu_week_of_code
/Day4/p1.py
306
4.21875
4
size = int(input("Enter the size of tuple: ")) print("Enter the elements in tuple one by one") arr = [] for i in range(size): arr.append(input()) arr = tuple(arr) element = input("Enter the element whose occurrences you want to know: ") print("Tuple contains the element", arr.count(element), "times")
true
4d39b4b1e0d28374f5dbdf455db1e223aa48dc3a
petrewoo/Trash
/ex_iterator/p1.py
439
4.125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- class reverse_iter: def __init__(self, l): self._l = l def __iter__(self): return self def next(self): if len(self._l): return self._l.pop() else: raise StopIteration if __name__ == '__main__': """Test case""" test_list = [1, 2, 3, 4, 7, 5] x = reverse_iter(test_list) while 1: print next(x)
false
058d1ae6fa21662f7bac3d3e05ef0aedfdbe14b2
gneelimavarma/practicepython
/C-1.19.py
340
4.4375
4
##C-1.19 Demonstrate how to use Python’s list comprehension syntax to produce ##the list [ a , b , c , ..., z ], but without having to type all 26 such ##characters literally. ##ascii_value = ord('a') ##print(ascii_value) i=0 start = 97 ##ascii of 'a' result = [] while(i<26): result.append(chr(start+i)) i+=1 print(result)
true
4195b70fb68c585767702cf31041ee98535aea48
ianbel263/geekbrains_python
/lesson_1/task_5.py
920
4.125
4
company_income = int(input('Введите прибыль фирмы: ')) company_costs = int(input('Введите издержки фирмы: ')) if company_income > company_costs: print('Фирма работает с прибылью') company_profit = company_income - company_costs profitability = round(company_profit / company_income * 100, 2) print(f'Рентабельность фирмы составляет: {profitability}%') staff_number = int(input('Введите численность сотрудников фирмы: ')) profit_per_staff = round(company_profit / staff_number, 2) print(f'Прибыль фирмы в расчете на одного сотрудника составляет: {profit_per_staff}') elif company_income < company_costs: print('Фирма работает в убыток') else: print('Фирма работает в ноль')
false
0396e783aca5febe373e32fc544dead5a5817760
marbor92/checkio_python
/index_power.py
367
4.125
4
# Function finds the N-th power of the element in the array with the index N. # If N is outside of the array, then return -1. def index_power(my_list, power) -> int: pos = 0 index = [] for i in my_list: index.append(pos) pos += 1 if power not in index: ans = -1 else: ans = my_list[power] ** power return ans
true
2c455ec9c2bbd31d79aa5a3b69c4b9b17c25b7a7
whalenrp/IBM_Challenge
/SimpleLearner.py
1,584
4.125
4
import sys import math import csv from AbstractLearner import AbstractLearner class SimpleLearner(AbstractLearner): """ Derived class implementation of AbstractLearner. This class implements the learn() and classify() functions using a simple approach to classify all as true or false """ def __init__(self, trainingInputFile, testInputFile, isMachineReadable, outputFile): AbstractLearner.__init__(self, trainingInputFile, testInputFile, isMachineReadable, outputFile) #global variable for classification of data, default false self.classification = False def learn(self): """ Creates a classification model based on data held in the AbstractLearner's trainingData list-of-lists """ numRows = len(self.trainingData) numTrue = 0 numFalse = 0 #get number of true and false elements in the data for i in range(numRows): if self.trainingData[i][-1]: numTrue += 1 else: numFalse += 1 #if there are more trues, set classification to true, otherwise it will be false if numTrue >= numFalse: self.classification = True def classify(self): """ Based on the classification model generated by learn(), this function will read from the testData list-of-lists in AbstractLearner and output the prediction for each variable """ #create a csv writer for output myWriter = csv.writer(open(self.outputFile, "wb")) #if classification is true if self.classification: numRows = len(self.testData) #write index of all rows, since all are true for i in range(numRows): myWriter.writerow([i]) sys.exit(0)
true
bcda1f6f442b5219ce52c10c0bf51f59122f212c
benjie13/benjie-lattao
/loops_lattao.py
508
4.25
4
print ("2 to 10") for x in range (2,12,2): print(x) print ("3 to 15") for y in range(3,18,3): print(y) print ("4 to 20") for z in range (4,24,4): print(z) print ("12 to 36") for a in range (12,48,12): print(a) #nested loop sample print ("Multiplication") for y in range (1,11): for z in range (1,11): print(z * y, end='\t') print() print ("Multiplication 10 - 20") for y in range (10,21): for z in range (1,11): print(z * y, end='\t') print()
false
d272fde739325284f99d1f148d1603d739d24721
ganesh28gorli/Fibonacci-series
/fibonacci series.py
678
4.4375
4
#!/usr/bin/env python # coding: utf-8 # # fibonacci series # In[15]: # n is the number of terms to be printed in fibonacci series # In[16]: n = int(input("enter number of terms: ")) # In[17]: # assigning first two terms of the sequence # In[18]: a=0 b=1 # In[19]: #checking if the number of terms of sequence(n), given by the user is valid or not.if number is valid the fibinacci sequence. # In[20]: if n<=0: print("enter number greater than zero") print(a) elif n == 1: print(a) else: print(a) print(b) for i in range(2,n): c=a+b a=b b=c print(c) # In[ ]: # In[ ]:
true
aef6477c03006ff40a937946213ea05c1ec11106
ta11ey/algoPractice
/algorithms/linkedList_insertionSort.py
1,088
4.3125
4
# Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. # The steps of the insertion sort algorithm: # Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. # At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. # It repeats until no input elements remain. from algoPractice.dataStructures.ListNode import ListNode def dummyInsert(head: ListNode, item: ListNode): dummy = ListNode() current = dummy current.next = head while current.next and current.next.val < item.val: current = current.next item = ListNode(item.val, current.next) current.next = item return dummy.next def exec(head): # sorted part sortedHead = ListNode(head.val, None) # Current current = head # Unsorted while current.next is not None: sortedHead = dummyInsert(sortedHead, current.next) current = current.next return sortedHead
true
8b9ac54cf15648e5c5bb315fbd2e2d3bcffb5b9c
howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files
/Básicos/PygLatin.py
775
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #o objetivo deste programa é mover a primeira letra da palavra para o final e adicionar ay. #Dessa forma, a palavra Batata vira atatabay pyg = 'ay' #primeiro define-se ay original = raw_input('Escolha uma palavra: ') #deixa um espaço para colocar uma palavra if len(original) > 0 and original.isalpha(): #a palavra deve ter mais que 0 letras e ser composta somente por letras (isalpha) print "A palabra escolhida foi: ", original word = original.lower first = word[0] #primeira letra da palavra já com as letras minúsculas new_word = word + first + pyg new_word = new_word[1:len(new_word)] #cortamos aqui a primeira letra da palavra print "Sua tradução em PygLatin é: ", new_word else: print "Vazio!"
false
600e7893f4e4f7cb0e6b8819d4e17cc718427ec8
dihogoteixeira/fiap-ctp-exercises
/exercicios-aula-08/AULA_08_Exercicio03.py
443
4.1875
4
contaCliente = input("Digite seu codigo de verificacao de 3 digitos: ") verificadorCliente = contaCliente[::-1] somaNumeroConta = int(contaCliente) + int(verificadorCliente) multiplicaDigito = list(str(somaNumeroConta)) digitoVerificador = int(multiplicaDigito[0]) *1 + int(multiplicaDigito[1]) *2 + int(multiplicaDigito[2]) *3 exibirDigitoVerificador = list(str(digitoVerificador)) print("Valor da verificacao: ", exibirDigitoVerificador[1])
false
6185ccae596ac60ad46d2788c30e035eb7153701
AilanPaula/Curso_em_video_Python3
/ex052.py
753
4.28125
4
''' Crie um programa onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' from random import randint print('Sou seu computador...') print('Acabei de pensar em um número entre 0 e 10.') print('Será que você consegue adivinhar em qual foi?') acertou = False ram = randint(0,10) cont = 0 while not acertou: num = int(input('Qual o seu palpite?: ')) cont +=1 if num == ram: acertou = True else: if num < ram: print('Mais... Tente mais uma vez.') elif num > ram: print('Menos... Tente mais uma vez.') print('Acertou com {} tentativas. '.format(cont))
false
acc830fa259137641c7dcda20abd8b2b1a08a802
AilanPaula/Curso_em_video_Python3
/ex094.py
824
4.15625
4
''' Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. ''' def LeiaInt(resp): num = str(input(resp)) if num.isnumeric(): num = int(num) return num while not num.isnumeric(): print('ERRO! Digite um número válido') num = str(input(resp)) return num '''def teste(msg): ok = False valor = 0 while True: num = str(input(msg)) if num.isnumeric(): valor = int(num) ok = True else: print('ERRO! Digite um número válido') if ok: break return valor''' #Programa principal n = LeiaInt('Digite um número: ') print(f'Você digitou o número {n}.')
false
4cc1e53231d01ca6445afab717339048af2cf378
AilanPaula/Curso_em_video_Python3
/ex053.py
1,214
4.28125
4
''' Crie um programa que leia dois valores e mostre um menu na tela: [ 1 ] somar [ 2 ] multiplicar [ 3 ] maior [ 4 ] novos números [ 5 ] sair do programa Seu programa deverá realizar a operação solicitada em cada caso. ''' n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) op = 0 while op !=5: print('\nMenu: \n[1]somar \n[2]multiplicar \n[3]maior \n[4]novos números \n[5]sair do programa \n') op = int(input('Qual a sua opções?: ')) if op == 1: soma = n1 + n2 print('A soma entre {} e {} é: {}. '.format(n1, n2, soma)) elif op == 2: produto = n1 * n2 print('A multiplicação entre {} e {} é: {}. '.format(n1, n2, produto)) elif op == 3: if n1 > n2: maior = n1 else: maior = n2 print('O maior número entre {} e {} é: {}. '.format(n1, n2, maior)) elif op == 4: print('Informe os número novamente: ') n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) elif op == 5: print('Finalizando...') break else: print('Opção inválida. Digite um valor válido.') print('Fim do programa. Volte sempre.')
false
2a04e50ee49757c2ba2c9ae5ceeb5940e97c482e
AilanPaula/Curso_em_video_Python3
/ex090.py
767
4.125
4
''' um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior. ''' from random import randint from time import sleep lista = list() def sorteia(lst): print('Os valores sorteados são: ', end='') print() for c in range(0, 5): n = randint(1, 10) lst.append(n) print(f'{n} ', end='', flush=True) sleep(0.3) def somapar(lst): soma = 0 for v in lst: if v % 2 == 0: soma += v print(f'\nSomando os valores pares da lista {lst} é: {soma}', end='') sorteia(lista) somapar(lista)
false
084cb1de7fece4e3f74452233bd61c03af0812b8
amitp-ai/Resources
/leet_code.py
1,353
4.65625
5
#test """ Syntax for decorators with parameters def decorator(p): def inner_func(): #do something return inner_func @decorator(params) def func_name(): ''' Function implementation''' The above code is equivalent to def func_name(): ''' Function implementation''' func_name = (decorator(params))(func_name) #same as decorator(params)(func_name) As the execution starts from left to right decorator(params) is called which returns a function object fun_obj. Using the fun_obj the call fun_obj(fun_name) is made. Inside the inner function, required operations are performed and the actual function reference is returned which will be assigned to func_name. Now, func_name() can be used to call the function with decorator applied on it. """ # Decorators with parameters in Python def big_func(dumy): print(dumy) return func1 def func1(x): print('xxxxx') print(x) big_func('zzzz')(2) @big_func('zzz') def func1(x): print(x) print('1'*50) def decorator(*args, **kwargs): print("Inside decorator") def inner(func): print("Inside inner function") print("I like", kwargs['like']) return func return inner @decorator(like = "geeksforgeeks") def func(): print("Inside actual function") func() print('2'*50) decorator(like = "geeksforgeeks")(func)()
true
fb55395ee175bdce797e17f48c6c04d7f2c574a2
dukeofdisaster/HackerRank
/TimeConversion.py
2,484
4.21875
4
############################################################################### # TIME CONVERSION # Given a time in 12-hour am/pm format, convert it to military (24-hr) time. # # INPUT FORMAT # A single string containing a time in 12-hour clock format (hh:mm:ssAM or # hh:mm:ssPM) wehre 01 <= hh <= 12 and 00 <= mm, ss <= 59 # # OUTPUT FORMAT # Convert and print given time in 24hr format where 00 <= hh <= 23 ############################################################################### # Note: We have several options for figuring out how to tackle this problem. At # first look it might seem like we can use the 're' library, to find a matching # sequence in the time string, i.e. "AM" or "PM"...which is nice, but also more # complicated than we need the problem to be. # # We've seen that HackerRank likes to use the split() function, what if we used # it ourselves to split our time string into 3 separate strings, based on the # fact that the format of the string is somewhat split itself by the colon ':'? # # This method works. We can declare multiple variables in the same line by # using commas, so a,b,c = time.split(':') works just fine because splitting # the time string by the two colons creates 3 separate substrings.The first two # of these substrings will be easy to work with because they are numbers, so # type casting them with int() will be easy.but the last string still contains # AM or PM. How can we separate the numbers from the letters? # The next useful method will be slicing. we can slice a string x using the # format: myString[int:int], which will create a substring from the left value # to the right value based on what you give the string. [:2] will return the # first two values of the string, while [2:] will return the values between the # second character all the way to the end of the string... i.e. all but the 1st # two. so we can create two sub values from the c string by slicing and storing # these values as aORp (am or pm) and seconds. import sys time = raw_input().strip() a,b,c = time.split(':') aORp = c[2:] seconds= c[:2] if aORp[0] == 'A': if a == '12': print('00'+':'+b+':'+seconds) else: print(a+':'+b+':'+seconds) # For PM, we use two type casts: first we typecast a to an int so we can # do the conversion to 24 time, which consists of adding 12 to the time elif aORp[0] == 'P': if a == '12': print (a+':'+b+':'+seconds) else: print(str((int(a)+12))+':'+b+':'+seconds)
true
b500774449d17ede116b123f293a89969d2a01c9
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio38.py
1,331
4.21875
4
# Um funcionário de uma empresa recebe aumento salarial anualmente: Sabe-se que: # Esse funcionário foi contratado em 1995, com salário inicial de R$ 1.000,00; # Em 1996 recebeu aumento de 1,5% sobre seu salário inicial; # A partir de 1997 (inclusive), os aumentos salariais sempre correspondem ao dobro do percentual do ano anterior. Faça um programa que determine o salário atual desse funcionário. Após concluir isto, altere o programa permitindo que o usuário digite o salário inicial do funcionário. salario_inicio_carreira = int(input("Informe o seu salário iniciao ")) ano_inicio_carreira = int(input("Informe o ano de inicio da carreira ")) ano_atual = int(input("Informe o ano atual ")) def calcula_salario(salario_inicio_carreira, ano_inicio_carreira): percentual_ao_mes_inicial = 1.5 while ano_inicio_carreira < ano_atual: resultado_salario = (percentual_ao_mes_inicial * salario_inicio_carreira) / 100 ano_inicio_carreira += 1 percentual_ao_mes_inicial *= 2 total = salario_inicio_carreira + resultado_salario print("O salário inicial foi de: R$" + str(salario_inicio_carreira)) print("O aumento de salário de: R$" + str(resultado_salario)) print("O salário final foi de: R$" + str(total)) calcula_salario(salario_inicio_carreira, ano_inicio_carreira)
false
7a225d2e1f0ac5450917eb22f8f5537bac4be099
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio24.py
735
4.15625
4
# Faça um programa que calcule o mostre a média aritmética de N notas. quantidade_notas = int(input("informe a quantidade de notas do aluno: ")) def calcula_media(quantidade_notas): contador = 0 listagem_notas = [] while contador < quantidade_notas: nota_aluno = float(input("informe a nota: ")) if nota_aluno >= 0.0 and nota_aluno <= 10.0: contador += 1 listagem_notas.append(nota_aluno) else: print("nota precisa ser um valor válido entre 0 e 10") somatoria = sum(listagem_notas) media = somatoria/quantidade_notas print("relação de notas: " + str(listagem_notas) + " e a média do aluno fdi: " + str(media)) calcula_media(quantidade_notas)
false
a8f8878c553a1ec9da4e70fb13af9223bebdb35d
jimbrunop/brunoperotti
/Exercicios-Python/RepeticaoExercicio1.py
414
4.21875
4
# Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido. def valida_numero(): numero = float(input("informe um numero de 0 a 10: ")) while (numero > 10) or (numero < 0): numero = float(input("informe um numero de 0 a 10: ")) else: print("o valor bateu") valida_numero()
false
f7c35cd71de55bd957da4338110c3343918c641d
Dr-A-Kale/Python-intro
/str_format.py
669
4.125
4
#https://python.swaroopch.com/basics.html age = 20 name = 'Swaroop' print('{0} was {1} years old when he wrote this book'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) print(f'{name} was {age} years old when he wrote this book') print(f'Why is {name} playing with that python?') print("What's your name?") print('What\'s your name?') # This line is being left as a space for jokes. print("Bond said \"hi my name is james\"") # The use of backslash as an escape sequence # Below is an example of a two-line string using \n print("This is the first line\nThis is the second line") print("This is the first line\tThis is the second line")
true
03b4609e13f7b1f3bafbdc8c9ffc83e04ca49b04
KartikeyParashar/FunctionalPrograms
/LeapYear.py
322
4.21875
4
year = int(input("Enter the year you want to check that Leap Year or not: ")) if year%4==0: if year%100==0: if year%400==0: print("Yes it is a Leap Year") else: print("Not a Leap Year") else: print("Yes it is a Leap Year") else: print("No its not a Leap Year")
true
914d4fa9aeacfdb617b936cd783f52a0c4687f59
vltian/some_example_repo
/lesson_6_OOP/hw_62.py
1,195
4.53125
5
"""2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см * чи сло см толщины полотна. Проверить работу метода. Например: 20м * 5000м * 25кг * 5см = 12500 т """ class Road: def __init__(self, length, width): self._length = length self._width = width def clc (self): m = int(input("mass kg - ")) h = int(input("height cm - ")) print(self._length*self._width*m/1000*h) rd_clc = Road(5000,20) rd_clc.clc()
false
169d013c1c226c53da4c2e5d0fa6444d7f8bb087
natalya-patrikeeva/interview_prep
/binary-search.py
1,672
4.3125
4
"""You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated values, and elements are in a strictly increasing order. Return the index of value, or -1 if the value doesn't exist in the list.""" def binary_search(input_array, value): count = 0 while len(input_array) > 1: array = input_array length = len(input_array) # Even number of elements if length % 2 == 0: half_index = length / 2 if value > input_array[half_index - 1]: input_array = input_array[half_index:] count += half_index elif value < input_array[half_index - 1]: input_array = input_array[:half_index] else: count += half_index - 1 return count # Odd number of elements else: half_index = (length - 1 ) / 2 if value > input_array[half_index]: input_array = input_array[half_index + 1:] count += half_index + 1 elif value < input_array[half_index]: input_array = input_array[:half_index] else: count += half_index return count if value == input_array[0]: return count else: return -1 test_list = [1,3,9,11,15,19,29] test_val1 = 25 test_val2 = 15 print binary_search(test_list, test_val1) print binary_search(test_list, test_val2)
true
eed9c8739eb2daa6ecbc47e10693e3d9b1970d82
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON CLASS/CLASSx8.py
1,757
4.71875
5
# -*- coding: utf-8 -*- #! /usr/bin/env python3 # Classes and Objects # Suppose there is a class 'Vehicles' # A few of the other objects can be represented as objects/children of this super class # For instance, Car, Scooter, Truck are all vehicles and can be denoted as a derivative # of the class 'Vehicle' # Furthermore, these derived objects can have some other properties that are unique to # them and are not available in the super class. # Superclass - Baseclass # 'Subclasses' derive properties from the super class class MeClass: print("\nIn Class") x=32 foo= MeClass() print(foo) print(foo.x) class FirstClass: print("Inside Class") def __init__(self, prop): print("Inside Init function") self.x= prop foo= FirstClass(45) print(foo) print(foo.x,'\n') class Person: # Assignment of values to the properties of the objects created is done # inside the init function. def __init__(self, name, age, city): self.name= name self.age= age self.city= city def introduceInSpanish(self): print("Hola! Me llamo "+self.name) # Treating Ramesh as an object. ramesh= Person("Ramesh", 32, "Noida") print( "Name:", ramesh.name ) print( "Age: ", ramesh.age ) print( "City:", ramesh.city ) ramesh.introduceInSpanish() # To reassign/modify any propert of an object # Object.Property= NewValue ramesh.age= 55 print( "\nNew Age: ", ramesh.age ) # Let's delete his name from records. del ramesh.name # Gives out error. No attribute 'name' # print( ramesh.name ) print( ramesh.__dict__ ) print("\nYou know what? I don't really like ramesh.") print("Let's delete him.") del ramesh print("Deleted.") try: print("Trying to access ramesh ...") print( ramesh.__dict__ ) except: print("There was an error. There's no ramesh.")
true
f87f1f7c943f2b754de1c35a0f994c18201ca2fe
sarthakjain95/UPESx162
/SEM I/CSE/PYTHON PRACTICALS/PRACTICALx4B.py
2,687
4.125
4
# -*- coding: utf-8 -*- # PRACTICAL 4B # Q1) Find a factorial of given number. def getFacto(num): facto= 1 for i in range(1,num+1): facto*=i return facto n= int( input("Enter a number for factorial:") ) print( "Factorial is", getFacto(n) ) # Q2) To find whether the given number is Armstrong number. def isArmstrong(num): num_len= len( str(num) ) digits_sum= 0 for digit in list(str(num)): digits_sum+= int( digit ) ** num_len if num == digits_sum: return True else: return False n= int( input("Enter a number to check for Armstrong Number:") ) if isArmstrong(n): print("It is an Armstrong Number.") else: print("It is not an Armstrong Number.") # Q3) Print Fibonacci series up to given term. def getFibo(n): fibo= [0,1] while len(fibo) <= n: fibo.append( fibo[-1] + fibo[-2] ) for num in fibo: print( num , end="\t" ) print() n= int( input("Enter the number of terms for Fibonacci Series:") ) getFibo(n) # Q4) Write a program to find prime number. def isPrime(x): lim= int(x**0.5) for i in range(2, lim+1): if x%i == 0: return False return True n= int( input("Enter a number to check for Prime:") ) if isPrime(n): print("The given number is prime.") else: print("The given number is not prime.") # Q5) Check whether given number is palindrome or not. def isPalindrome(n): n= str(n) for i in range( 0, len(n) ): if n[i] != n[ -1*i - 1 ]: return False return True n= int( input("Enter a number to check for Palindrome:") ) if isPalindrome(n): print("The given number is a palindrome.") else: print("The given number is not a palindrome.") # Q6) Write a program to print sum of digits. def sumOfDigits(num): num= list(str(num)) sum_of_digits= 0 for digit in num: sum_of_digits+= int(digit) return sum_of_digits n= int( input("Enter a number for sum of digits:") ) print( "Sum of digits is",sumOfDigits(n) ) # Q7) Count and print all numbers divisible by 5 or 7 between 1 to 100. counter= 0 for num in range(1,101): if num%5 == 0 or num%7 == 0: print(num, end=" ") counter+= 1 print( "\nIn 1 to 100, {} number(s) are divisible by 5 or 7.".format(counter) ) # Q8) All lower case to upper in string. string= input("Enter a String:") print("Upper case String is", string.upper()) # Q9) Print prime numbers between 1 and 100. def isPrimeNumber(x): lim= int(x**0.5) for i in range(2, lim+1): if x%i == 0: return False return True for num in range(2,100): if isPrimeNumber(num): print(num, end=" ") print() # Q10) Print the table for a given number: # 5 * 1 = 5 # 5 * 2 = 10 num= int( input("Enter a number to print table:") ) for i in range(1,11): print( " {} * {} = {} ".format(num, i, num*i) )
false
f0cf8343b7cb9293b5ecea2532953d0ca0b55d49
devaljansari/consultadd
/1.py
1,496
4.59375
5
"""Write a Python program to print the following string in a specific format (see the output). Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are""" print ("Trial 1 is :") print() print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!") print() print() print ("Trial 2 is :") print() print("Twinkle, twinkle, little star, \n") print(" How I wonder what you are! \n") print(" Up above the world so high, \n") print(" Like a diamond in the sky. \n") print("Twinkle, twinkle, little star, \n") print(" How I wonder what you are!") print();print() print ("Trial 3 is :") print() print("Twinkle, twinkle, little star, \ \n\tHow I wonder what you are! \ \n\t\tUp above the world so high,\ \n\t\tLike a diamond in the sky.\ \nTwinkle, twinkle, little star,\ \n\tHow I wonder what you are!") print() print() print ("Trial 4 is :") print() print("Twinkle, twinkle, little star, \n") print("\tHow I wonder what you are! \n") print("\t\tUp above the world so high, \n") print("\t\tLike a diamond in the sky. \n") print("Twinkle, twinkle, little star, \n") print("\tHow I wonder what you are!")
true
2b18385f2dc36a87477c3e7df27ff8bd2a988c33
heet-gorakhiya/Scaler-solutions
/Trees/Trees-1-AS_inorder_traversal.py
1,783
4.125
4
# Inorder Traversal # Problem Description # Given a binary tree, return the inorder traversal of its nodes values. # NOTE: Using recursion is not allowed. # Problem Constraints # 1 <= number of nodes <= 10^5 # Input Format # First and only argument is root node of the binary tree, A. # Output Format # Return an integer array denoting the inorder traversal of the given binary tree. # Example Input # Input 1: # 1 # \ # 2 # / # 3 # Input 2: # 1 # / \ # 6 2 # / # 3 # Example Output # Output 1: # [1, 3, 2] # Output 2: # [6, 1, 3, 2] # Example Explanation # Explanation 1: # The Inorder Traversal of the given tree is [1, 3, 2]. # Explanation 2: # The Inorder Traversal of the given tree is [6, 1, 3, 2]. # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return a list of integers def inorderTraversal(self, A): from queue import LifoQueue # Recursive solution # if not A: # return # self.inorderTraversal(A.left) # # ans_arr.append(A.val) # print(A.val) # self.inorderTraversal(A.right) # Iterative Solution using stack curr_node = A ans_arr = [] stack = LifoQueue() while True: if curr_node: stack.put(curr_node) curr_node = curr_node.left else: if not stack.empty(): temp = stack.get() ans_arr.append(temp.val) curr_node = temp.right else: return ans_arr
true
459ee1c60423011457183df6e5a897df77b7b62d
ani07/Coding_Problems
/project_euler1.py
491
4.28125
4
""" This solution is based on Project Euler Problem Number 1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ class MultiplesThreeFive(): def multiples(self): sum = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: sum += i return sum ans = MultiplesThreeFive() print(ans.multiples())
true
5d401b278b9e481bc02bfd5c57cedcbf945b9104
DeepakMe/Excellence-Technologies-
/QONE.py
309
4.15625
4
# Question1 # Q1.Write a function which returns sum of the list of numbers? # Ans: list1 = [1,2,3,4] def Sumlist(list,size): if (size==0): return 0 else: return list[size-1]+Sumlist(list,size-1) total = Sumlist(list1,len(list1)) print("Sum of given elements in List: ",total)
true