blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d76038a4603f933edd56521be326454183071c19
herealways/Data-Structures-and-Algorithms-Exercise
/Sorting/InsertionSort.py
449
4.1875
4
def insertionSort(numbers): for i in range(len(numbers)): current_item = numbers[i] j = i - 1 while j >= 0 and numbers[j] > current_item: numbers[j + 1] = numbers[j] j -= 1 numbers[j + 1] = current_item return numbers # e.g. # 44 99 6 # 44 99 99 # 44 44 99 # 6 44 99 if __name__ == "__main__": numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0] print(insertionSort(numbers))
true
5259742b4d7db3a86b6e933a2ea7411e20066e75
Rohanarekatla/python-basics
/#LISTS.py
906
4.5625
5
#LISTS # lists are used to store multiple items in a single item # they are defined with [] # they can be any type ex: int float string in single variable # lists are immutable # lists are ordered # allow dublicate values list=[12,'sec',3.0,8] print (list) # list methods (as these are functions () are complusary) '''1.append()''' list.append(8) print(list) '''2.clear()''' #list.clear() print(list) '''3.copy''' x=list.copy() print(x) '''4.count()''' x=list.count(8) print (x) '''5.index()''' print(list.index('sec')) '''6.insert''' x=list.insert(1,"1") print(list) '''7.pop()''' list.pop(2) print(list) '''8.remove''' list.remove('1') print(list) '''9.reverse''' x=list.reverse() print(list) '''10.sort''' list=[2,5,6,8,10,4] list.sort() print(list) list=[2,5,6,8,10,4] list.sort(reverse=True) print(list) '''11.extend''' list.extend([1,2,3]) print(list)
true
940f224a431dea06c35b6a190ec95e6723a22b33
willyudi/pythonexercicios02
/exercicio02_williano_02.py
383
4.125
4
#!/usr/bin/env python # encoding: utf-8 ano = int(input ('Informe o ano: ')) #Ano bissexto sua dezena é divisível por 4 e não termina em 00 #O ano terminado em 00 será bissexto se for divisível por 400 if (ano % 4 == 0 and ano % 100 != 0) or (ano % 400 == 0): print ('O ano ' + str(ano) + ' é bissexto.') else: print ('O ano ' + str(ano) + ' não é bissexto.')
false
f1677d6dad8eff7ac95ca7741319b992fce22bdd
MRossol/python-sp16
/lessons/divisible.py
1,937
4.375
4
from __future__ import print_function import sys def is_divisible(a, b): """Determines if integer a is divisible by integer b.""" remainder = a % b # if there's no remainder, then a is divisible by b if not remainder: return True else: return False def find_divisors(integer): """Find all divisors of an integer and return them as a list.""" divisors = [] # we know that an integer divides itself divisors.append(integer) # we also know that the biggest divisor other than the integer itself # must be at most half the value of the integer (think about it) divisor = integer / 2 while divisor >= 0: if is_divisible(integer, divisor): divisors.append(divisor) divisor =- 1 return divisors if __name__ == '__main__': # do some checking of the user's input try: if len(sys.argv) == 2: # the following statement will raise a ValueError for # non-integer arguments test_integer = int(sys.argv[1]) # check to make sure the integer was positive if test_integer <= 0: raise ValueError("integer must be positive") elif len(sys.argv) == 1: # print the usage if there are no arguments and exit print(__doc__) sys.exit(0) else: # alert the user they did not provide the correct number of # arguments raise ValueError("too many arguments") # catch the errors raised if sys.argv[1] is not a positive integer except ValueError as e: # alert the user to provide a valid argument print("Error: please provide one positive integer as an argument.") sys.exit(2) divisors = find_divisors(test_integer) # print the results print("The divisors of %d are:" % test_integer) for divisor in divisors: print(divisor)
true
cb4d97e20acde2780235fff2a8c1be71d0c60c15
mcshanej/JTC-App-1-Assignment
/tip_calculator.py
2,120
4.21875
4
# Requesting information from the user about the cost of food, number of people, and tip percentage # First I ask the user to input some information cost = input("How much does the food in your meal cost? ") #Found the try/except code recommendation here in the last comment: https://stackoverflow.com/questions/55885862/convert-input-str-to-int-in-python #this checks to make sure the 'cost' input can be converted to an float. If the input can't be converted to an float or integer (as appropriate for the question), this asks them to enter a number and repeats the question. This is required because mathematical operations can only be performed on int and float. try: cost = float(cost) except: print('Please enter a number') cost = input("How much does the food in your meal cost? ") #Converts cost input into an float cost = float(cost) #as above, checks to make sure that the input is an integer people = input("How many people will be splitting the check? ") try: people = int(people) except: print('Please enter a whole number') people = input("How many people will be splitting the check? ") #converts people input into an integer (can't have partial people) people = int(people) #as above, checks to make sure that the input is a float (people MAY want to leave part of a percentage, though 15.75% seems a bit strange....) tip = input("How much of a tip would you like to leave? ") try: tip = float(tip) except: print('Please enter a percentage in number form') tip = input("How much of a tip would you like to leave? ") #converts tip input into a float tip = float(tip) #Creating a variable to calculate the total cost of the meal by adding the cost of the food, the amount of the tip, and the sales tax total = (cost) + (cost *(tip/100)) + (cost/10) #Calculating the amoun each person owes per_person = total / people #Telling the user the total cost and each person's share after the tip and sales tax. print(f"The total cost of the meal, including the tip, is ${total}. Because there are {people} people in your party, each person's share is ${per_person}.")
true
a3fc214f3a90d94874b598fcddad96c8a5a512b2
YuriiShp/Python-lessons
/homework_3_1.py
870
4.28125
4
# 1. Дан список чисел. Необходимо вывести в отдельные списки (три списка пустых) такие числа: # в первый добавляем все числа которые делятся на 2 # во второй - те которые делятся на три # в третий - те которые не подходят под первые два условия some_list = [1, 2, 3, 4, 5, 6, 8, 98, 54, 34, -7, 0] div_by_2 = [] div_by_3 = [] other_num = [] for el in some_list: if el % 2 == 0: div_by_2.append(el) if el % 3 == 0: div_by_3.append(el) if not(el % 2 == 0 or el % 3 == 0): other_num.append(el) print('Numbers div by 2: {}'.format(str(div_by_2))) print('Numbers div by 3: {}'.format(str(div_by_3))) print('Other numbers: {}'.format(str(other_num)))
false
c2ee2dc66efc769e92ccbf1c239785b342f48256
YuriiShp/Python-lessons
/homework_3_2.py
738
4.28125
4
# 2. Пользователь вводит строку и символ (одну букву). Проверить есть ли в этой строке введенный символ. some_str = input('Input text: ') some_symbol = input('Searching symbol: ') # Var 1. some_set = set(some_str) n_of_steps = len(some_set) while n_of_steps > 0: if some_symbol == some_set.pop(): print('symbol {} is in string {}'.format(some_symbol, some_str)) break n_of_steps -= 1 if n_of_steps == 0: print('symbol {} not found'.format(some_symbol)) # Var 2. if some_symbol in some_str: print('symbol {} is in string {}'.format(some_symbol, some_str)) else: print('symbol {} not found'.format(some_symbol))
false
4e499f456789c1748c221f6e67ac375d6d628309
MasonDG/COURSEWORK-FINISHED
/Question 2.py
843
4.25
4
def zeroes(x): factorial = x zeroes = 0 #the following code is performed as many times as the value of the factorial number in increments of one for factorial in range(1,factorial+1): #run the function as long as a number exists while factorial > 0: #if the number can no longer be divided whole by 5, break the function, otherwise add 1 to zeroes and divide factorial number by 5, then run whilst it still meets the while loop. if factorial % 5 != 0: #every time 5 can be divided to give no remainder, a zero is added. the number passed is ran through the conditionals again. break else: factorial = factorial / 5 zeroes = zeroes + 1 return zeroes
true
16479e3c4b5bd727dc35ad4f3bb4f884505840ea
rishikajain25/jupyterfiles
/jupyter1.py
693
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print ("hello world") # In[2]: i=1 while i<=10: print(i) i=i+1 # In[25]: def operations(num1,num2,operator): if(operator == '+'): result= num1+num2 print(result) elif(operator == '-'): result= num1-num2 print(result) elif(operator == '*'): result= num1*num2 elif(operator == '//'): result= num1//num2 elif(operator =='%'): result= num1%num2 elif(operator=='/'): result= num1/num2 else: result=0 print("Answer: {} : ({},{}) : result={}" .format(operator,num1,num2,result)) operations(5,2,'//') # In[ ]: # In[ ]:
false
80202c70ab78a4e0634a3347951bf575e86c353d
kritikadusad/calculator-2
/calculator.py
2,202
4.28125
4
"""A prefix-notation calculator. Using the arithmetic.py file from Calculator Part 1, create the calculator program yourself in this file. """ import sys import string from arithmetic import * operations = ['+', '-', '*', '/', 'square', 'cube', 'pow', 'mod', 'x+', 'cubes+'] while True: user_input = input('What do you want to do: ') tokens = user_input.split(' ') tokens_length = len(tokens) try: num1 = float(tokens[1]) num2 = float(tokens[2]) num3 = float(tokens[3]) except ValueError: print("Incorrect input. Try again") continue except IndexError: pass # Initializing operated_result to None operated_result = None if tokens[0] == 'q': print('Goodbye!') sys.exit() else: if tokens[0] not in operations: print('Incorrect operator. Please try again!') continue elif tokens_length == 2: if tokens[0] == 'square': operated_result = square(num1) print(operated_result) elif tokens[0] == 'cube': operated_result = cube(num1) print(operated_result) elif tokens_length == 3: if tokens[0] == '+': operated_result = add(num1, num2) print(operated_result) elif tokens[0] == '-': operated_result = subtract(num1, num2) print(operated_result) elif tokens[0] == '*': operated_result = multiply(num1, num2) print(operated_result) elif tokens[0] == '/': operated_result = divide(num1, num2) print(operated_result) elif tokens[0] == 'pow': operated_result = power(num1, num2) print(operated_result) elif tokens[0] == 'mod': operated_result = mod(num1, num2) print(operated_result) elif tokens[0] == 'cubes+': operated_result = add_cubes(num1, num2) print(operated_result) else: print('You are providing an incorrect input. Try again!') elif tokens_length == 4: if tokens[0] == 'x+': operated_result = add_mult(num1, num2, num3) print(operated_result) else: print('You are providing an incorrect input. Try again!') else: print('You are giving too many numbers for this operation. Try again!') continue # elif tokens[0] == '**': # operated_result = subtract(num1, num2) # print(operated_result)
true
123d5108f10da0ae69302314fc0dd823fff16047
verdatestudo/Edx_HarvardX_PH526x
/dna_caesar/caesar.py
1,234
4.21875
4
''' Week 3/4 - Case Study 1 from HarvardX: PH526x Using Python for Research on edX A cipher is a secret code for a language. In this case study, we will explore a cipher that is reported by contemporary Greek historians to have been used by Julius Caesar to send secret messages to generals during times of war. Last Updated: 2016-Dec-20 First Created: 2016-Dec-20 Python 3.5 Chris ''' # Let's look at the lowercase letters. import string def caesar(message, key): ''' Takes a message string and an int key and returns the coded caesar message. ''' # define `coded_message` here! coded_message = {letter: (idx + key) % 27 for idx, letter in enumerate(alphabet)} return ''.join([letters[coded_message[letter]] for letter in message]) # We will consider the alphabet to be these letters, along with a space. alphabet = string.ascii_lowercase + " " # create `letters` here! letters = {idx: letter for idx, letter in enumerate(alphabet)} # Use caesar to encode message using key = 3, and save the result as coded_message. message = "hi my name is caesar" coded_message = caesar(message, 3) print(coded_message) decoded_message = caesar(coded_message, -3) print(decoded_message)
true
61b0e00f040bd31e5c61f35f90c2cb383169a6e6
Haozhuo/practice
/python/array/q243.py
858
4.15625
4
""" Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Given word1 = “coding”, word2 = “practice”, return 3. Given word1 = "makes", word2 = "coding", return 1. Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. """ def shortestDistance(self, words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ pos1 = -1 pos2 = -1 diff = len(words) for i,val in enumerate(words): if val == word1: pos1 = i elif val == word2: pos2 = i if pos1 != -1 and pos2 != -1: diff = min(diff,abs(pos1-pos2)) return diff
true
3477731e117b6f7ec498c304d7b63b7ef76201ae
Haozhuo/practice
/python/hash_table/q246.py
632
4.3125
4
""" A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers "69", "88", and "818" are all strobogrammatic. """ def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ dic = {} dic["0"],dic["1"],dic["6"],dic["8"],dic["9"] = "0","1","9","8","6" s, e = 0, len(num) - 1 while s <= e: if num[s] not in dic or dic[num[s]] != num[e]: return False s += 1 e -= 1 return True
true
5ba9fc405cc2f9b0fa6acb90fbe1a6e9b20c53f2
caylemh/Python
/chapter_4/pg110_TryItYourself.py
959
4.5
4
# Counting to Twenty - using a 'for' loop for value in range(21): print(value) # One Million - making a list to contain the numbers from 1 to 1000000 numbers = list(range(1,1000001)) print(numbers) # Summing a Million - using the min(), max() and sum() functions print(f'\nThe smallest number in the list is: {min(numbers)}') print(f'The largest number in the list is: {max(numbers)}') print(f'The sum of all the numbers in the list is: {sum(numbers)}\n') # Odd Numbers - using the third argument in the range() function for odd_num in range(1,21,2): print(odd_num) print("") # Threes - making a list of the multiples of 3 from 3 to 30 using a 'for' loop to print them for value in range(3,31,3): print(value) # Cubes - numbers raised to the power of 3 cubes = [] for value in range(1,11): cubes.append(value**3) print(f'\n{cubes}\n') # Cube Comprehension cubes = [value**3 for value in range(1,11)] print(f'\n{cubes}\n')
true
9d00e43d21286dc51cbd3133e967752bbb4d14d1
sgoodspeed/CS112-Spring2012
/Notes/Notes-Class/writingFiles.py
877
4.40625
4
#!usr/bin/env python #writes file with name, w designates right, we can also use 'r' for read, file_in = open("textFile.txt","w") for line in file_in: print line #Prints all the lines of the file file_in.write("stuff we are writing to file.\n") #python documentation for file or open commands it will tell you the whole list of r, w, those things. try: file_in = open("textFile.butts","r") for line in file_in: print line file_in.close() except IOError: print "Incorrect file name" #after except you can have text that specifies which except code to run in the case of specific errors, for instance in this case IOError for wrong file. # the above block of code will try to pull open the file, but if it doesn't exist, has the wrong name typed (as in this example) or whatever, the code will keep running and it will run the except line.
true
9a06d25715476c95c3b1d2c5815f79b1c41c328f
sgoodspeed/CS112-Spring2012
/Notes/Notes-Friday/randomStuff/methods.py
2,338
4.28125
4
#!usr/bin/env python class Enemy(object): _objects = []#_ in front makes it private def __init__(self,name): Enemy.objects.append(self) self.name = name def update(self): print self.name,"is in your base" def kill(self): print self.name,"is dead" Enemy._objects.remove(self) @classmethod def all(cls): return cls._objects[:]# Note 1 @classmethod def all(cls): x,y = 0,0 vx,vy = 0,0 color = 255,0,100 return Enemy(x,y,vx,vy,color,bounds) #Note 2 class Vector: @staticmethod#NOTE 3 def dot(a,b): print "no" Enemy.spawn(screen.get_rect()) #the variables in the example are all zeros, in real life we would use #randrange or something to set up some parameters. Vector.dot(a,b) a = Enemy ("A") b = Enemy("B") c = Enemy("C") for enemy in Enemy.objects: enemy.update() c.kill() for enemy in Enemy.objects: enemy.update() #NOTE 1 #this makes a COPY of a list of all the things in objects[], so that you can #fuck around with that list that w made without accidentally changing values #that live in Enemy. Basically what Object oriented programming is all about, #in that it is keeping different methods objects and functions seperate and #unable to change each other's data unwittingly. #NOTE 2 #So, it'd be nice if we had a thing that could create a random tie fighter in random bounds, which is what this stuff does. Instead of spawning them we can just call this function, (WHICH THOUGH IT IS CLASS SPECIFIC DOES NOT REQUIRE AN INSTANCE OF ENEMY TO EXIST TO CALL IT CREATES ONE.) we call this and it makes one. This example does NOT work though hahahaha. #Note 3 #this lets you define a method of a class that does not need self. This means #you can call this method without initializing Vector. This is good for a code #clarity thin, and little else, because now our call of the function clearly #says 'vector' which is better than a.dot(a,b) or whatever if it wasnt in a #class Vector. ####################################### #class Enemy(Sprite): # _all_bullets = Group() # def shoot(self): # Bullet(Enemy._all_bullets, self.bullets) #Let's us track bullets as a group of all bullets, and ALSO as the bullets belonging to a single enemy class.
true
d69dc17a40760cce5cf1ff6be3a1cd1c1f90da08
sgoodspeed/CS112-Spring2012
/Notes/Notes-Friday/fri-1/strings1.py
1,768
4.5625
5
#!usr/bin/env python print """ These triple-quotes let me... Do all the formatting within it! Cool. """ #to find and print the binary of a number, type bin(11) #and for the hexadecimal use: hex(357) #This is the format for all functions like these # int sets an integer, float sets a float, raw_input sets a string (I THINK!!) #int(a) is the format for this #SAMPLE UH SORT OF #print n = int(raw_input("Enter a number: ")) #This takes a number from user and sets n to that number #abs is for absolute value, str is for string. #min, max. The function min(2,3,4,1) will return you the lowest number you put in #Shit what does this do we don't REALLY need it but it's some sort of conversion thing... #int("0xff",16) #OK next section is about string formatting. Diffuculut QUESTION MARK??? #Say you wanted to print "Hi Jim, thanks for the bear." #But what if name is just: #name='Jim' #And pear is #item='pear' #Well, you need to... #"Hi "tname", thanks for the "titemt"." #But that is really ugly. Try this: #msg = Hi %s, thanks for the %s."%(name,item) #print msg #Wooooo old school name="Jim" item="bear" msg = "Hi %s, thanks for the %s."%(name,item) print msg #alternatively: msg2="Hi %s, thanks for the %s." print msg2 %(name,item) #%s string #%d decimal #%f float #You will notice if you try to do print 3 print 100 print 11 #It comes out all ugly in spacing print "%4d" % 6 #though, will give you a number of spaces equivalent hereto the numbr, in this case 4 #And here print "%04d" % 16 #fills in the spaces with zeroes #Taking user input: #to take input name3 = raw_input("Enter your name: ") inp = raw_input("%s: " % name3) print "input was: %s" % inp #assigning multiple variables at once x,y = 3,4 print x print y print x, y
true
60a11f24a6cd005b08449045ecf5fd7f34e920cf
sgoodspeed/CS112-Spring2012
/hw03/conversion.py
1,085
4.1875
4
#!usr/bin/env python print """ Conversion table: 1 Fractional reduction: 2 """ selIn=raw_input("Choose a procedure: ") selIn1=int(selIn) if selIn1==1: numIn1=raw_input("Enter numbers you would like to convert: 1: ") num1=int(numIn1) numIn2=raw_input("2: ") num2=int(numIn2) numIn3=raw_input("3: ") num3=int(numIn3) numIn4=raw_input("4: ") num4=int(numIn4) numIn5=raw_input("5: ") num5=int(numIn5) print print "Numbers" print num1,num2,num3,num4,num5 print "Hexadecimal" numH1=hex(num1) numH2=hex(num2) numH3=hex(num3) numH4=hex(num4) numH5=hex(num5) print numH1,numH2,numH3,numH4,numH5 print "Binary" numB1=bin(num1) numB2=bin(num2) numB3=bin(num3) numB4=bin(num4) numB5=bin(num5) print numB1,numB2,numB3,numB4,numB5 elif selIn1==2: numIn1=raw_input("Enter fraction you would like to reduce: Numerator: ") num1=float(numIn1) numIn2=raw_input("Denominator: ") num2=float(numIn2) num3=num1/num2 print """ %f / %f = %f """ % (num1,num2,num3)
false
d9d37468741338c68d5c20ab1fc63bad8d66f4b8
sgoodspeed/CS112-Spring2012
/Notes/Notes-Class/lists-for/forLoops.py
1,074
4.53125
5
#!/usr/bin/env python titles=["Hitchikers guide to the galaxy", "Resteraunt at the end of the universe", "Life the unierse and everthing"] titles.append("So Long and Thanks for all the fish") titles.append("Mostly Harmless") #So, the for loop sets the variable (in this case title) and then give it your list, (titles) and then it runs through the loop for each element, in this case printing title for title in titles[0:3]:#This prints elements 0,1 and 2. The last number referenced is 'non-inclusive' so we don't get three, in this case print title for i in range(10): print i #The above for loop prints 0-9, so this range command creates a list of 10 elements, 0-9, and then i is each of them, iterating up and counting for i in range(1,11): print i #This prints 1-10 #For counting by a multiple of something for i in range(1,11,2): print i #Now it counts 1-10 by twos #numbers is a list, 0-99 numbers=range(100) #The following counts by .2 UHHHHH for i,n in enumerate(numbers): numbers[i]=n*.2 print numbers
true
15d0800113b03973537b429fb2cbbfd79dd3fecb
sgoodspeed/CS112-Spring2012
/hw04/sect2_while.py
988
4.5625
5
#!/usr/bin/env python from hwtools import * print "Section 2: Loops" print "-----------------------------" # 1. Keep getting a number from the input (num) until it is a multiple of 3. num = 1 while num%3!=0: num = int(raw_input("Input a multiple of three. Or, don't: ")) print "1. num= %i and it is now a multiple of 3." % num # 2. Countdown from the given number to 0 by threes. # Example: # 12... # 9... # 6... # 3... # 0 print "2. Countdown from", num while num>=0: print num num-=3 print "Brastoff" # 3. [ADVANCED] Get another num. If num is a multiple of 3, countdown # by threes. If it is not a multiple of 3 but is even, countdown by # twos. Otherwise, just countdown by ones. num = int(raw_input("3. Countdown from: ")) if num%3==0: while num>=0: print num num-=3 elif num%2==0: while num>=0: print num num-=2 else: while num>=0: print num num-=1
true
b85501d42093c49163b49181094b72d4042be3d4
Prasanna-Kumar-1/Algorithms-Python
/BinarySearch.py
1,838
4.28125
4
def binary_search(sorted_collection, item): """Implementation of binary search algorithm in Python. Collection must be ascending sorted :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found """ def binary_search(input_list, item): first = 0 last = len(input_list) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if input_list[midpoint] == item: found = True else: if item < input_list[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return found def __assert_sorted(collection1): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is ascending sorted :raise: :py:class:`ValueError` if collection is not ascending sorted ... ValueError: Collection must be ascending sorted """ if collection != sorted(collection): raise ValueError("Collection must be ascending sorted") return True if __name__ == "__main__": import sys user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item) for item in user_input.split(",")] print(collection) try: __assert_sorted(collection) except ValueError: sys.exit("Sequence must be ascending sorted to apply binary search") target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = binary_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
true
f73d81298824f2165865e917006e109065b4d157
Prasanna-Kumar-1/Algorithms-Python
/Anagram.py
1,142
4.5625
5
# Implementation of Anagrams # Two strings are anagrams if they are made up of the same letters arranged differently(ignoring the case). # Examples: # (1) ''Silent' & 'Listen' # (2) 'This is a string', 'Is this a string' # string1 = 'Silent' # string2 = 'Listen' # 1. Convert the string to lower case # print(string1.lower()) # 2. sort the letters using sorted() method, this creates a list of letters like ['e', 'i', 'l', 'n', 's', 't'] # print(sorted(string1.lower())) # 3. Use join() function to construct the string back again # print("".join(sorted(string1.lower()))) def check_anagram(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made of the same letters arranged differently (ignoring the case). """ return ( "".join(sorted(first_str.lower())).strip() == "".join(sorted(second_str.lower())).strip() ) if __name__ == "__main__": string1 = input("Enter 1st String : \n") string2 = input("Enter 2nd String : \n") status = check_anagram(string1, string2) print(f"{string1} & {string2} are {'' if status else 'not '}anagrams.")
true
9be9a06a5976e272c6f76a1e0363c77dde45f10f
Devin-Bielejec/Intro-Python-I
/src/14_cal.py
1,081
4.34375
4
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: NONE => current month - one arg => curren month - month and year - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime def program(): userInput = input("Please enter the month, then the year:") inputList = userInput.split(" ") if len(inputList) > 2: print("Incorrect form, input should be [month] [year]") return if userInput == "": m = datetime.today().month y = datetime.today().year if len(inputList) == 1: m = inputList[0] y = datetime.today().year if len(inputList) == 2: m = inputList[0] y = inputList[1] print(calendar.month(int(y), int(m))) program()
true
a7abf1ca419549d57be74e2a54a4dedeb5314266
codefoxut/pycourses
/design_patterns/design-patterns-python/prototype/prototype.py
1,206
4.21875
4
import copy class Address: def __init__(self, street_address, city, country): self.street_address = street_address self.city = city self.country = country def __str__(self): return f'{self.street_address}, {self.city}, {self.country}' class Person: def __init__(self, name, address): self.name = name self.address = address def __str__(self): return f'{self.name} lives at {self.address}' if __name__ == '__main__': print('----step1---') address1 = Address('123 london road', 'london', 'UK') john = Person('John', address1) print(john) jane1 = john jane1.name = 'Jane' print(john, '\n', jane1) print('----step2---') john = Person('John', address1) jane2 = Person('Jane', address1) print(john, '\n', jane2) jane2.address.street_address = '123b london road' print('after address change.') print(john, '\n', jane2) print('----step3---') address2 = Address('123 london road', 'london', 'UK') john = Person('John', address2) jane3 = copy.deepcopy(john) jane3.name = 'Jane' jane3.address.street_address = '123b london road' print(john, '\n', jane3)
false
5ef1802c38f91a30b3d3902d7e65e6beee03c131
xr1217/cpy5python
/Practical 04/q7_find_largest.py
624
4.3125
4
# Filename: q7_find_largest.py # Author: Chia Xiang Rong # Date created: 3/3/13 # Date modified: 3/3/13 # Description: Returns the largest integer in an array alist #Create list and prompt input of integers alist = [] x = int(input("Enter number of integers: ")) for i in range(0,x): num = int(input("Enter integer: ")) alist.append(num) #Define function find_largest(alist) def find_largest(alist): if len(alist) == 1: return alist[0] else: if alist[0] > alist[1]: alist[1] = alist[0] return find_largest(alist[1:]) print("Largest integer is: " + str(find_largest(alist)))
true
8577f82f027346bb3b5abecf7a0efa5ea980935f
xr1217/cpy5python
/Practical 01/q1_fahrenheit_to_celsius.py
444
4.25
4
# Filename: q1_fahrenheit_to_celsius.py # Author: Chia Xiang Rong # Date created: 22/1/2013 # Date modified: 22/1/2013 # Description: Convert Fahrenheit degree in double to Celsius # Prompt input of Fahrenheit degree in double fahrenheit = float(input("Enter temperature in Fahrenheit: ")) # Convert to Celsius celsius = (5/9) * (fahrenheit - 32) # Display Celsius degeee print ("Temperature in Celsius (to nearest degree): {0:.0f}".format(celsius))
false
8c29e2ccfab25375947f3848a7a22e40b7670707
Ankit-29/competitive_programming
/Stack/minAddToMakeParenthesesValid.py
1,021
4.28125
4
''' Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. Input: "())" Output: 1 Input: "(((" Output: 3 Input: "()))((" Output: 4 Input: "()" Output: 0 ''' def minAddToMakeValid(S: str) -> int: stack = list() size = 0 for x in S: if(x == "("): stack.append(x) size += 1 else: if(size and stack[-1]=="("): stack.pop() size -= 1 else: stack.append(x) size += 1 return size S = "()))((" print(minAddToMakeValid(S))
true
2f4bed5907a141ec040e79a06c29a022b667fb33
Ankit-29/competitive_programming
/HashTable/sortCharacterByFrequency.py
722
4.125
4
''' Given a string, sort it in decreasing order based on the frequency of characters. Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Input: "cccaaa" Output: "cccaaa" ''' def frequencySort(s: str) -> str: Hash = dict() for letter in s: if(letter in Hash): Hash[letter] += 1 else: Hash[letter] = 1 itemList = list(Hash.items()) itemList.sort(key=lambda x:(x[1],x[0]), reverse=True) string = "" for item in itemList: string += item[0]*item[1] return string s = "tree" print(frequencySort(s))
true
88001116fa4eda5c2f4abc664b435e6b7b8fd184
Ankit-29/competitive_programming
/BitManipulation/alternatingBits.py
554
4.1875
4
''' Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Input: 7 Output: False Explanation: The binary representation of 7 is: 111. ''' def hasAlternatingBits(n: int) -> bool: lastBit = n & 1 while(n): n //= 2 currBit = n & 1 if(not(lastBit ^ currBit)): return False lastBit = (n & 1) return True n = 5 print(hasAlternatingBits(n))
true
25040e1a8a2ceb7e81bf56f026ad3aa228933803
Ankit-29/competitive_programming
/HashTable/longSubStrWithoutRepeat.py
824
4.15625
4
# Longest Substing without Repeating Characters ''' Given a string, find the length of the longest substring without repeating characters. e.g. "pwwkew" -> 3 "dvdf" -> 3 "abcabcbb" -> 3 "bbbbb" -> 1 "abba" -> 2 "tmmzuxt" -> 5 ''' def lengthOfLongestSubstring(s: str) -> int: longest = 0 left = 0 # Left most index of current substring Hash = dict() for x in range(len(s)): # Check if character already present if(s[x] in Hash): # Change Left index left = max(Hash[s[x]]+1,left) # Update Hash Hash[s[x]] = x # Calculate longest length longest = max(longest,x - left + 1) return longest s = "tmmzuxt" print(lengthOfLongestSubstring(s))
true
a72b4700444d13cbc5ce8ba9f4068f1c34dfb132
Ankit-29/competitive_programming
/Matrix/spiralMat.py
971
4.40625
4
# Spiral Matrix ''' Given a 2D array, print it in spiral form. e.g. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 ''' from typing import List def spiralMat(mat: List[List[int]]) -> List[int]: row = len(mat) col = len(mat[0]) if mat[0] else 0 spiral = list() for x in range(row//2+1): for y in range(x, col-x): spiral.append(mat[x][y]) if(x!=(row//2)): for y in range(x+1, row-x): spiral.append(mat[y][col-x-1]) for y in range(col-x-2, x-1, -1): spiral.append(mat[row-x-1][y]) for y in range(row-x-2, x, -1): spiral.append(mat[y][x]) return spiral mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] # mat = [ # [1, 2, 3, 4, 5, 6], # [7, 8, 9, 10, 11, 12], # [13, 14, 15, 16, 17, 18], # ] print(spiralMat(mat))
false
30130063fd1f069d3a568c863d9fe36cfd52ba29
Ankit-29/competitive_programming
/Numbers/topKFrequentElements.py
660
4.15625
4
''' Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] ''' from typing import List def topKFrequent(nums: List[int], k: int) -> List[int]: Hash = {} ret = [] for x in nums: if(x in Hash): Hash[x] += 1 else: Hash[x] = 1 Hash = dict( sorted(Hash.items(), key=lambda item: item[1], reverse=True)) for x in Hash.items(): ret.append(x[0]) if(len(ret) == k): break return ret nums = [1,1,1,2,2,3]; k = 2 print(topKFrequent(nums,k))
true
466c878bfdf897c0f65194b3a044af692e7db39d
Ankit-29/competitive_programming
/HashTable/groupAnagram.py
556
4.21875
4
# Group Anagrams ''' Given an array of strings, group anagrams together. ''' def groupAnagrams(strs: list) -> list: Hash = dict() for s in strs: freq = [0]*26 # Frequency List for x in s: # Calculate Frequency freq[ord(x)-ord('a')] += 1 # Make Key for Hash using freq list key = tuple(freq) if(key not in Hash): Hash[key] = list() Hash[key].append(s) return list(Hash.values()) strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams(strs))
true
923b9d2b16d442556377d1cfa8ac29f7530bec7a
Ankit-29/competitive_programming
/Strings/stringMultiply.py
841
4.375
4
''' Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly. ''' def multiply(num1: str, num2: str) -> str: return toInt(num1)*toInt(num2) def toInt(num: str) -> int: Hash = {"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"0":0} if(num in Hash):return Hash[num] place = 10**(len(num)-1) ret = 0 for x in num: ret += Hash[x]*place place //=10 return ret num1 = "123"; num2 = "456" print(multiply(num1,num2))
true
00952975408af685675e72dbc72e10c00656ddba
shressujan/Intro-to-Python
/reverse-singly-linked-list.py
2,060
4.1875
4
class ListNode: """ Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Input: 4 -> 3 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 2 -> 3 -> 4 -> NULL""" def __init__(self, x): self.val = x self.next = None def add_item(self, x): if self.val is None: self.val = x return while self.next: self = self.next self.next = ListNode(x) def printList(self): node = self output = '' while node is not None: output += str(node.val) output += ' ' node = node.next print(output) @staticmethod def reverseIteratively(head): current_node = head num = 0 step = 10 while current_node: num = num * step + current_node.val current_node = current_node.next # Create list lst = ListNode(None) while num != 0: rem = num % step lst.add_item(rem) num //= step return lst # def reverseRecursively(self, head, num): # current_node = head # if current_node.next: # num = num * 10 + current_node.val # ListNode.reverseRecursively(self, current_node.next, num) # # if self is None: # self.val = current_node.val # else: # self.next = current_node if __name__ == '__main__': # Test Program # Initialize the test list: testHead = ListNode(4) node1 = ListNode(3) testHead.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(1) node2.next = node3 testTail = ListNode(0) node3.next = testTail print('Initial list: ') testHead.printList() lst = testHead.reverseIteratively(testHead) print('List after reversal: ') lst.printList() # lst = ListNode(None) # lst.reverseRecursively(testHead, 0) # print('List after reversal: ') # lst.printList()
true
fee269ccfd3d725f0ae2b4cf439a93b3f8b187c9
deepa-project/Eclipse-AWS-Java-Projects
/LearningPython/zipfunction_PascalTriangle.py
414
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 24 13:54:45 2020 @author: deepa PascalTriangle_zip function :https://www.askpython.com/python/examples/pascals-triangle-using-python """ def PascalTriangle(n): trow = [1] y=[] for x in range(n): print(trow) trow=[left+right for left,right in zip(trow+y, y+trow)] return n>=1 n=int(input("Enter an integer value: ")) PascalTriangle(n)
true
d04bb03e2ae45291dfb084640e07ebfb7d19c887
bunnycou/CSET-Work
/Lab Practice/wk3/Q2.py
808
4.34375
4
# import math import math as m ############ # Question 2 ############ print ("Question 2 - Calculate triangle angles from three coordinates") # collect inputs of coordinates x1, y1 = eval(input("Input first point (x, y): ")) x2, y2 = eval(input("Input second point (x, y): ")) x3, y3 = eval(input("Input third point (x, y): ")) # calculate the sides a = m.sqrt((abs(x1 - x2)**2) + (abs(y1 - y2)**2)) b = m.sqrt((abs(x2 - x3)**2) + (abs(y2 - y3)**2)) c = m.sqrt((abs(x1 - x3)**2) + (abs(y1 - y3)**2)) # calculate the angles A = m.degrees(m.acos((a**2 - b**2 - c**2) / (-2 * b * c))) B = m.degrees(m.acos((b**2 - a**2 - c**2) / (-2 * a * c))) C = m.degrees(m.acos((c**2 - b**2 - a**2) / (-2 * a * b))) # display results print(f"\nThe angles are {round(A*100)/100}, {round(B*100)/100}, {round(C*100)/100}")
false
861369d374836dd1a8b450cb80576ed8ca7b6ddb
bunnycou/CSET-Work
/Lab Assignments/wk3/Q2.py
581
4.28125
4
# Noah Cousino # R01506332 # import and set turtle from turtle import Turtle, Screen turtle = Turtle() screen = Screen() # set universal turtle properties turtle.pensize(5) # create a function that draws the circle given coordinates and color def circ(color, x, y) : turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.color(color) turtle.circle(50) # draw the circles # b, bk, r, y, gr circ("blue", -90, 25) circ("black", 0, 25) circ("red", 90, 25) # second row circ("yellow", -45, -25) circ("green", 45, -25) # exit when user clicks screen.exitonclick()
false
cb786a6324bdd84f2c93eef944f63d1957664210
bunnycou/CSET-Work
/Lab Assignments/wk1/Q3.py
296
4.125
4
# Noah Cousino # R01506332 # Store information in variables dist = 14 #km time = 45.5 #min # find our miles and hour mi = dist/1.6 hr = time/60 # calculate mph mph = mi/hr # display result using f string print(f'{mph} mph') # displays result rounded to the tenths place print(f'{round(mph, 1)} mph')
true
8bd93044bceb849292bd1c7f8cd35841dc5ccb9c
Cjames21082/Python-Basics
/ex6.py
825
4.5
4
# Strings and Text # Assigning a string to a variable. String format d represents that number ten. x = "There are %d types of people." %10 # Assigning a string to a variable binary = "binary" do_not = "don't" # This string references the two variables as string formats y = "Those who know %s and those who %s" % (binary, do_not) # Python prints variable x and y print x print y # Python prints the string with variable x through a formatted variable print "I said: %r." %x print "I also said: '%s'." %y # Assigning boolean false to hilarious! hilarious = False # Assigned string to joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" #Print to python print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." f = 10 # Print concatenated strings print w + e
true
7c67043bae42ec3839674a8614a494637d7123b0
Mehul-Popat/python-basics
/Lists and Range.py
890
4.46875
4
## Lists and Range ## A list contains sequence of values in [] ## Each value can be float, int, or string ## Each value in list is called an element ## List can contain: ## Nested lists ## Tuples ## Dictionaries ## And much more ## ## Mutable ## ## Elements in a list and dictionaries are mutable ## Elements in a tuple or string aren't mutable ## ## Range generated a specefied list of numbers ## Used with loops print(list(range(11))) print(list(range(5, 11))) print(list(range(0, 22, 2))) num = [2, 5, 3, 7, 4, 10] print(type(num)) print(num) num.sort() print(num) num.reverse() print(num) items = ["cars", "bike", "plane"] print(items) items.append(num) print(items) items[3].insert(2, ["hello"]) print(items) print(items[0]) print(items[3]) print(items[3][2]) print(items[3][2][0])
true
7759a2ffc2fbfd22983e9b94fdf55beb9b5dd52a
tkanicka/python_learning
/homework(november)/homeworkAssigment2/circle.py
527
4.28125
4
def print_circle(r): d = 2*r for column in range(d+1): for row in range(d+1): circuit_distance = ((column - r)**2 + (row - r)**2)**0.5 if (circuit_distance > r - 0.5 and circuit_distance < r + 0.5): # making a tolerance so the distance is +- r print("*", end = " ") else: print(" ", end = " ") print() # goes to another line without making extra space r = int(input("give me your radius: ")) print_circle(r)
true
f5620bac3c077648c72e4defdc1ab269d1325b25
heitormariano/python-estudos
/tutorials-point/atribuicoes.py
469
4.15625
4
print('Brincando com atribuicoes') a = b = c = 3000 print(a, b, c) num01, num02 = 10, 45 print(num01) print(num02) print('O primeiro número informado foi {} e o segungo foi {}'.format(num01, num02)) contador, salario, nome = 34, 1560.45, 'Jose' print("Contador: " + str(contador)) print("Salario: " + str(salario)) print("Nome: " + nome) print('Mais uma brincadeira com Strings') print('O contador: {}. O salário: {}. O nome: {}'.format(contador, salario, nome))
false
45535a64cf5b2428c8ce6d3424ee5fd53df36a38
ydong08/PythonCode
/sourcecode/08/8.5/overload.py
723
4.1875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- class Fruit: def __init__(self, price = 0): self.price = price def __add__(self, other): # ؼӺ return self.price + other.price def __gt__(self, other): # ش if self.price > other.price: flag = True else: flag = False return flag class Apple(Fruit): pass class Banana(Fruit): pass if __name__ == "__main__": apple = Apple(3) print "ƻļ۸", apple.price banana = Banana(2) print "㽶ļ۸", banana.price print apple > banana total = apple + banana print "ϼƣ", total
false
2766b8b2389d517ba855f69b91975bebaff1ffb9
ydong08/PythonCode
/test_code/class/class_test.py
1,218
4.5
4
'''' class test code ''' #coding=utf-8 class Man: ''' class variables NOTE: 1. instance variables cannot change class variables 2. can be add class or instance variables dynamicly 3. instance have all class variables ''' sex = 'male' ''' init function, not constructor function ''' def __init__(self): ''' instance variables ''' self.name = 'china' self.age = '5000' self.city = 'asia' ''' instance method both class and instance can call this 'methodx' instance.method('HeNan') or Man.method(instance, 'HeNan') ''' def method(self, index): print(index, self.sex, self.city) ''' class method, only class can call this method ''' @classmethod def class_method(cls, index): print(index, cls.sex) ''' same as method, both class and instance can call static_method however, it dosenot need self or cls parameter ''' @staticmethod def static_method(index): print(index) if __name__ == '__main__': Man.tall = '1000' Man.hands = 10 print(Man.sex) print(Man.tall) print(Man.hands) man = Man() man.road = 'people' print(man.road) man.method('1') Man.method(man, '2') Man.class_method('3') Man.static_method('4') man.static_method('5')
true
8e6f3e1ce894dd577a1cdc9b22c29886a8c8adce
manutouzumaki/mi-primer-programa
/comer helado.py
1,362
4.125
4
apetece_helado_input = input("quieres helado? si/no").upper() if apetece_helado_input == "SI": apetece_helado = True elif apetece_helado_input == "NO": apetece_helado = False else: print("no se que quisiste decir pero supongo que no") apetece_helado = False tienes_dinero_input = input("tienes dinero? si/no").upper() if tienes_dinero_input == "SI": puedo_permitirmelo = True elif tienes_dinero_input == "NO": puedo_permitirmelo = False else: print("no se que quisiste decir pero supongo que no") apetece_helado = False esta_senor_input = input("esta el senor de los helados si / no").upper() if esta_senor_input == "SI": esta_seor = True elif esta_senor_input == "NO": esta_seor = False else: print("no se que quisiste decir pero supongo que no") esta_seor = False esta_tia_iput = input("esta tu tia? si/no").upper() if esta_tia_iput == "SI": puedo_permitirmelo = True elif esta_tia_iput == "NO": puedo_permitirmelo = False else: print("no se que quisiste decir pero supongo que no") puedo_permitirmelo = False apetece_helado = apetece_helado_input == "SI" puedo_permitirmelo = tienes_dinero_input == "SI" or esta_tia_iput == "SI" esta_seor = esta_senor_input == "SI" if apetece_helado and puedo_permitirmelo and esta_seor: print("comete un helado") else: print("pues nada")
false
393db94998ac50789ce038e04389b0c14d56b7dd
Ravi4teja/Python_classes
/math_calcs.py
718
4.1875
4
# a = 7 # b = 8 # print(a + b) # print(64** (1/2)) #Importing math module import math #sqrt() in math module returns the square root of specified number sqrt_of_num = math.sqrt(6) print(sqrt_of_num) #pow() in math module returns the power of 1st argument to 2nd argument passed print(math.pow(5, 3)) #approximating to 0 decimals print(round(2.3)) #floor() in math module returns the integer by removing the decimals print(math.floor(5.9992)) #floor() in math module returns the integer+1 by removing the decimals print(math.ceil(5.002)) # print(help(math)) #radians() in math module converts degrees to radians #sin() in math module gives the sin of radians provided print(math.sin(math.radians(45)))
true
ca581c760879e64e8b36ef0828e279d816bf180e
Ravi4teja/Python_classes
/scopes.py
1,238
4.5625
5
#Scopes x = "global x" #Global Variable def local_func1(): x = "local x" #Local variable print(x) #Accessing local variable local_func1() print(x) #Accessing global variable y = "global y" #Global Variable def outer_func1(): y = "outer y" #this is local variable to the outer_func1 def inner_func1(): y = "inner y" #this is local variable to the innner_func1 print(y) #Accessing local variable in inner_func1 scope inner_func1() print(y) #Accessing local variable in outer_func1 scope print(y) #Accessing global variable outer_func1() print("done") z = "global z" def local_func(): global z #Using global variable z = "local z" #Modifying global variable print(z) #Accessing global variable local_func() print(z) #Accessing global variable a = "global a" def outer_func2(): a = "outer a" #this is local to the outer_func def inner_func2(): nonlocal a #Using variable from outer_func2 scope a = "inner a" #Modifying variable from outer_func2 scope print(a) #Accessing variable from outer_func2 scope inner_func2() print(a) #Accessing variable from outer_func2 scope print(a) #Accessing global variable outer_func2() print("done")
true
bad5357913c3dbe687e0dc3b012ff849807982a0
stemleague/sorting-hat
/sorting_hat.py
2,168
4.25
4
#### PART 1: Introduction #### print("=== Sorting Hat Quiz ===") print("Welcome to Hogwarts! It's time to find out which house you belong in! For each question, please type the number of the answer you choose.\nAre you ready? Time to put on the Sorting Hat...\n") # Create a list containing each result of the quiz. results = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"] # Create a list 'tallies' that will keep score of each result. This list should be the same length as the 'results' list. Each entry in 'tallies' will keep score for the result with the same index in 'results'. tallies = [0] * len(results) # QUESTION 1 print("Question 1") print("What's your favorite element?") print("1: Fire") print("2: Earth") print("3: Air") print("4: Water") # input() prompts the user to enter an input. The input is by default a string so we need to cast it into an integer. Then we save this input in the variable 'answer'. answer = int(input("Answer: ")) # Add a point in 'tallies' for the result that corresponds to the user's answer. Remember that list indexing starts at 0. tallies[answer - 1] += 1 #### PART 2: Add Questions #### # Now let's write some questions! Make sure your answer choices are either 1, 2, 3, or 4 so it will be added to your tallies list. # QUESTION 2 #### YOUR CODE HERE ### answer = int(input("Answer: ")) tallies[answer - 1] += 1 # QUESTION 3 #### YOUR CODE HERE ### answer = int(input("Answer: ")) tallies[answer - 1] += 1 # QUESTION 4 #### YOUR CODE HERE ### answer = int(input("Answer: ")) tallies[answer - 1] += 1 # QUESTION 5 #### YOUR CODE HERE ### answer = int(input("Answer: ")) tallies[answer - 1] += 1 ### PART 3: Report the result #### # This line finds the index of the maximum score in 'tallies' (if two scores are tied, it takes the first one in the list). Then it finds the value with the corresponding index in 'results' and stores it in the variable 'result'. max_number_from_talliest = max(tallies) index_of_max_num = tallies.index(max_number_from_talliest) result = results[index_of_max_num] print("\nAfter a long pause, the Sorting Hat cries:") print(result + "!")
true
071c557d35076812e2448168f14d93ed2a07f280
chetans4/python_study
/03strings.py
1,292
4.625
5
#Strings course = "Python's course for bigineers!" print(course) print(course[0]) print(course[-1]) print("o to 2 : "+course[0:3]) print("o to 2 : "+course[:3]) print("3 to end : "+course[3:]) another = course[:] print another print("1 to second last: "+course[1:-1]) course1 = 'Python for "bigineers"!\n' print(course1) print(course1[-1]) print(course1[-2]) msg = '''Hi Chetan, This is message. Thannks.''' print msg print '-----------------------------------Formated String---------------------------------------' first = "Chetan" last = 'Choudhary' #python 2 msg = first+" ["+last+"] is a coder" print msg #in python 3 #message = f'{first} [{last}] is a coder' #print( message) print '-----------------------------------String Functions---------------------------------------\n' course = "Python's course for bigineers!" # len is a general purpose fuction print len(course) #string methods print course.upper(); print course.lower(); print "Origional : "+course print course.find("P") print course.find("O") print course.find("o") print course.find("bigineers") print course.replace("bigineers", "abs bigineers") print course.replace("o", "A")#relpace will replace all. print 'Title : '+course.title() print "Python"in course; print "python"in course;
false
dbc3a0b5f2d4b8aab8a2a9c4c2474848e40aac9d
chetans4/python_study
/15lists_2d.py
1,213
4.15625
4
#2d lists matrix = [ [1,2,3], [4,5,6], [7,8,9] ] #print matrix for row in matrix: for item in row: print item print "----------------------List methods---------------------------" numbers = [4,7,5,2,7,1,6] numbers.append(20) numbers.insert(0,10) numbers.remove(5) #since python 3.3 #numbers.clear() #remove last item from list numbers.pop() #to check first occurance of object, if not in list ValueError will occure print numbers.index(2) print 50 in numbers print numbers.count(7) print numbers # retun None: means absnce of value, null in java print numbers.sort() print numbers numbers.reverse() print numbers # copy not working ???????? #numbersCopy = numbers.copy() numbersCopy = list(numbers) print numbersCopy print "--------------------------Remove Duplicate from list -------------------------------" duplicateList = [2,3,6,1,3,7,9,4,1] print duplicateList for number in duplicateList: if duplicateList.count(number) > 1: duplicateList.remove(number) print duplicateList uniqueList = [] for number in duplicateList: if number not in uniqueList: uniqueList.append(number) print uniqueList
true
0acd2f5791680afb21ee27788746b297add54951
Axioma42/Data_Analytics_Boot_Camp
/Week 3 - Python/Activities/1/Activities/08-Stu_ConditionalConundrum/Solved/conditionals_solved.py
1,248
4.125
4
# 1. oooo needs some work x = 5 if 2 * x > 10: print("Question 1 works!") else: print("oooo needs some work") # 2. Question 2 works! x = 5 if len("Dog") < x: print("Question 2 works!") else: print("Still missing out") # 3. GOT QUESTION 3! x = 2 y = 5 if (x ** 3 >= y) and (y ** 2 < 26): print("GOT QUESTION 3!") else: print("Oh good you can count") # 4. Dan is in group three name = "Dan" group_one = ["Greg", "Tony", "Susan"] group_two = ["Gerald", "Paul", "Ryder"] group_three = ["Carla", "Dan", "Jefferson"] if name in group_one: print(name + " is in the first group") elif name in group_two: print(name + " is in group two") elif name in group_three: print(name + " is in group three") else: print(name + " does not have a group") # 5. Can ride bumper cars height = 66 age = 16 adult_permission = True if (height > 70) and (age >= 18): print("Can ride all the roller coasters") elif (height > 65) and (age >= 18): print("Can ride moderate roller coasters") elif (height > 60) and (age >= 18): print("Can ride light roller coasters") elif ((height > 50) and (age >= 18)) or ((adult_permission) and (height > 50)): print("Can ride bumper cars") else: print("Stick to lazy river")
true
3ea30facfe3b40e1fb0c3c09a6bba85ac37f48e8
Axioma42/Data_Analytics_Boot_Camp
/Week 3 - Python/Activities/2/Activities/04-Stu_HouseOfPies/Solved/house_of_pies_bonus.py
1,759
4.1875
4
# Initial variable to track shopping status shopping = 'y' # List to track pie purchases pie_purchases = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Pie List pie_list = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun", "Blueberry", "Buko", "Burek", "Tamale", "Steak"] # Display initial message print("Welcome to the House of Pies! Here are our pies:") # While we are still shopping... while shopping == "y": # Show pie selection prompt print("---------------------------------------------------------------------") print("(1) Pecan, (2) Apple Crisp, (3) Bean, (4) Banoffee, " + " (5) Black Bun, (6) Blueberry, (7) Buko, (8) Burek, " + " (9) Tamale, (10) Steak ") pie_choice = input("Which would you like? ") # Get index of the pie from the selected number choice_index = int(pie_choice) - 1 # Add pie to the pie list by finding the matching index and adding one to its value pie_purchases[choice_index] += 1 print("------------------------------------------------------------------------") # Inform the customer of the pie purchase print("Great! We'll have that " + pie_list[choice_index] + " right out for you.") # Provide exit option shopping = input("Would you like to make another purchase: (y)es or (n)o? ") # Once the pie list is complete print("------------------------------------------------------------------------") # Count instances of each pie print("You purchased: ") # Loop through the full pie list for pie_index in range(len(pie_list)): pie_count = str(pie_purchases[pie_index]) pie_name = str(pie_list[pie_index]) # Gather the count of each pie in the pie list and print them alongside the pies print(pie_count + " " + pie_name)
true
a7d0177fb589d354d3d20b3b6cd93791f2bd7674
Axioma42/Data_Analytics_Boot_Camp
/Week 3 - Python/Activities/2/Activities/12-Ins_Functions/Solved/functions.py
872
4.5625
5
# Define the function and tell it to print "Hello!" when called def printHello(): print(f"Hello!") # Call the function within the application to ensure the code is run printHello() # -------------# # Functions that take in and use parameters can also be defined def printName(name): print("Hello " + name + "!") # When calling a function with a parameter, a parameter must be passed into the function printName("Bob Smith") # -------------# # The prime use case for functions is in being able to run the same code for different values listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] listTwo = [11, 12, 13, 14, 15] def listInformation(simpleList): print(f"The values within the list are...") for value in simpleList: print(value) print("The length of this list is... " + str(len(simpleList))) listInformation(listOne) listInformation(listTwo)
true
c3e190ff521fde3aa8e43deb723daa4c21af680b
abhaysaini221/Python_Programs_Practice
/4_String_Programs/8_count_matching_str_char.py
469
4.34375
4
# program to count the number of matching char in pair of string main_str = input("Enter the string\n") sec_str = input("Enter the 2nd string\n") print("Entered string is '" + main_str + "'") match_str = '' for main_char in main_str: for sec_char in sec_str: if main_char == sec_char: match_str = match_str + main_char match_str = set(match_str) print(match_str) print(str(len(match_str)) + " char matches!")
true
e6364d25a6ee223b13ad3f715ac275f603f04419
abhaysaini221/Python_Programs_Practice
/1_Basic_Programs/9_Nth_Fibonacci_number.py
280
4.125
4
# Program for nth Fibonacci number number = int(input("Enter a number\n")) fib_list = [0, 1] for i in range(number-2): fib_list.append(fib_list[i]+fib_list[i+1]) print(fib_list) print("Element at position " + str(number) + " is " + str(fib_list[number-1]))
false
5e516d3d36659441eec67b81c6266b4809857691
abhaysaini221/Python_Programs_Practice
/3_List_Programs/13_largest_elem.py
440
4.3125
4
# program to find largest number number_elem = int(input("Enter the number of elements\n")) new_list = [] print("Enter " + str(number_elem) + " elements") for i in range(0, number_elem): elem = input() new_list.append(elem) print("original list is " + str(new_list)) large = int(new_list[0]) for i in new_list: if int(i) > large: large = int(i) print("largest of all elements is " + str(large))
true
7e6b47aa0e8b21abc9bb4aba3fc8aa8b2cec983b
abhaysaini221/Python_Programs_Practice
/3_List_Programs/5_elem_exists_or_not.py
583
4.1875
4
# program to check is a element exists or not in a list number_elem = int(input("Enter the number of elements\n")) search_elem = input("Enter the element to be searched\n") new_list = [] print("Enter " + str(number_elem) + " elements") for i in range(0, number_elem): elem = input() new_list.append(elem) print("original list is " + str(new_list)) flag = 0 for i in new_list: if i == search_elem: flag = 1 if flag == 1: print(search_elem + " is found in the list") else: print(search_elem + " is not found in the list")
true
d2d5e8c2eb3f509037b261721963f95bb43fd50f
abhaysaini221/Python_Programs_Practice
/4_String_Programs/23_slicing_to_rotate_string.py
298
4.375
4
# program to rotate string using slicing main_str = input("Enter the string\n") no = int(input("Enter the no of char\n")) print("Entered string is '" + main_str + "'") rot_1st = main_str[no:] + main_str[0:no] rot_2nd = main_str[-no:] + main_str[0:-no] print(rot_1st) print(rot_2nd)
false
99f33e65e0ef6363b69dfe1e99419ec2f0fc7855
abhaysaini221/Python_Programs_Practice
/3_List_Programs/25_count_pos_neg.py
532
4.1875
4
# program to count positive and negative numbers number_elem = int(input("Enter the number of elements\n")) new_list = [] print("Enter " + str(number_elem) + " elements") for i in range(0, number_elem): elem = input() new_list.append(elem) print("original list is " + str(new_list)) pos_count = 0 neg_count = 0 for i in new_list: if int(i) > 0: pos_count += 1 else: neg_count += 1 print("Positive numbers: " + str(pos_count) + ", Negative Numbers: " + str(neg_count))
true
3d4c5b425fe5cfe883deab75e8a7438b6113fa7d
sinha-shaurya/apt-lab
/Lab 7/string_regex.py
208
4.34375
4
# check if a string starts and ends with the same character using regex import re s = input("Enter a string: ") # searching regex = r'^[a-z]$|^([a-z]).*\1$' check = re.search(regex, s) print(check != None)
true
3c04054747ca2b20bfeb3d7c4b8dec3e0f038d48
sinha-shaurya/apt-lab
/Lab 7/reverse_lines.py
207
4.125
4
#print lines of file in reverse order import os filepath="file.txt" #open file f=open(filepath,encoding='utf-8') lines=[] for line in f: lines.append(line) lines.reverse() for i in lines: print(i)
true
2b04e053fcabbba16c19768dd7985282f08311ea
yiwang454/Floodwarning_system
/partia-flood-warning-system-113/Task1D.py
1,459
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 28 22:10:02 2018 @author: yw454 """ from floodsystem.stationdata import build_station_list from floodsystem.geo import rivers_with_stations, stations_by_river def run(): '''Testing for rivers_with_stations and stations_by_river ''' stations = build_station_list() river_sets = rivers_with_stations(stations) # showing the number of rivers with stations print('There are {} rivers with stations'.format(len(river_sets))) output = [] output.append(len(river_sets)) river_list = [] for river in river_sets: river_list.append(river) sorted_river = sorted(river_list) print(sorted_river[:10]) output.append(sorted_river[:10]) def prt(river_name, output): '''This functions will print the list of stations on the given rivers Input: river_name: name of given river, type: string ''' # get lists of rivers mapped to river names list_of_stations = stations_by_river(stations) print(river_name + " has stations including: ") print(sorted(list_of_stations[river_name])) output.append(sorted(list_of_stations[river_name])) prt('River Aire', output) prt('River Cam', output) prt('Thames', output) return output if __name__ == "__main__": run()
true
00ad2e208d04fa40f71fec5ec74ec4dccdaf95cd
shadow-dragon/Python-Programming-Exercises
/Exercise 16/ex16.py
1,109
4.40625
4
#importing argv from sys import argv #taking the script name and file name script, filename = argv #printing intro instructions print(f"We're going to erase {filename}") print("If you don't want thar, hit CTRL-C (^C).") print("If you do want that, hit RETURN. ") #taking user input for actions #to be done on the file input("?") #printing opening the file print("Opening the file...") #opening the file target = open(filename, 'w') #print truncating the file print("Truncating the file. Goodbye!") target.truncate() #taking three lines of input print("Now I'm gonna ask you for three lines to put in the file") line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") #compiling the three lines into a single message message = line1 + "\n" + line2 + "\n" + line3 + "\n" #printing that these lines will be added to the file print("I'm going to write these to the file.") #writing the compiled message into the file target.write(message) #printing that the file is going to get closed now print("And finally, we close it.") #closing the file target.close() print("Goodbye!")
true
7eb5369187c440de5a5e478987222b9c79402d25
nyemade-uversky/magic8Ball
/magic_py_ball/__init__.py
842
4.25
4
"""A simple magic 8 ball""" __version__ = '2.3.0' from random import choice ANSWERS = [ 'It is certain.', 'It is decidedly so.', 'Without a doubt.', 'Yes - definitely.', 'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.', 'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My reply is no.', 'My sources say no.', 'Outlook not so good.', 'Very doubtful.', 'Certainly no.', 'Gods say yes.', 'Gods say no.', 'No one knows.', "I don't think so.", ] def answer(): """Generates a magic 8 ball answer to a user's question. Returns: str """ return choice(ANSWERS)
true
0ccf17529ece36b03af0833f755e68568bd2caf0
swati12995/python-practice
/src/basics/dictionaries.py
1,448
4.25
4
''' Dictionaries are unordered mappings for storing objects. dictionaries use a key-value pair. The key-value pair allows users to quickly grab objects withit needing to know an index location It uses curly braces and colons to signify the keys and their associated values. {'key1':'value','key2':'value2'} Dictionaries will be useful when we want to quickly pick a value without needing to know the exact index location it can't be sorted Dictionary is a built-in Python Data Structure that is mutable ''' my_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict) print(my_dict['key1']) dictio = {'1': 'First', '2': 'Second'} print(dictio['1']) dictio['3'] = 'Third' print(dictio) d = {'k1': [1, 2, 3]} print(d['k1'][1]) ''' 1. Do dictionaries keep an order? How do I print the values of the dictionary in order? Dictionaries are mappings and do not retain order! If we do want the capabilities of a dictionary but we would like ordering as well, we can use the ordereddict object ''' # Using keys and indexing, grab the 'hello' from the following dictionaries: d = {'simple_key': 'hello'} # Grab 'hello' print(d['simple_key']) dd = {'k1': {'k2': 'hello'}} # Grab 'hello' print(dd['k1']['k2']) dst = {'k1': [{'nest_key': ['this is deep', ['hello']]}]} # Grab hello print(dst['k1'][0]['nest_key'][1][0]) ddd = {'k1': [1, 2, {'k2': ['this is tricky', {'tough': [1, 2, ['hello']]}]}]} # Grab hello print(ddd['k1'][2]['k2'][1]['tough'][2][0])
true
f938cb5e1364c471753028718d69a5e04f3d1ec4
swati12995/python-practice
/src/basics/lists.py
1,281
4.4375
4
''' Lists are ordered sequences that can hold a variety of object type. They use [] brackets and commas to separate objects in the list. Lists support indexing nad slicing. Lists can be nested ''' my_list = [1, 2, 3] my_list = ['STRING', 100, 23.33] print(len(my_list)) mylist = ["ONE", "TWO", "TREE"] print(mylist[0]) print(mylist[1:]) print(my_list + mylist) print(my_list + my_list) my_list[0] = "VALUE CHANGED" print(my_list) mylist.append("Appened") print(mylist) mylist.append("four") print(mylist) mylist.append("five") print(mylist) mylist.append("six") mylist.append("seven") print(mylist) mylist.pop() print(mylist) mylist.pop(4) print(mylist) new_list = ["two", "three", "four", "five"] new_list = ['a', 'e', 'x', 'b', 'c'] num_list = [4, 1, 8, 3] new_list.sort() print(new_list) num_list.sort() print(num_list) print(type(new_list)) my_sorted_list = new_list.sort() print(my_sorted_list) new_list.reverse() print(new_list) new_list.append("Appended") # Build this list 0,0,0 two separate ways. # Method 1: l = [0, 0, 0] print(l) # Method 2: ll = [0]*3 print(ll) # Reassign 'hello' in this nested list to say 'goodbye' instead: list3 = [1, 2, [3, 4, 'hello']] list3[2][2] = 'goodbye' print(list3) # Sort the list below: list4 = [5, 3, 4, 6, 1] list4.sort() print(list4)
true
8eff525cd94ebcf0b97a5f5af2cb13c990ca810f
hhammoud01/Datacamp
/2-Supervised-Learning-with-Scikit-Learn/1-Classification/7-Train-Test-Split-Fit-Predict-Accuracy.py
1,195
4.3125
4
#1- Import KNeighborsClassifier from sklearn.neighbors and train_test_split from sklearn.model_selection. #2- Create an array for the features using digits.data and an array for the target using digits.target. #3- Create stratified training and test sets using 0.2 for the size of the test set. Use a random state of 42. Stratify the split according to the labels so that they are distributed in the training and test sets as they are in the original dataset. #4- Create a k-NN classifier with 7 neighbors and fit it to the training data. #5- Compute and print the accuracy of the classifier's predictions using the .score() method. # Import necessary modules from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split # Create feature and target arrays X = digits.data y = digits.target # Split into training and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0. 2, random_state=42, stratify=y) # Create a k-NN classifier with 7 neighbors: knn knn = KNeighborsClassifier(n_neighbors=7) # Fit the classifier to the training data knn.fit(X_train, y_train) # Print the accuracy print(knn.score(X_test, y_test))
true
e119c2e0be5cebf24cc588e4c6c911adee158aec
hhammoud01/Datacamp
/2-Supervised-Learning-with-Scikit-Learn/4-Preprocessing-and-Pipelines/2-Creating-Dummy-Variables.py
729
4.375
4
""" Use the pandas get_dummies() function to create dummy variables from the df DataFrame. Store the result as df_region. Print the columns of df_region. This has been done for you. Use the get_dummies() function again, this time specifying drop_first=True to drop the unneeded dummy variable (in this case, 'Region_America'). Hit 'Submit Answer to print the new columns of df_region and take note of how one column was dropped! """ # Create dummy variables: df_region df_region = pd.get_dummies(df) # Print the columns of df_region print(df_region.columns) # Create dummy variables with drop_first=True: df_region df_region = pd.get_dummies(df, drop_first=True) # Print the new columns of df_region print(df_region.columns)
true
5ee42dbf70fa702fa7eb775843a815817cbf1f68
hhammoud01/Datacamp
/2-Supervised-Learning-with-Scikit-Learn/1-Classification/5-k-Nearest-Neighbors-Predict.py
879
4.28125
4
#1 Create arrays for the features and the target variable from df. As a reminder, the target variable is 'party'. #2 Instantiate a KNeighborsClassifier with 6 neighbors. #3 Fit the classifier to the data. #4 Predict the labels of the training data, X. #5 Predict the label of the new data point X_new. # Import KNeighborsClassifier from sklearn.neighbors from sklearn.neighbors import KNeighborsClassifier # Create arrays for the features and the response variable y = df['party'].values X = df.drop('party', axis=1).values # Create a k-NN classifier with 6 neighbors: knn knn = KNeighborsClassifier(n_neighbors=6) # Fit the classifier to the data knn.fit(X, y) # Predict the labels for the training data X y_pred = knn.predict(X) # Predict and print the label for the new data point X_new new_prediction = knn.predict(X_new) print("Prediction: {}".format(new_prediction))
true
52fa0373eb54501928d4a4106be6ee2926d98df0
vivekpabani/codeabbey
/python/007/problem_007.py
1,053
4.125
4
#!/usr/bin/env python """ Problem Definition : There are two widespread systems of measuring temperature - Celsius and Fahrenheit. First is quite popular in Europe and second is well in use in United States for example. By Celsius scale water freezes at 0 degrees and boils at 100 degrees. By Fahrenheit water freezes at 32 degrees and boils at 212 degrees. You may learn more from wikipedia on Fahrenheit. Use these two points for conversion of other temperatures. You are to write program to convert degrees of Fahrenheit to Celsius. Input data contains N+1 values, first of them is N itself (Note that you should not try to convert it). Answer should contain exactly N results, rounded to nearest integer and separated by spaces. """ __author__ = 'vivek' import time import sys startTime = time.clock() length = int(sys.argv[1]) start = 2 for i in xrange(length): fh = int(sys.argv[start]) sc = int(round((fh - 32)*5.0/9)) print(sc), start += 1 print "\nRun time...{} secs \n".format(round(time.clock() - startTime, 4))
true
3397cf01cd8058a046541562c55ebcc3ea500aef
ztamayo/python_samples
/Max Number.py
508
4.40625
4
# Programmer: Zailyn Tamayo # This program will prompt the user to enter two integers. # It will then output which is the larger number that was entered. # For example, if the user enters 4 and 8, the output will read "8 is the maximum". first = input("\nEnter the first integer: ") second = input("\nEnter the second integer: ") if first > second: print ("\n", first, "is the maximum.") elif first == second: print ("\nThey are equal.") else: print ("\n", second, "is the maximum.")
true
91abdc29bfca96c27c3dd7b0b9b2aa430ddc0153
MrymHkmbdi/DataStructures
/linkedlist.py
1,908
4.15625
4
class Node: def __init__(self, data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.size = 0 def print_list(self): head = self.head while head is not None: print(head.data) head = head.next def insert_begin(self, new_data): the_node = Node(new_data) the_node.next = self.head self.head = the_node def insert_end(self, new_data): NewNode = Node(new_data) if self.head is None: self.head = NewNode return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = NewNode def insert_between(self, middle_node, new_data): if middle_node is None: print("The mentioned node is absent") return NewNode = Node(new_data) NewNode.next = middle_node.next middle_node.next = NewNode def remove_node(self, key): head = self.head if head is not None: if head.data == key: self.head = head.next head = None return while head is not None: if head.data == key: break prev = head head = head.next if head is None: return prev.next = head.next head = None def list_size(self): return self.size def last_node(self): head = self.head while head is not None: if head.next is None: return head.data if __name__ == "__main__": new_list = LinkedList() new_list.insert_begin(1) new_list.insert_begin(2) new_list.insert_begin(3) new_list.insert_between(new_list.head.next, 5) new_list.insert_end(4) new_list.print_list()
true
38cf7e6f5689c665cc53d2b58cff7cefa16d9092
bollwyvl/vak
/src/vak/files/files.py
2,076
4.375
4
import os import re from glob import glob def find_fname(fname, ext): """given a file extension, finds a filename with that extension within another filename. Useful to find e.g. names of audio files in names of spectrogram files. Parameters ---------- fname : str filename to search for another filename with a specific extension ext : str extension to search for in filename Returns ------- sub_fname : str or None Examples -------- >>> sub_fname(fname='llb3_0003_2018_04_23_14_18_54.wav.mat', ext='wav') 'llb3_0003_2018_04_23_14_18_54.wav' """ m = re.match(f'[\S]*{ext}', fname) if hasattr(m, 'group'): return m.group() elif m is None: return m def from_dir(dir_path, ext): """helper function that gets all files with a given extension from a directory or its sub-directories. If no files with the specified extension are found in the directory, then the function recurses into all sub-directories and returns any files with the extension in those sub-directories. Parameters ---------- dir_path : str path to target directory ext : str file extension to search for Returns ------- files : list of paths to files with specified file extension Notes ----- used by vak.io.audio.files_from_dir and vak.io.annot.files_from_dir """ wildcard_with_extension = f'*.{ext}' files = sorted( glob(os.path.join(dir_path, wildcard_with_extension)) ) if len(files) == 0: # if we don't any files with extension, look in sub-directories files = [] subdirs = glob(os.path.join(dir_path, '*/')) for subdir in subdirs: files.extend( glob(os.path.join(dir_path, subdir, wildcard_with_extension)) ) if len(files) == 0: raise FileNotFoundError( f'No files with extension {ext} found in ' f'{dir_path} or immediate sub-directories' ) return files
true
c4970288616c2389ba2dcf119bf72796fb600896
gurgelgabriel/untitled4
/functionsintro.py
1,255
4.46875
4
# task 6(shopping list) print("welcome to task 6") # print a introduction to the task list_2 = [] # creates a list print("you need to buy: potatos, apples, bananas, ice cream ") # print what you need to buy list_1 = ["potatos", "apples", "bananas", "ice cream"] # creates a second list while list_1[0] not in list_2 or list_1[1] not in list_2 or list_1[2] not in list_2 or list_1[3] not in list_2: # creates a while loop until "list" have all those thinks inpu_1 = int(input("press 0 to 3 on the order we post the list for the item you got")) # ask the user what he got if inpu_1 == 0: # if the user anserw 0 list_2.insert(0, "potatos") # you add potatos as the first item of the list if inpu_1 == 1: # if the user anserw 1 list_2.insert(1, "apples") # you add apples as the second item of the list if inpu_1 == 2: # if the user anserw 2 list_2.insert(2, "bananas") # you add bananas as the third item of the list if inpu_1 == 3: # if the user anserw 3 list_2.insert(3, "ice cream") # you add ice cream as the fourth item of the list print("you have", list_2) # print what you have inside the while loop so every time you get somethink you will know what you still need
true
769dbaa558cdff41edd9a937ba9c25cfc3f98613
gurgelgabriel/untitled4
/october30.py
693
4.28125
4
# task 9(the pivot list) print("welcome to task 9") # print a introduction to the task def pivotlist(inlist, number): # define a function and it parameters list = [] # creates a list for x in inlist: # for the values in "inlist" if x < number: # if x is smaler then parameter number.. list.append(x) # you put the x inside your list return list # set the value of list and finish the function inlist = [1, 2, 3, 4, 5, 6 ,7 ,8 ,18, 81, 100] # creates a list inside the parameter "inlist" number = int(input("chose a number")) # input a value to the parameter "number" print(pivotlist(inlist, number)) # calls the function and prints it on the console
true
7a2289b20f9ec6112536db4accf6a20fc71f7999
joeyfields/CTI-110
/P4HW3_NestedLoops_MartinFields.py
430
4.3125
4
#Nested Loop to draw pattern #5 July 2020 #CTI-110 P4HW3- Nested Loops #Martin Fields #Pseudocode #Create rows with "#" #Create spaces in rows between the #'s #Display the pattern #Create rows with "#" for row in range (6): print( '#', end='', sep='') #Create incrimental spaces in rows for spaces in range(row): print(' ', end='',sep='') #Display pattern print( '#', sep='' )
true
a92594c862acad4a94415704ab3e49752d3d704b
samahDD/cs1-2016
/lab5/lab5_d_2.py
2,960
4.125
4
from Tkinter import * import random from math import * # Helper functions def draw_star(can, color, radius, x_coord, y_coord, number_points): '''Takes 6 arguments: can the canvas to draw on, color, the radius of the circle the star is contained within, x_coord the x coordinate of the center of the star, y_coord the y coordinate of the center of the circle, and number_points the number of points that the star has. Draws a star of the color specified centered at (x_coord, y_coord) with the designated radius and the designated number_points. ''' star = [] theta = (2 * pi) / number_points point_lst = [] for i in range(number_points): point_lst.append(i) if i + (number_points - 1) / 2 >= number_points: point_lst.append(i + (number_points - 1) / 2 - number_points) else: point_lst.append(i + (number_points - 1) / 2) for j in range(number_points): point_1 = point_lst.pop(0) point_2 = point_lst.pop(0) line = can.create_line(x_coord + radius * sin(theta * point_1), \ y_coord - radius * cos(theta * point_1), \ x_coord + radius * sin(theta * point_2), \ y_coord - radius * cos(theta * point_2), \ fill = color) star.append(line) global star_lst star_lst.append(star) def random_color(): '''Generates random color values in the format of #RRGGBB. ''' hex_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', \ 'c', 'd', 'e', 'f'] color = '#' for a in range(6): color += random.choice(hex_list) return color def random_diameter(): '''Returns a random even number between 50 and 100 to be used as the diameter for a circle. ''' return 2 * (random.randint(25, 50)) # Event handlers def key_handler(event): '''Handle key presses.''' global n if event.keysym == 'q': quit() elif event.keysym == 'c': global current_color current_color = random_color() elif event.keysym == 'x': global star_lst for star in star_lst: for line in star: canvas.delete(line) star_lst = [] elif event.keysym == 'plus': n += 2 elif event.keysym == 'minus': if n > 5: n -= 2 def button_handler(event): '''Handle left mouse button click events.''' global current_color global n draw_star(canvas, current_color, random_diameter() / 2, event.x, event.y, n) if __name__ == '__main__': root = Tk() root.geometry('800x800') canvas = Canvas(root, width=800, height=800) canvas.pack() current_color = random_color() star_lst = [] n = 5 root.bind('<Key>', key_handler) canvas.bind('<Button-1>', button_handler) root.mainloop()
true
ff3fe224d1907fa2cade15fd2afa4720fd2e1040
arpancodes/a-week-of-python
/DAY - 1 - OOP/oop.py
1,636
4.34375
4
# class is blueprint of objects # we can instantiate multiple "unique" object from a single class # class contains properties and methods # constructor or "__init__" # 4 pillars of OOP: # 1. Encapsulation # 2. Abstraction # 3. Inheritance # 4. Polymorphism # BONUS: dunder methods and multiple inheritance, mro # |^^^^^^^^^^^^^^^^^| instantiate # | | -----------> Object1 - properties, methods # | CLASS | # | properties | -----------> Object2 - properties, methods # | methods | # | | -----------> Object3 - properties, methods # |_________________| class Father: def __init__(self, name, age): self.name = name self.age = age def walk(self): print(f'[FROM FATHER] {self.name} Walking...') class Mother: def __init__(self, hair_color): self.hair_color = hair_color def sprint(self): print(f'[FROM MOTHER] Sprinting...') class Son(Father, Mother): def __init__(self, name, age, hair_color): Mother.__init__(self, hair_color) Father.__init__(self, name, age) def fight(self): print(f'{self.name} is using - Nutcracker choke') class Daugter(Father): def __init__(self, name, age): super().__init__(name, age) def fight(self): print(f'{self.name} is using - Ax stomp to the wherever') jarrard = Son('Jarrard', 10, 'blak') daisy = Daugter('Daisy', 12) jarrard.sprint() jarrard.walk() class X: pass class Y: pass class Z: pass class A(X, Y): pass class B(Y, Z): pass class M(B, A, Z): pass print(M.__mro__)
true
495ff081288a5e5a9f5063dc88b71848394724b0
azocher/python-intro-lesson
/main.py
1,101
4.375
4
# hello world print example #print("👋 Hello, world!") # variable examples name = "Anna" address_num = 1435 has_dog = True # print(name) # print(address_num) # print(has_dog) # example of if statement # alphabet = "sljasdfakdsjlkajslfdkjaasdklfjsldjfiels" # if ("z" in alphabet): # print("Yay - I found a Z char") # example of a for loop # for i in range(1, 6): # print(i) # example of lists (arrays) # foods = ["carrots", "kale", "beets"] # for food in foods: # print("Hello, I currently have {} in the garden.".format(food)) # example of function in python # def sum(num1, num2): # return num1 + num2 # total = sum(352, 38239) # print(total) # example of built in list methods in py # colors = ["red", "yellow", "purple", "green"] # colors_length = len(colors) # print(colors_length) # colors.append("blue") # print(colors) # colors_length = len(colors) # print(colors_length) # example of mathematical list operations # batting_avgs = [.328, .348, .293, .293] # sum_avgs = sum(batting_avgs) # true_avg = sum_avgs / len(batting_avgs) # print(true_avg)
true
d70df55de20f84ccacb1bce6a102bac054d00977
Abhishekbhagwat/pythonParade
/lists.py
341
4.4375
4
fruits = ['Apple','Banana','Orange'] fruits[0] #'Apple' fruits[1] #'Banana' fruits[2] #'Orange' #to access all elements of the list use a for loop in the following way for fruit in fruits: #uses a var fruit to check the presence of an element in list print (fruit) #prints the element stored in the var fruit
true
c380f64fb70426039ff847d8ee9cafde2de9f6f8
Sagnik-Dey/PasswordGenerator
/src/app/function/functions.py
1,435
4.375
4
import random import pyperclip def generate_password(length, include_numbers): """ This is a function which will generate random password depend on the arguments Args: length ([int]): [This argument specifies the length of the password] include_numbers ([boolean]): [This argument specifies whether numbers shoulb be included or not] Returns: [string]: [This function returns the randomly generated password] """ characters_array = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers_array = "1234567890" password = "" if (include_numbers): half_length = length // 2 rest_num = length - half_length for i in range(0, half_length): index = random.randint(0, len(characters_array)-1) password += characters_array[index] for i in range(0, rest_num): index = random.randint(0, len(numbers_array)-1) password += numbers_array[index] return password for i in range(0, length): index = random.randint(0, len(characters_array)-1) password += characters_array[index] return password def copy_to_clipboard(text): """ This is a function which copies the text which is passed to the clipboard Args: text ([string]): [This argument specifies the text which has to be copied] """ pyperclip.copy(text=text)
true
e0fe14dc4be6c5ee1c691e956e7d2484c4343585
Igor-Polatajko/python-labs
/lab_7_10.py
268
4.4375
4
#!/usr/bin/env python def get_shortest_word_length(line): words = line.split() return min(map(lambda w: len(w), words)) if __name__ == '__main__': line = input("Enter line: ") print(f"Length of the shortest word: {get_shortest_word_length(line)}")
false
21396823e3210bc3031e8494a6989e96b6631c51
Igor-Polatajko/python-labs
/lab_7_3.py
671
4.3125
4
#!/usr/bin/env python OPEN_BRACKETS = ('<', '[', '(', '{') CLOSE_BRACKETS = ('>', ']', ')', '}') BRACKETS_PAIRS = dict(zip(CLOSE_BRACKETS, OPEN_BRACKETS)) def is_brackets_sequence_correct(line): brackets_stack = [] for symbol in line: if symbol in OPEN_BRACKETS: brackets_stack.append(symbol) elif symbol in CLOSE_BRACKETS: if BRACKETS_PAIRS[symbol] != brackets_stack.pop(): return False return len(brackets_stack) == 0 def main(): line = input("Enter string to test: ") print(f"Brackets sequence test result: {is_brackets_sequence_correct(line)}") if __name__ == '__main__': main()
false
6e6db476c346478e3fc69788682d43d88603f4c5
Igor-Polatajko/python-labs
/lab_7_4.py
412
4.25
4
#!/usr/bin/env python def next_symbol(symbol): if ord(symbol) == ord('z'): return 'a' if ord(symbol) == ord('Z'): return 'A' return chr(ord(symbol) + 1) def encrypt(raw): encrypted = '' for symbol in raw: encrypted += next_symbol(symbol) return encrypted if __name__ == '__main__': raw = input("Enter raw text: ") print(f"Encrypted: {encrypt(raw)}")
true
35e235b7cdb5736be1f740dc2524049fc1db3d93
minakoyang/YY_python2.7_interpreter_in_CPP
/cases/while.py
419
4.28125
4
def g(): x = 0 while x < 9: if x < 3: print x elif x < 5: print x+3 else: print x+1 x += 1 else: print x*2 sum = 0 n = 1 while n <= 100: sum = sum + n n = n + 1 print sum # Example to illustrate # the use of else statement # with the while loop counter = 0 while counter < 3: print "Inside loop" counter = counter + 1 else: print "Inside else" g()
false
d42f6393fd943c9f0f25772baea7c05b4e2424be
abhishekpshenoy/Python
/Practice_samples/Condisional/Conditional_example.py
1,509
4.28125
4
""" 1. Write a program that asks the user to enter a number and displays whether entered number is an odd number or even number? """ fromUser = int(input("Please enter a number")) if(fromUser % 2 == 0): print("The entered number is a even number") else: print("The entered number is an odd number") # using shorthand print("The entered number is a even number") if fromUser % 2 == 0 else print("The entered number is an odd number") """ Write a program that prompts the user to input a number. The program should then output the number and a message saying whether the number is positive, negative, or zero. """ fromUser = int(input("Please enter a number")) if(fromUser == 0): print("Number is equal to zero") elif(fromUser > 0): print("Number is grater than zero") else: print("Number is lesser than zero") """ Write a program to calculate the monthly telephone bills as per the following rule: Minimum Rs. 200 for up to 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls. """ bill = 0 telephoneUseage = int(input("Please enter the number of call")) if(telephoneUseage <= 100 ): bill = 200 elif(telephoneUseage <= 150): bill = 200 + (telephoneUseage - 100) * 0.60 elif(telephoneUseage <= 200): bill = 200 + (50 * 0.60) + ((telephoneUseage - 150) * 0.60) else: bill = 200 + 50 * 0.60 + 50 * 0.50 + (telephoneUseage - 200) * 0.40 print("Telephone bill is ",bill)
true
8279a6a164afac7f1ca1f6fb500dd765668e5080
abhishekpshenoy/Python
/Classes/multi_inheretence.py
987
4.375
4
# Python program to demonstrate # multilevel inheritance # Base class class Grandfather: def __init__(self, grandfathername): self.grandfathername = grandfathername def grandfather(self): print("my grandfather is ",self.grandfathername) # Intermediate class class Father(Grandfather): def __init__(self, fathername, grandfathername): self.fathername = fathername # invoking constructor of Grandfather class Grandfather.__init__(self, grandfathername) def father(self): print("my father is ",self.fathername) # Derived class class Son(Father): def __init__(self,sonname, fathername, grandfathername): self.sonname = sonname # invoking constructor of Father class Father.__init__(self, fathername, grandfathername) def intro(self): print('Grandfather name :', self.grandfathername) print("Father name :", self.fathername) print("Son name :", self.sonname)
true
83ea29b4358e6a7d47ad12adffd767fc6daa14e3
ziggi24/python-word-count
/wordCount.py
1,489
4.28125
4
#this is the python script I will use to parse the word choice in my writing # # #@author Zach Sharpe #@since 2017-10-6 #@modified 2017-10-6 #for this project we will use the Counter Object, which is based on the python #dictionaries. this will automatically handle the parsing of words, as well as #counting their frequency. It will also provide the most_common() method that #we use to calculate the 100 most common and return them to the user. The # documentation for Counter objects can be found here: # #https://docs.python.org/3/library/collections.html from collections import Counter # here we ask the user which file to parse. For the sake of this example the #file will always be the included input.txt, however I added this input so that #other people could take this code and use it without having to modify it. fileName = input("what is the file name of the input text? ") # with the file name given, we will open the file, and read it. #This is the main loop of the script. This check to see if the file exists, then #opens it, and proceeds to loop through every word and adds it to the Counter #object, called count here. This will return completed when there are no more #words to parse. with open(fileName) as doc: count = Counter(doc.read().strip().split()) #in this look we format the print. We loop through every value in the top 100 #most common, and then print them out on their own line. for key, value in count.most_common(100): print(key+ " - " + str(value))
true
9f3835dcae2d09632226bbde497be1c9d66cd7ed
carlopeano/python_work
/chap_6/6_11_cities.py
840
4.3125
4
cities = { 'bologna': { 'country': 'italy', 'population': 388_367, 'fact':'it has the oldest existing universities in continuous ' 'operation in the world', }, 'brussels': { 'country': 'belgium', 'population': 1_208_542, 'fact': 'it was founded in 979', }, 'berlin': { 'country':'germany', 'population': 3_769_495, 'fact':'it is the capital of germany', }, } for city, data in cities.items(): print(f"Regarding the city of {city.title()}, we have the " f"following information") country_city = data['country'] pop_city = data['population'] fact_city = data['fact'] print(f"\tCountry: {country_city.title()}") print(f"\tPopulation: {pop_city}") print(f"\tFact: {fact_city}")
false
fbbd03a7a020a659243cbef4c508cf6acad3dfc4
dev-sna/learning-python
/03-Python-Statements/01-if-elif-else.py
270
4.28125
4
if 3 > 2: print('3 is greater than 2.') else: print("This definitely won't work") location = 'Bank' if location == 'Auto Shop': print('Gonna get my car repaired.') elif location == 'Bank': print('Money is cool.') else: print('I do not know much.')
true
baff2957536ea43c05a5fa6b3be4b3675e140b10
kirillnovoselov/python
/lesson_1_task_4.py
669
4.15625
4
# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. Целочисленное // div? Остаток % mod n = int(input('Введите целое положительное число:')) max = n % 10 a: int = n // 10 print(n, max, a) while a > 0: if a % 10 > max: max = a % 10 else: a: int = a // 10 # print(a) print(f'Наибольшая цифра в числе {n} равна {max}')
false
e13ff1b5d43655c9c79b0f7a50c8ad5b72f268cc
baukajikorean/Python
/lesson12.py
1,178
4.3125
4
# print(3 == 3) # x = 0 # if x: # print("Переменная x вернула ИСТИНУ") # else: # print("Переменная x вернула ЛОЖЬ") # if 1: # print("Выражение истинно") # else: # print("Выражение ложно") # light = "What" # if light == "red": # print("Stop") # elif light == "yellow": # print("Wait") # elif light == "green": # print("Go") # else: # print("What?") # age = int(input("How old are you? ")) # if age >= 18: # print(f"Welcome! You are {age}. You have been available to come for {age - 18} years.") # else: # print(f"You are too young. Your age is {age}. You can come in {18 - age} years.") # time = int(input("What time is it? ")) # if time < 12 or time > 13: # print("We are open.") # else: # print("We are closed.") # time = 7 # day = 'st' # if time >= 8 and day != "su": # print("Open.") # else: # print("Closed.") # x = 1 # if not x: # print("Okay.") # else: # print("Nope.") # сокращенное выражение (тернарное) # x = 1 # res = "OK" if not x else "NO" # print(res) x = 1 print("OK" if x else "NO")
false
07ac45f6b7e31a670508fb2234d166cde58c13fc
saim22r/Functions
/Eng89_Functions.py
1,186
4.53125
5
### Let's create a function #### Syntax def is used to declare followed by name of the function(): # ## First Iteration # def greeting(): # print("Welcome") # # greeting() # You have to call the function to execute the code # # # pass is the keyword that allows the ineterpretor to skip without any errors # # DRY (Don't Repeat Yourself) declare functions and reuse code # # # Second Iteration (Use return statement) # def greeting(): # print("Good morning!") # return "Welcome" # print(greeting()) ## Third Iteration (With user name as a string as an argument) # def greeting(name): # # print(name) # return "Welcome on Board " + name # # print(greeting("Saim")) # - Create a function to prompt the user to enter their name and display the name back to the user with greeting message # # def greeting(name): # return "Welcome " + name + "!" # # print(greeting(input("What is your name? "))) # Let's create a function with multiple args as an int # def add(num1, num2): # return num1 + num2 # # print(add(1, 3)) # # def multiply(num1, num2): # return num1 * num2 # # print(multiply(4, 3)) #- Return statement is the last line of code in a function
true
e68206c6f8b6920a7377b9f87bf1703f3a116e07
kmicic77/thinkpython
/5-Conditionals and Recursion/ex5-2.py
393
4.21875
4
""" checking Fermat's theorem""" def check_fermat(a,b,c,n): if n>2 and a**n+b**n==c**n: print("Holy smokes! Fermat was wrong!") else: print("No, that doesn't work.") def ask_for_input(): a=int(input("Give me \"a\": ")) b=int(input("Give me \"b\": ")) c=int(input("Give me \"c\": ")) n=int(input("Give me \"n\": ")) check_fermat(a,b,c,n) ask_for_input()
false
76c72d278c88fbd6d80ff62dccd3ac553e4c3fc1
perosu/Code
/Python/GuessNum/1.py
466
4.15625
4
#2017.12.31 20:24 :version1 #A game for study. #Guess random number. import random num = random.randint(1,10) temp = input("number:\n") guess = int(temp) if guess == num: print("Yes") else: while guess != num: if guess <= num: print("Bigger") temp = input("Try again:") guess = int(temp) else: print("Smaller") temp = input("Try again:") guess = int(temp) print("End")
true
93a028c2badeaf60352c19cc5f233381f04f6bea
Amit2197/ProgramingSolved
/InterViewPreWithPython/TechMahindra/test5.py
954
4.1875
4
# Q1. Find Large Small Difference # Write a program to return the difference between the largest and smallest numbers from an array of positive integers. # Note: # You are expected to write code in the findLargeSmallDifference function only which will receive the first parameter as the number of items in the array and the second parameter is the array itself. You are not required to take input from the console. # Example: # Finding the difference between the largest and smallest from a list of 5 numbers. # Input # Input1: 5 # Input2: 10 11 7 12 14 # Output # 7 # Explanation: # The first parameter(5) is the size of the array. Next is an array of integers. The difference between largest (14) and smallest(7) is 7. # Code Solution in C++: # Input1: 5 # Input2: 10 11 7 12 14 def findLargeSmallDifference(l, arlist): arlist.sort() return arlist[-1]-arlist[0] print(findLargeSmallDifference(5, [10, 11, 7, 12, 14]))
true
b1b3e400dcbd99dba2278ba65b223bd1104913a0
sod2003/portfolio
/python/fundamentals/db-api.py
1,230
4.125
4
#!/usr/bin/env python3 import sqlite3 def main(): print('Connecting to database') db = sqlite3.connect('db-api.db') # Will create the db-api.db file if it does not already exist. cur = db.cursor() print('Creating table') cur.execute("DROP TABLE IF EXISTS test") cur.execute(""" CREATE TABLE test ( id INTEGER PRIMARY KEY, string TEXT, number INTEGER ) """) print('Inserting 1st row') cur.execute(""" INSERT INTO test (string, number) VALUES ('one', 1) """) print('Inserting 2nd row') cur.execute(""" INSERT INTO test (string, number) VALUES ('two', 2) """) print('Inserting 3rd row') cur.execute(""" INSERT INTO test (string, number) VALUES ('three', 3) """) print('Committing changes') db.commit() print('Counting rows') cur.execute("SELECT COUNT(*) FROM test") count = cur.fetchone()[0] print(f'There are {count} rows in the table') print('Reading rows') for row in cur.execute("SELECT * FROM test"): print(row) print('Dropping table') cur.execute("DROP TABLE test") print('Closing database') db.close() if __name__ == '__main__': main()
true
f01744ad26d00eda0df318472231496a3d88af48
sod2003/portfolio
/python/python-designpatterns/visitor.py
1,112
4.1875
4
class House(object): """The class being visited""" def accept(self, visitor): visitor.visit(self) def work_on_hvac(self, hvac_specialist): print(self, "worked on by", hvac_specialist) def work_on_electricity(self, electrician): print(self, "worked on by", electrician) def __str__(self): return self.__class__.__name__ class Visitor(object): """The abstract class""" def __str__(self): return self.__class__.__name__ class HvacSpecialist(Visitor): """Concrete implementation of the Hvac visitor""" def visit(self, house): house.work_on_hvac(self) class Electrician(Visitor): """Concrete implementation of the Electrician visitor""" def visit(self, house): house.work_on_electricity(self) # Create the visitors for testing bill = HvacSpecialist() ted = Electrician() # Create the house for testing house = House() # Test the house accepting its visitors house.accept(bill) house.accept(ted) # Print the str names print("Bill is a", bill) print("Ted is an", ted) print("Bill and Ted worked on a", house)
true
1cc0ad606d85b29d8923fee603a8d30ba041efd2
ahdrage/flask
/calculate_date.py
433
4.15625
4
from datetime import datetime, date, time year = 0 month = 0 day = 0 pregnancy = 40 # a pregnancy lasts 40 weeks def week_converter(year, month, day): week = date(year, month, day).isocalendar()[1] print week if week < pregnancy: new_week = 52 + (week - pregnancy) year = year - 1 return new_week, year else: new_week = week - pregnancy return new_week print week_converter(2016, 4, 28) print year
true