blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b6ee3ae1c6ffa6db1546c8dd7bd12d5e0cfaf4eb
jonmckay/Python-Automate
/Section-6-Lists/lists-and-strings.py
945
4.40625
4
list('Hello') name = 'Zophie' name = [0] print(name) # Taking a section of a string name[1:3] print(name) # Create a new string using slices name = 'Zophie a cat' newName = name[0:7] + 'the' + name[8:12] print(newName) # References spam = 42 cheese = spam spam = 100 print(spam) # When you assign a list to a variable, you assign a reference of the list to the variable # The lists spam and cheese below are referencing the same list spam = [0, 1, 2, 3, 4, 5] cheese = spam cheese[1] = 'Hello!' print(cheese) print(spam) # Passing lists in function calls def eggs(someParameter): someParameter.append('Hello') spam = [1, 2, 3] eggs(spam) print(spam) # For mutable data types such as lists. You are creating a reference to that list. import copy # Copy.deepcopy creates a separate list in memory. Modifying cheese doesn't modify spam spam = ['A', 'B', 'C', 'D'] cheese = copy.deepcopy(spam) cheese[1] = 42 print(cheese) print(spam)
true
51aac9ce3556555f4292613680e1658480079c57
venkateshmorishetty/CSPP1
/m22/assignment2/clean_input.py
433
4.1875
4
''' Write a function to clean up a given string by removing the special characters and retain alphabets in both upper and lower case and numbers. ''' import re def clean_string(string): '''filters the string''' result = re.sub('[^a-zA-Z0-9]', '', string) return result def main(): '''read input and pass it to clan_string.''' string = input() print(clean_string(string)) if __name__ == '__main__': main()
true
12fe78e6920e54715d4ca8c9b12520a1419de7ba
venkateshmorishetty/CSPP1
/m22/assignment3/tokenize.py
644
4.21875
4
''' Write a function to tokenize a given string and return a dictionary with the frequency of each word ''' import re dictionary = {} def tokenize(string): '''tokenize''' # string1 = re.sub('[^a-zA-Z0-9]','',string) list1 = string.split(' ') for index_ in list1: index1 = re.sub('[^a-zA-Z0-9]', '', index_) if index1 in dictionary: dictionary[index1] += 1 else: dictionary[index1] = 1 def main(): '''main''' lines = int(input()) for _ in range(0, lines, 1): string = input() tokenize(string) print(dictionary) if __name__ == '__main__': main()
true
c5ce313a4133c2fa03e8d33b14f0bbae1cdc726d
donyewuc/Personal-Projects
/TicTacToe.py
1,606
4.15625
4
#! python3 #This program lets you play a simple 2-player game of Tic-Tac-Toe import sys board = {'tl':' ','tm':' ','tr':' ','ml':' ' ,'mm':' ','mr':' ','bl':' ','bm':' ','br':' ',} count = 0 turn = 'X' plays = [] def win(check): '''This function checks to see if you have won the game''' check('tl','tm','tr') check('ml','mm','mr') check('bl','bm','br') check('tl','ml','bl') check('tm','mm','bm') check('tr','mr','br') check('tl','mm','br') check('bl','mm','tr') def check(a,b,c): ''' This function checks to see if you have three in a row in one position ''' con = [board[a],board[b],board[c]] content = [x.strip() for x in con] if board[a] == board[b] == board[c] and all(content): print('You have won!') sys.exit() def tictac(board): '''This function prints the board''' count = 0 print() for key, value in board.items(): count += 1 print(f'{value:^6}', end =' | ') if count %3 == 0: print() for key, value in board.items(): place = input('\nWhere do you want to play? ') while place not in board: print('That is not a valid move on the board.') place = input('\nWhere do you want to play? ') while place in plays: print('You can only play in a position one time.') place = input('\nWhere do you want to play? ') board[place] = turn if turn == 'X': turn = 'O' else: turn = 'X' tictac(board) win(check) plays.append(place)
true
f52d78d9aec18519119d29e9ba2abdef0746ff5e
rhwb/python
/numbers3.py
286
4.125
4
num1 = input("Please enter a number here: \n") print("The number you have entered is: %s \n" %num1) num2 = input("Enter another number: \n") print("The second number you have entered is: %s \n" %num2) num3 = int(num1) + int(num2) print("%s + %s + %d" %num1 %num2 %num3)
true
27efacb6f3c118d46510ebf05b0cfa49c96e6428
luiscavazos/testrepo
/firstfile.py
1,644
4.21875
4
#name= "Luis" #Country= "Mexico" #Age= 37 #hourly_wage = 1000 #Satisfied = True #daily_wage = hourly_wage * 8 #print ("Your name is " + name) #print("you live in " + Country ) #print("You are " + str(Age) + " years old") #print("You make " + str(daily_wage) + " per day") #print("Are you satisfied with your current wage? " + str(Satisfied)) # 1. x = 5 y = 10 if 2 * x > 10: print("Question 1 works!") else: print("oooo needs some work") # ooo needs some work # 2. x = 34 y = 10 if len("supercalifragilisticespiralidocious") < x: print("Question 2 works!") else: print("Still missing out") #question 2 works # 3. x = 2 y = 5 if (x ** 3 >= y) and (y ** 2 < 26): print("GOT QUESTION 3!") else: print("Oh good you can count") #Got question 3! # 4. 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") #Dan is in group three # 5. height = 66 age = 22 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") #Can ride bumper cars
false
0cc1d3b2b39b518d6eae67a7b1f06349d2d6b443
ArchieMuddy/PythonExercises
/List/Exercise1/Approach4.py
315
4.125
4
# Swap the first and last elements of a list # Approach 4: Use the * operand inputList =[12, 35, 9, 56, 24] first, *remaining, last = inputList #stores first element in first, last element in last and remaining element in *remaining newList = last, *remaining, first #swap first and last print(newList)
true
688ffa9841e756a65d959b7fe1773fd87429bfea
ArchieMuddy/PythonExercises
/List/Exercise1/Approach2.py
382
4.1875
4
# Swap the first and last elements of the list # Approach 2: Don;t use the len function. Instead use list[-1] to access the last element of the list #swap function def swapList(newList): newList[0], newList[-1] = newList[-1], newList[0] #swapping logic without temp variable return newList #calling code inputList = [12, 35, 9, 56, 24] print(swapList((inputList)))
true
6d10a456493f1a50482ff74626f4c327e104228d
shitalajagekar/Python-Practice
/main.py
2,811
4.34375
4
# print("Hello world\n") # this is comment a=18 b="shital" c=2.2 # print(a+3) # converting int into float and string a1=float(a) a2=str(a) # print(a1,a2) # converting string into int and float # b1=int(b) # can not convert sting into int and float # b2= float(b) # print(b1,"\n", b2) # converting float into int and string c1= int(c) c2= str(c) # print(c1,"\n", c2) # string features name= '''shital is good girl''' # print(name) # print(name[0]) # print(name[2:4]) # print(name[2:]) # print(name[:10]) name1=" shital " # print(name.strip()) # print(len(name)) # print(name.lower()) # print(name.upper()) # print(name.replace("i","ee")) name2="siya" var="This is a {} and she is good girl {}".format(name.strip(),name2.strip()) # print(var) var="This is a {1} and she is good girl {0}".format(name.strip(),name2.strip()) # print(var) # use of f string var="This is a {name1} and she is good girl {name2}" # print(var) var=f"This is a {name1} and she is good girl {name2}" # print(var) ''' Python Collection: 1. List 2. Tuple 3. Set 4. Dictionary ''' # List lst=[23,45,3,4,56,78] lst2=type(lst) lst2=lst[1] # print(lst2) lst2=lst[1:6] # print(lst2) lst2=lst[:5] # print(lst2) lst2=len(lst) # print(lst2) lst2=len(lst) # print(lst2) lst[3]=11 lst2=lst # print(lst2) lst.append(100) # print(lst) lst.insert(1,200) # print(lst) lst.pop()# removes the element from end # print(lst) lst.remove(23) # print(lst) del lst[2] # print(lst) # Tuple a=("shital","siya",'kumar',"shital") var=type(a) # print(var) # a[2]="akshya" #cannot change the elements # print(a) n=a.count("shital") # count(): Returns the number of times a specified value occurs in a tuple # print(n) n=a.index("shital") # print(n) n=a.index("kumar") # print(n) a=list(a) var=type(a) # print(var) # Set a={2,3,4,2,2,2,4,5,6,7} # print(a) a.add(90) # add(): used to add single element into a # print(a) a.update([23,45,56]) # print(a) a.remove(2) # print(a) a.discard(122) # print(a) # Dictionary shitDict={ "name":"shital", "age":32, "sex":"female" } # print(shitDict) # print(shitDict["name"]) shitDict.pop("age") # print(shitDict) shitDict.update({"age":32,"marks":444}) # print(shitDict) del shitDict # print(shitDict) # age=input("Enter ur age\n") # print(age, type(age)) # age=int(age) # print(age, type(age)) #Function def display(): print("Hi Shital") print("Welcome to College") # display() # def sum(a,b): # return a+b # print(sum(2,3)) # class class Emp: def __init__(self): self.name="shital" self.age=34 self.salary=23000 e=Emp() print(e.name,"\n",e.age)
false
eb380d10f572e10320923a650768d38d730b086f
crash-bandic00t/python_dev
/1_fourth/algorithm_python/lesson1/task3.py
441
4.15625
4
# По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки. x1 = int(input("x1 = ")) y1 = int(input("y1 = ")) x2 = int(input("x2 = ")) y2 = int(input("y2 = ")) k = (y1 - y2) / (x1 - x2) b = y2 - k*x2 print(f'Уравнение прямой для этих точек: y = {k}x + {b}')
false
83b8c613b59572c31964330fde92946fe5fafd20
crash-bandic00t/python_dev
/1_fourth/algorithm_python/lesson1/task5.py
1,190
4.1875
4
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв. import string firstLetter = input('Введите букву английского алфавита для левой границы: ') secondLetter = input('Введите букву английского алфавита для правой границы: ') firstLetter = firstLetter.lower() secondLetter = secondLetter.lower() if ord(firstLetter) <= ord(secondLetter): cnt = 1 for i in string.ascii_lowercase: # итерируемся по буквам английского алфавита if i == firstLetter: print(f'Место буквы "{firstLetter}" в алфавите = {cnt}') tmp1 = cnt elif i == secondLetter: print(f'Место буквы "{secondLetter}"" в алфавите = {cnt}') tmp2 = cnt cnt += 1 print(f'Между введенными буквами {tmp2 - tmp1 - 1} букв(ы,а)') else: print('Некорректная граница букв')
false
f51bbb6a8590dd857d55f366d76238761a0a3f06
sodomojo/Week3
/hw3.py
2,476
4.375
4
#!/usr/bin/env python """ This script will do the following - Ask the user to enter a starting and ending number - Check that the starting number is not less than 1 - Check that the ending number is at least 5 times greater than the starting number - Create a list of integers in the range of the user's starting and ending numbers - Print out the number and index of each item in the list that is even - Sum and print all the odd numbers in the list """ # function to obtain the range start # output will be the user-inputted range start def first_number(): # set the start number to a global variable for consumption by the end range function. global start_num start_num = int(input("Please enter a starting number: ")) # check to ensure user enters a number greater than 1 if start_num < 1: print("The number must be more than 1. Try again.") first_number() else: return start_num # function to obtain the range end # output will be the user-inputted range end def end_number(): # set the end number to a global variable to capture the full range. global end_num end_num = int(input("Please enter an ending number: ")) # if the user enters a number less than 5x the range at the start of the list throw an error and retry. if end_num < (start_num * 5): print("The ending number must be at least five times greater than the starting number. Try again.") end_number() else: return end_num # call first and end range numbers first_number() end_number() # compute the full range based on the start and ended input values # add +1 to end range to make sure last number is counted full_range = list(range(start_num, end_num+1, 1)) # loop through full range and pull out all even numbers and their index. # Adding +1 so that the index starts at 1, not zero print("Even numbers in your list: \n") for even_index, i in enumerate(full_range): if i % 2 == 0: # adding +1 to even index so that index starts at 1, not 0 print("{} is at the {} index\n".format(i, str(even_index+1))) # create empty list that will eventually be all odd numbers odd_sum = [] # find all odd numbers in range by finding numbers with a remainder of 1. Add to odd num list for j in full_range: if j % 2 == 1: odd_sum.append(j) # print the sum of all the odd numbers print("The sum of your number list is: {} \n".format(sum(odd_sum))) input("Press any key to quit")
true
1186f93b2e38957a25e78ee8b9d779e0f9677b5c
Thorarinng/prog_01_kaflaverkefni
/Midterm_2/longest_gamla.py
1,015
4.25
4
import string # Function definitions start here def open_file(fname): """Tekur inn texta skrá or opnar hana""" try: word_file = '' input_file = open(fname, 'r') # for line in input_file: # word_file += line except FileNotFoundError: print("File {}.txt not found!".format(fname)) # return word_file return input_file def get_longest_word(wfile): """Finnur lengsta ordid og skilar thvi ut""" longest = '' length = 0 new_list = wfile.split() for word in new_list: if len(word) > length: longest = word length = len(longest) return longest # The main program starts here # filename = input("Enter name of file: ") filename = "longest.txt" file_stream = open_file(filename) if file_stream: longest_word = get_longest_word(file_stream) print("Longest word is '{:s}' of length {:d}".format(longest_word, len(longest_word))) file_stream.close else: print('File',filename,'not found!')
true
7edf6cc78129f9429b46630d61ad5526fff2a0a3
Thorarinng/prog_01_kaflaverkefni
/timaverkefni/7-5.py
635
4.34375
4
# palindrome function definition goes here def is_palindrome(strengur): nyr_strengur = strip(strengur) if nyr_strengur and (nyr_strengur[::-1] == nyr_strengur): return print('"{}"'.format(strengur), "is a palindrome.") else: return print('"{}"'.format(strengur), "is not a palindrome.") def strip(orgStrengur): samsett = "" temp = "" for stafur in orgStrengur: if stafur.isalpha(): samsett = temp + stafur temp = samsett return samsett.lower() in_str = input("Enter a string: ") # call the function and print out the appropriate message is_palindrome(in_str)
false
547302f7fe8bd3ef6a5c35997b5520053af1d85f
Thorarinng/prog_01_kaflaverkefni
/Skilaverkefni/hw2/2-2_characterCounts.py
734
4.15625
4
# Hlynur Magnus Magnusson # Hlynurm18@ru.is import string my_string = input("Enter a sentence: ") count_digit = 0 count_lower = 0 count_upper = 0 count_punktur = 0 # for every character in the string it checks for digits, lower, upper and punctuations # on each encounter we add one to the counter for char in my_string: if char.isdigit(): count_digit += 1 elif char.islower(): count_lower += 1 elif char.isupper(): count_upper += 1 elif char in string.punctuation: count_punktur += 1 print("{:>15}{:>6}".format("Upper case", count_upper)) print("{:>15}{:>6}".format("Lower case", count_lower)) print("{:>15}{:>6}".format("Digits", count_digit)) print("{:>15}{:>6}".format("Punctuation", count_punktur))
true
8335d1830f941ba3fcc6dc7f08a4e0a8430ec8c8
Thorarinng/prog_01_kaflaverkefni
/timaverkefni/7-6.py
308
4.125
4
# Your function definition goes here def fibo(tala): n1, n2 = 0, 1 print(1, end=' ') for i in range(tala-1): fib = n1 + n2 n1 = n2 n2 = fib print(fib, end=' ') n = int(input("Input the length of Fibonacci sequence (n>=1): ")) # Call your function here fibo(n)
false
633e22f59f95aa72896543ce0cc13b2e1d16c725
ajialala/python_work_study
/study_class_2.py
909
4.21875
4
class A(): def __init__(self): self.__name='python' #私有变量,翻译成 self._A__name='python' def __say(self): #私有方法,翻译成 def _A__say(self) print(self.__name) #翻译成 self._A__name a=A() #print a.__name #访问私有属性,报错!AttributeError: A instance has no attribute '__name' print(a.__dict__) #查询出实例a的属性的集合 print(a._A__name) #这样,就可以访问私有变量了 #a.__say()#调用私有方法,报错。AttributeError: A instance has no attribute '__say' print(dir(a))#获取实例的所有属性和方法 a._A__say() #这样,就可以调用私有方法了 ''' 从上面看来,python还是非常的灵活,它的oop没有做到真正的不能访问,只是一种约定让大家去遵守, 比如大家都用self来代表类里的当前对象,其实,我们也可以用其它的,只是大家习惯了用self '''
false
30cdfee01e33cbe30f08337a89371974b08debbf
monergeim/python
/fibonacci/func_l.py
375
4.46875
4
#!/usr/bin/python3.8 #calculates the nth Fibonacci number in O(n) time == without using any "for" or "while" loops import numpy as np num = input("Enter fibonacci num:") def fib_matrix(n): Matrix = np.matrix([[0,1],[1,1]]) vec = np.array([[0],[1]]) F=np.matmul(Matrix**n,vec) return F[0,0] print("Fibonacci n-th number is: " + str(fib_matrix(int(num))))
true
c51c5a55278b99d693a35a448a8240936a97e67c
wesley-998/Python-Exercicies
/33_Maio-numero.py
656
4.1875
4
print('Digite 3 números: ') n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1>n2>n3 or n1>n3>n2: print('{} é maior que {} e {}'.format(n1,n2,n3)) elif n2>n1>n3 or n2>n3>n2: print('{} é maior que {} e {}'.format(n2,n1,n3)) elif n3>n1>n2 or n3>n2>n1: print('{} é maior que {} e {}'.format(n3,n2,n1)) else: print('else') if n1<n2<n3 or n1<n3<n2: print('{} é menor que {} e {}'.format(n1,n2,n3)) elif n2<n1<n3 or n2<n3<n1: print('{} é menor que {} e {}'.format(n2,n1,n3)) elif n3<n1<n2 or n3<n2<n3: print('{} é menor que {} e {}'.format(n3,n2,n1)) else: print('else')
false
0d23856e20f128756fa1e29a5120a2de3b015060
wesley-998/Python-Exercicies
/096_Funcoes-area.py
460
4.1875
4
''' Programa com a função área(), que recebe as dimenções de um terreno retangular e mostre a área do terreno. ''' def area(largura,comprimento): m3 = a * l print(f'A área do terreno com {a}m de largura e {l}m de largura é {m3}m². ') def linha(): print('__' * 50) linha() print('Controle de Terrenos') linha() a = float(input('LARGURA (m): ')) l = float(input('COMPRIMENTO (m): ')) linha() area(a,l) linha()
false
da6493892c17f517ea3d53b1feacbf053d5faf30
wesley-998/Python-Exercicies
/021_MP3.py
351
4.1875
4
"""Programa que lê um número qualquer inteiro e converte para Binário, Hexadecimal ou Octadecimal""" n1 = int(input('Digite o número que você deseja converter: ')) opcao = int(input('''Digite a opção desejada. [ 1 ] Binário [ 2 ] Octal [ 3 ] Hexadecimal ''')) if opcao == 1: print('{} em binário é {}'.format(n1, bin(n1)))
false
de3a1f6d4905d4ae4b3049bb6fecbc121513a12b
veselotome4e/Programming0
/Week 2/Saturday_Tasks/is_prime.py
263
4.125
4
import math n = int(input("Enter n: ")) prime = True start = 2 while start <= math.sqrt(n): if n % start == 0: prime = False break start +=1 if prime: print("The number is prime!") else: print("The number is not prime!")
true
ecdfd79a0db5fa78a123fcf9f20ecc6f08cc8982
veselotome4e/Programming0
/Week 2/AndOrNotProblems/simple_answers.py
363
4.15625
4
userInput = input("Enter some text: ") if "hello" in userInput or "Hello" in userInput: print("Hello there, good stranger!") elif "how are you?" in userInput: print("I am fine, thanks. How are you?") elif "feelings" in userInput: print("I am a machine. I have no feelings") elif "age" in userInput: print("I have no age. Only current timestamp")
true
28f7be01317bfe5f3caf7639d6fe99535c898856
veselotome4e/Programming0
/Week 7/is_string_palindrom.py
520
4.1875
4
def is_string_palindrom(string): string = string.lower() delimiters = [',','.','!','?',':','-',"'",'"', ' '] modified = [x for x in string if x not in delimiters] modified = from_list_to_string(modified) return modified == modified[::-1] def from_list_to_string(l): s = "" for each in l: s += each return s print(is_string_palindrom("Az obi4am ma4 i boza")) print(is_string_palindrom("A Toyota!")) print(is_string_palindrom("bozaaa")) print(is_string_palindrom(" kapak! "))
false
06bb7485d5b94dff9b03b6ff15a06bdad535e024
raotarun/assignment3
/ass2.py
1,492
4.1875
4
#Create a list with user defined inputs. a=[] b=int(input("Enter First Element")) a.append(b) print(a) #Add the following list to above created list: [‘google’,’apple’,’facebook’,’microsoft’,’tesla’] c=["google","apple","facebook","microsoft","tesla"] c.append(a) print(c) #Count the number of time an object occurs in a list. c=[1,6,8,3,8] n=int(input("find element")) x=c.count(n) print(x) # create a list with numbers and sort it in ascending order. a=[1,6,8,3,8] a.sort() print(a) # - Given are two one-dimensional arrays A and B which are sorted in ascending order. Write a program to merge them into a single sorted array C that contains every item from arrays A and B, in ascending order. [List] c=[] b=[1,2,3,4] c=a+b c.sort() print(c) #Count even and odd numbers in that list. codd=ceven=0 for i in range(0,len(a)): if(c[i]%2==0): ceven=ceven+1 else: codd=codd+1 print("total even ",ceven) print("total even ",codd) #Print a tuple in reverse order. t=() t=('556','5564','98685') t=t[::-1] print(t) #Q.2-Find largest and smallest elements of a tuples. t=(1,2,3,4,5) x=max(tup) c=min(tup) print("max",x) print("min ",c) #Convert a string to uppercase. s='hello world' print(s.upper()) #Print true if the string contains all numeric characters. s="6515469259685616326" print(bool(s.isdigit())) #Replace the word "World" with your name in the string "Hello World". s="hello world" s1=s.replace('world','tarun rao') print(s1)
true
a5f490adc76c885d3f41e1f2990baf2e14305eb6
ericnnn123/Practice_Python
/Exercise6.py
367
4.28125
4
def CheckPalindrome(word): reverse = word[::-1] if word == reverse: print("'{}' is a palindrome".format(word)) else: print("'{}' is not a palindrome".format(word)) try: print("Enter a word to check if it's a palindrome") word = str(input()).lower() CheckPalindrome(word) except: print("There was an error")
true
23e31ffbe33b07da776bcf58aecbd78b6f5c0e3d
JenishSolomon/Assignments
/assignment_1.py
233
4.21875
4
#Area of the Circle A = 3.14 B = float(input("Enter the Radius of the circle: ")) C = "is:" print ("Input the Radius of the circle : ",B); print ("The area of the circle with radius",B,C) print (float(A*B**2))
true
238496ecca652af5fdefa421a9d0db146e78f7d3
pteerawatt/Elevator
/elevator1.3.py
1,348
4.4375
4
# In this exercise we demonstrait a program that simulates riding an elevator. #simple version # this is 2nd draft # refractored import time import sys def print_pause(message): #add print_pause() to refractor print(message) sys.stdout.flush() time.sleep(2) print_pause("You have just arrived at your new job!") print_pause("You are in the elevator.") while True: print_pause("Please enter the number for the floor " "you would like to visit:") floor = input("1. Lobby\n" #switch out each print_pause to just making it intput "2. Human resources\n" #also switch out variable name to floor from response "3.Engineering department\n") if floor == "1": #switch out if in to if == print_pause("You push the button for the first floor.") print_pause("You find yourself in the lobby") elif floor == "2": print_pause("You push the button for second floor.") print_pause("You find yourself in the human resources department.") elif floor == "3": print_pause("You push the button for third floor.") print_pause("you find yourself in the engineering department.") print_pause("where would you like to go next?") # remove where would you like to go next at each choice and just add to the end of loop instead.
true
c2052a8082181a75fe993a36aff6a19cfe23ac8c
melgreg/sals-shipping
/shipping.py
1,323
4.15625
4
class ShippingMethod: """A method of shipping with associated costs.""" def __init__(self, name, flat_fee=0.00, max_per_pound=0.00, cutoffs=[]): self.name = name self.flat_fee = flat_fee self.max_per_pound = max_per_pound self.cutoffs = cutoffs def get_cost(self, w): """Calculate the cost of shipping a package weighing w lbs by this method.""" price_per_pound = self.max_per_pound for weight, price in self.cutoffs: if w <= weight: price_per_pound = price break return self.flat_fee + w * price_per_pound if __name__ == '__main__': weight = 6 ground = ShippingMethod("Ground Shipping", 20, 4.75, [(2, 1.50), (6, 3.00), (10, 4.00)]) ground_premium = ShippingMethod("Ground Premium", 125) drone = ShippingMethod("Drone Shipping", 0, 14.25, [(2, 4.50), (6, 9.00), (10, 12.00)]) ## print(f"{ground.name}: ${ground.get_cost(weight):.2f}") ## print(f"{ground_premium.name}: ${ground_premium.get_cost(weight):.2f}") ## print(f'{drone.name}: ${drone.get_cost(weight):.2f}') methods = [ground, ground_premium, drone] costs = [(method.name, method.get_cost(weight)) for method in methods] method, cost = min(costs, key=lambda x: x[1]) print(f'{method}: ${cost:.2f}')
true
a3ca0d1f54d4a9e301fbe78c23a8bd3ebbff2194
dmayo0317/python-challenge
/PyBank/main.py
2,210
4.1875
4
#Note most of code was provided by the UTSA instructor(Jeff Anderson) just modify to fit the assignment. #Impot os module and reading CSV modules import os import csv # Creating Variable to hold the data profit = [] rowcount = 0 TotalProfit = 0 AverageProfit = 0 AverageChange = 0 LostProfit = 0 GainProfit = 0 #locating the file path of reading the csv data PyBankdataFile = os.path.join('Resources', 'budget_data.csv') #Opens and reads csv file with open(PyBankdataFile, newline="") as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') # Read the header row first (skip this step if there is no header) csv_header = next(csvreader) #checking if this prints the Header of the CSV file. print(f"CSV Header: {csv_header}") # Forloop to help find the profit, number of rows etc. for row in csvreader: # count the numer or Months by reading the number of rows. rowcount = rowcount +1 #The net total amount of "Profit/Losses" over the entire period profit.append(row[1]) TotalProfit = TotalProfit + int(row[1]) #Calculate the changes in "Profit/Losses" over the entire period, then find the average of those changes AverageProfit = TotalProfit / rowcount if float(row[1]) <=0: LostProfit = LostProfit - int (row[1]) elif float(row[1]) >0: GainProfit = GainProfit + int(row[1]) print("Total Months:", rowcount) print("Total Profit:", int (TotalProfit)) print('Average Profit is $', int (AverageProfit)) print("Greatest Decrease in Profits was", float(LostProfit)) print("Greatest Increase in Profits was", float(GainProfit)) # Create a text file to wite to the file with open('Results_PyBank', 'w') as text: text.write(f"Total Months: {rowcount}\n") text.write(f"Total Proft:$ {TotalProfit}\n") text.write(f"The Average Profit is $ {AverageProfit}\n") text.write(f"The Greatest Decrease in Profits was $ {LostProfit}\n") text.write(f"The Greatest Increase in Profits was $ {GainProfit}\n")
true
08df24bcafbb22a66ebead8d4fcdb81494347f52
ankit-kejriwal/Python
/calculator.py
314
4.34375
4
num1 = float(input("ENter first number")) num2 = (input("ENter oprtator")) num3 = float(input("ENter second number")) if num2 == "+": print(num1+num3) elif num2 == '-': print(num1 - num3) elif num2 == '*': print(num1 * num3) elif num2 == '/': print(num1 / num3) else: print("wrong operator")
false
233e89bf08eaaa7765e33f26e6b94adce4b66474
alok8899/colab_python
/python057.py
1,032
4.15625
4
#! python3 import os os.system("cls") """ def factorials(innumber): #Factorial=1 while innumber>=1: Factorial=Factorial*(innumber) innumber-=1 return Factorial print("the factorial of no ") invalue=int(input("enter the value to find the factorial : ")) factorials(invalue) print("the factorial of",factorials(invalue)) """ """ def Factorialofnumber(innumber): if innumber==0: return 1 else: return innumber * Factorialofnumber(innumber-1) print("the factorial of number ") infactorialnumber=int(input("enter the value that u want to get factorial : ")) print("the factorial of ",infactorialnumber,"is ",Factorialofnumber(infactorialnumber)) """ def Factorialofnumber(innumber): return 1 if (innumber==0 or innumber==1) else innumber * Factorialofnumber(innumber -1) factorialinvalue=int(input("enter the value that u want to find factorial : ")) print("the factorial of ",factorialinvalue,"is",Factorialofnumber(factorialinvalue))
false
bd56bc9c8f411d9cb58862397e9fa779055a59c0
vtainio/PythonInBrowser
/public/examples/print.py
933
4.40625
4
# print.py # Now we know how to print! print "Welcome to study with Python" # 1. Write on line 6 code that prints your name to the console # 2. If you want to print scandic letters you have to add u in front of the text, like this. # Take the '#' away and click run # print u"äö" # 3. We can also print other things than text # Remove '#' from the beginning of the beginning of next line and try running the code # print 1 + 1 # 4. Make more calculations. Print the result to the console and let the computer do the calculation. # Whenever printing content to console remember to start the line with 'print' # for example like this: # print 1 + 2 or print 1 * 2 # a) calculate your age + your friends age # b) choose number, multiply it with 10 and then multiply it with 3 # c) Make an equation of your own and print the result # d) Try printing the result of 1/2. What do you notice? We'll fix this in next exercise.
true
76708d7104e7cf43dbfef33cdfe3712de9905a31
hglennwade/hglennrock.github.io
/gdi-intro-python/examples/chained.py
253
4.34375
4
raw_input = input('Please enter a number: ') #For Python 2.7 use #raw_input = raw_input('Please enter a number: ') x = int(raw_input) if x > 5: print('x is greater than 5') elif x < 5: print('x is less than 5') else: print('x is equal to 5')
true
a4458a5f224971b83dd334bb0c1dbec49495809e
professionalPeter/adventofcode
/2019/day01.py
885
4.125
4
def calc_simple_fuel_requirement(mass): """Return the fuel required for a given mass""" return int(mass/3) - 2 def calc_total_fuel_requirement(mass): """Return the total fuel requirement for the mass including the recursive fuel requirements""" fuel_for_this_mass = calc_simple_fuel_requirement(mass) if fuel_for_this_mass <= 0: return 0 return fuel_for_this_mass + calc_total_fuel_requirement(fuel_for_this_mass) def part1(): """Output the answer for part 1""" x = 0 with open('day01input.txt') as fp: return sum([calc_simple_fuel_requirement(int(mass)) for mass in fp]) def part2(): """Output the answer for part 2""" x = 0 with open('day01input.txt') as fp: return sum([calc_total_fuel_requirement(int(mass)) for mass in fp]) print(f'Part 1 answer: {part1()}') print(f'Part 2 answer: {part2()}')
true
6f7ad11ac3dbce19b9e8d17e82df4fb74440b6b1
Bhoomika-KB/Python-Programming
/even_odd_bitwise.py
236
4.40625
4
# -*- coding: utf-8 -*- num = int(input("Enter a number: ")) # checking the number using bitwise operator if num&1: print(num,"is an odd number.") else: print(num,"is an even number.")
true
970de860d7934e94625f86272a8147684d6152e1
JoamirS/Fundamentos-python
/12class.py
872
4.1875
4
""" Criando uma lista composta """ #People = [['Bruce Wayne', 45], ['Steve Rodgers', 70], ['Peter Parker', 20], ['Superman', 40]] #print(People[0][0]) """ Criando uma estrutura em que faço o cadastro de 3 pessoas e no final apago os dados de Data, mas os dados de People continuam """ People = list() Data = list() AllAdulthood = 0 AllMinority = 0 for FormPeople in range(0, 3): Data.append(str(input('Nome: '))) Data.append(int(input('Idade: '))) People.append(Data[:]) # Este comando gera uma cópia Data.clear() # Este comando limpa os dados de Data após fazer uma cópia sua for Person in People: if Person[1] >= 21: print(f'{Person[0]} é maior de idade.') AllAdulthood += 1 else: print(f'{Person[0]} é menor de idade.') AllMinority += 1 print(f'Temos {AllAdulthood} maiores de idade e {AllMinority} menores de idade.')
false
3e9ed0848c34588af83cf79f29e854e6d1c9d510
Puthiaraj1/PythonBasicPrograms
/ListRangesTuples/listsExamples.py
379
4.125
4
ipAddress = '1.2.3.4' #input("Please enter an IP address :") print(ipAddress.count(".")) # Here I am using sequence inbuilt method count even = [2,4,6,8] odd = [1,3,5,7,9] numbers = even + odd # adding two list numbers.sort() # This is another method to sort the list value in ascending # You can use sorted(numbers). sorted() also works the same as '.sort()' print(numbers)
true
2b587eb5292af3261309413e7cd9436add8b72ef
dilesh111/Python
/20thApril2018.py
904
4.625
5
''' Python program to find the multiplication table (from 1 to 10)''' num = 12 # To take input from the user # num = int(input("Display multiplication table of? ")) # use for loop to iterate 10 times for i in range(1, 11): print(num,'x',i,'=',num*i) # Python program to find the largest number among the three input numbers # change the values of num1, num2 and num3 # for a different result num1 = 10 num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user # num1 = float(input("Enter first number: ")) # num2 = float(input("Enter second number: ")) # num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number between", num1, ",", num2, "and", num3, "is", largest)
true
dfcf5d72d3ccedb10309dfacb5117364d8e7060c
anajera10/mis3640
/Assignment 1/nim.py
975
4.15625
4
from random import randrange def nim(): """ Plays the game of Nim with the user - the pile size, AI intelligence and starting user are randomly determined Returns True if the user wins, and False if the computer wins """ # randomly pick pile size pile_size = randrange(10,100) # random - decide who starts 0 is the computer 1 is the human turn = randrange(0,1) # decide if computer is smart or dumb: 0 is dumb and 1 is smart ai_intelligence = randrange(0,2) print ('Pile is %s marbles to start' %(pile_size)) if ai_intelligence == 0: print('The computer is playing dumb') else: print('The computer is smart') while pile > 0: if turn = 0 print ('human move' turn + 1 elif turn = 1 if intelligence = 0: print ('stupid computer code') elif intelligence = 1: print ('smart computer code') turn - 1 if turn = 0: print("The computer won!") else: print("You Won!")
true
264f1813ea8c0463f4b6d87be10a167f33e30d5b
wheezardth/6hours
/Strings.py
1,222
4.25
4
# triple quotes allow to use single & double quotes in strings # No Need For Escape characters! (Yet...) course = '''***Monty-Python's Course for "smart" people***''' print(course) wisdom = ''' Triple quotes also allow to write string with line breaks in them. This is super convenient. Serial.print(vomit) ''' print(wisdom) # keep in mind that the quotes themselves cant be on a new line # realWisdom = # ''' # This doesn't work. # '' # Strings behave a bit like arrays of characters (which they are) and # can be addressed by an index, which will return the character. # The discrete character data type is not a thing in Python print(course[0]) print(course[3]) print(type(course)) # this returns string class print(type(course[0])) # this returns string class too print(course[-4]) # this allows you to warp around and index back to front # Using column allows you to extract a substring between the index numbers! # It will INCLUDE the start index # But will EXCLUDE the end index # If it didn't there'd be a dash after Monty print(course[3:8]) # There are defaults too print(course[3:]) # all the way to the end print(course[:8]) # all the way from the start print(course[:]) # all the stuff
true
1c0125fd19de4485bd49b72f0995f57583dd31c7
wheezardth/6hours
/classes.py
890
4.1875
4
# classes define custom data types that represent more complex structures # Default python naming convention: email_client_handler # Pascal naming convention: EmailClientHandler # classes in python are named using the Pascal naming convention # classes are defined using the class keyword # classes are blueprints of complex structures # objects are the -actual- instances of classes, e.g. instances of those blueprints # attributes are like variables for specific objects class Point: def move(self): #methods print("move") def draw(self): print("draw") # Point() # this creates a new object point1 = Point() # we now store this in a variable point1.x = 10 # attributes do not need to be declared in advance in the class definition? point1.y = 20 print(point1.x) point1.draw() point2 = Point() point2.x = 1 print(point2.x)
true
881ae7a58bdc18dac968b135294022aec4f641c9
wheezardth/6hours
/StringTricks.py
754
4.125
4
course = 'Python for Beginners' # len() gives string length (and other things!) print(len(course)) # len() is a FUNCTION course.upper() # .something() is a METHOD because it belong to a class print(course) # the original variabe is not affected capString = course.upper() print(capString) # the new one is tho print(course.find("n")) # returns the index of the 1st instance of the search term print(course.find("Beginners")) print(course.find("*")) # returns -1 because term cant be found print(course.replace("Beginners","Genuine Retards")) # replace does ..replace # "Python" in course # this is an actual expression in Python that returns BOOL content = "Python" in course # bool type is assigned automatically! print(type(content)) print(content)
true
34ba84a353937822b8f9329effc073185459a380
C-Joseph/formation_python_06_2020
/mes_scripts/volubile.py
324
4.3125
4
#!/usr/bin/env python3 #Tells user if length of string entered is <10, <10 and >20 or >20 phrase = input("Write something here: ") if len(phrase) < 10: print("Phrase of less than 10 characters") elif len(phrase) <= 20: print("Phrase of 10 to 20 characters") else: print("Phrase of more than 20 characters")
true
426dbdf9f784ee6b3c1333b0fda1a9a2eacc2676
antonborisov87/python-homework
/задание по строкам/test2.py
903
4.5
4
"""Задание по строкам: 1.1. Create file with file name test.py 1.2. Create variable x and assign "London has a diverse range of people and cultures, and more than 300 languages are spoken in the region." string to it. 1.3. Print this string with all letters uppercase. 1.4. Print this string the index of first "c" letter in this string. 1.5. Print the count of "o" letters in this string. 1.6. Print a list of all words in this string. Should be - ['London', 'has', 'a', 'diverse', 'range', 'of', 'people', 'and', 'cultures,', 'and', 'more', 'than', '300', 'languages', 'are', 'spoken', 'in', 'the', 'region.'] 1.7. Replace all "a" letters with "A" in this string.""" x = "London has a diverse range of people and cultures, and more than 300 languages are spoken in the region." print(x.upper()) print(x.find('c')) print(x.count('o')) a = x.split() print(a) print(x.replace('a', 'A'))
true
7c99435541a487308dba15237bf4c57867e205f3
neugene/lifelonglearner
/Weight_Goal_Tracker.py
1,975
4.21875
4
#This program tracks weightloss goals based on a few parameters. # The entries of initial weight and current weight establish the daily weight loss change/rate # which is used to extrapolate the target weight loss date from datetime import datetime, timedelta initial_weight = float(input("Enter initial weight in lbs: > ")) date_initial_weight = str(input("Enter your weigh-in date as YYYY-MM-DD: > ")) initial_weighin_date = datetime.strptime(date_initial_weight, "%Y-%m-%d") current_weight = float(input("Enter current weight in lbs: > ")) if current_weight > initial_weight: print("\nYou're actually gaining weight and I am unable to establish a date when you will achieve your goal.") else: target_weight = float(input("Enter target weight in lbs: > ")) weight_change = current_weight - initial_weight w = weight_change date_current_weight = datetime.today() print("\n\nYour weight change since the weigh-in on", initial_weighin_date,"is", w,"lbs.") print("\nThe current date is", date_current_weight,"and your current weight is",current_weight,"lbs.") days_since_initial_weight = date_current_weight - initial_weighin_date d = days_since_initial_weight.days print ("\nIt's been" ,d ,"days since your first weigh-in on", initial_weighin_date,".") daily_weight_change = w/d dwc = round(daily_weight_change,3) print("\nSo far your daily weight change has been", dwc, "lbs.") unmet_weight_loss = current_weight - target_weight uwl = unmet_weight_loss ("\nYou still have", uwl, "lbs to lose.") days_to_target_weight_date = round(abs(uwl/dwc)) target_weight_loss_date = date_current_weight + timedelta(days_to_target_weight_date) print("\nAt your current rate, you have",days_to_target_weight_date,"days to meet your goal.") print("\nYou will meet your weight loss goal on", target_weight_loss_date,".")
true
d09b15df7682cf7a027b8e70300274a98a5be5df
matham/vsync_rpi_data
/animate.py
1,557
4.375
4
''' Widget animation ================ This example demonstrates creating and applying a multi-part animation to a button widget. You should see a button labelled 'plop' that will move with an animation when clicked. ''' from os import environ #environ['KIVY_CLOCK'] = 'interrupt' import kivy kivy.require('1.0.7') from kivy.animation import Animation from kivy.app import App from kivy.uix.widget import Widget from kivy.lang import Builder Builder.load_string(''' <MyWidget>: size_hint: None, None size: '20dp', '600dp' canvas: Color: rgb: .5, .5, .5 Rectangle: size: self.size pos: self.pos ''') class MyWidget(Widget): pass class TestApp(App): def animate(self, instance): # create an animation object. This object could be stored # and reused each call or reused across different widgets. # += is a sequential step, while &= is in parallel animation = Animation(pos=(1000, 0), t='linear') animation += Animation(pos=(0, 0), t='linear') animation.repeat = True # apply the animation on the button, passed in the "instance" argument # Notice that default 'click' animation (changing the button # color while the mouse is down) is unchanged. animation.start(instance) def build(self): # create a button, and attach animate() method as a on_press handler button = MyWidget() self.animate(button) return button if __name__ == '__main__': TestApp().run()
true
ee0c3ca2ae21b7dc7b0c0894210277392cbe3456
ebonnecab/CS-1.3-Core-Data-Structures
/Code/search.py
2,869
4.28125
4
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found Worst case time complexity is O(n) where n is every item in array """ # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests # return linear_search_iterative(array, item) return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): if index > len(array)-1: return None elif array[index] == item: return index else: return linear_search_recursive(array, item, index+1) # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests def binary_search(array, item): """return the index of item in sorted array or None if item is not found Time complexity is O(log n) where n is items in array bc it cuts array in half """ # implement binary_search_iterative and binary_search_recursive below, then # change this to call your implementation to verify it passes all tests # return binary_search_iterative(array, item) return binary_search_recursive(array, item) def binary_search_iterative(array, item): #implement binary search iteratively here first = 0 last = len(array) -1 position = None found = False while not found and first <= last: midpoint = (first + last) //2 if array[midpoint] == item: found = True position = midpoint #if item is smaller than midpoint ignore the right elif item < array[midpoint]: last = midpoint -1 #if item is greater than midpoint ignore the left elif item > array[midpoint]: first = midpoint+1 return position def binary_search_recursive(array, item, left=None, right=None): #implement binary search recursively here if left is None and right is None: left = 0 right = len(array)-1 #base case if left > right: return midpoint = (left + right) // 2 if array[midpoint] > item: right = midpoint-1 return binary_search_recursive(array, item, left, right) elif array[midpoint] < item: left = midpoint+1 return binary_search_recursive(array, item, left, right) else: return midpoint # once implemented, change binary_search to call binary_search_recursive # to verify that your recursive implementation passes all tests
true
4dacde6d91cc83d58f4bc06c19bba5fe436493af
Harshan-Sarkar/important_concepts
/WHJR_PYTHON/Other_programms/Pallindrome_Detector.py
227
4.28125
4
a = input("Enter to check if a word is a pallindrome or not: ") a = a.replace(" ", "") b = a.upper() c = b[::-1] if b == c : print(f"Yes, '{a}' is a pallindrome.") else : print(f"No, '{a}' is not a pallindrome.")
false
2ffe0b58632675457a7f159c5da87cda4c8ca5ea
lew18/practicepython.org-mysolutions
/ex16-password_generator.py
2,119
4.15625
4
""" https://www.practicepython.org Exercise 16: Reverse Word OrderPassword Generator 4 chilis Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method. Extra: Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list. """ import random import string def generate_password(length = 4): choices = [string.punctuation, string.digits, string.ascii_lowercase, string.ascii_uppercase] password = [] # first, include one of each type for group in choices: password.append(group[random.randint(0, len(group) - 1)]) # next, fill out the password to the desired length for i in range(length - len(choices)): group = random.randint(0, len(choices)-1) index = random.randint(0, len(choices[group])-1) password.append(choices[group][index]) # shuffle the characters for i in range(7): for original_position in range(len(password)): password.insert(random.randint(0, len(password) - 1), password.pop(original_position)) # assemble into one text string return ''.join([str(i) for i in password]) length = 15 new_password = generate_password(length) print(new_password) # I"m being lazy, solution to exercise 31 shows how to pick a random word. # one solution put all of the characters into one long string then does # p = "".join(random.sample(s, 8)) # another uses return ''.join(random.choice(chars) for _ in range(size)) # along with string.ascii_letters, string.digits, and string.punctuation # so I copied part of that, originally listed out the digits and a string of symbols # also, notice the _ # # problem with these solutions is they don't force presence # of at least one of each type of the four classifications.
true
a782134e78b9059206f0068a4896d51898c2d42f
lew18/practicepython.org-mysolutions
/ex18-cose_and_bulls.py
2,236
4.375
4
""" https://www.practicepython.org Exercise 18: Cows and Bulls 3 chilis Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull ... Until the user guesses the number. """ import random def generate_target(): return(int(random.triangular() * 10000)) def compare(guess, target): if guess > 9999: print("guess must be 4 digits or less, try again.") return False cows = bulls = 0 g = [ int((guess % 10000) / 1000), int((guess % 1000) / 100), int((guess % 100) / 10), int((guess % 10) / 1) ] t = [ int((target % 10000) / 1000), int((target % 1000) / 100), int((target % 100) / 10), int((target % 10) / 1) ] for i in 3, 2, 1, 0: if g[i] == t[i]: g.pop(i) t.pop(i) cows += 1 for i in range(len(g)-1, -1, -1): if g[i] in t: t.pop(t.index(g[i])) g.pop(i) bulls += 1 if cows == 4: return True else: print("cows: %d, bulls: %d " % (cows, bulls)) return False if __name__ == "__main__": target = generate_target() print("target is %4d" % target) guess_count = 1 guess = int(input("What's your first guess? ")) while False == compare(guess, target): guess_count += 1 guess = int(input("What's your next guess? ")) print("Took %d guesses to guess %4d." % (guess_count, target))
true
64fdc533942c6079155317077310ca6a2cf052fc
lew18/practicepython.org-mysolutions
/ex24-draw_game_board.py
1,891
4.8125
5
""" https://www.practicepython.org Exercise 24: Draw a Game Board 2 chilis This exercise is Part 1 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 2, Part 3, and Part 4. Time for some fake graphics! Let’s say we want to draw game boards that look like this: --- --- --- | | | | --- --- --- | | | | --- --- --- | | | | --- --- --- This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more). Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s print statement. Remember that in Python 3, printing to the screen is accomplished by print("Thing to show on screen") Hint: this requires some use of functions, as were discussed previously on this blog and elsewhere on the Internet, like this TutorialsPoint link. """ # I had for loops, Nichele's example taught the "* size" inside the print statement def print_boarder(size): print(' ---' * size) def print_row(size): print('| ' * size + '|') def draw_simple_board(size): print("size is " + str(size)) print_boarder(size) # print the top border for rows in range(size): print_row(size) print_boarder(size) if __name__ == '__main__': size = int(input("what size game board do you want? ")) draw_simple_board(size) print("\nmy second, with help from Michele's solution and user's solution") a = '---'.join(' ' * (size + 1)) b = ' '.join('|' * (size + 1)) print('\n'.join(((a, b) * size)) + '\n' + a) # 1 234 4 32 1 print("\nuser's solution from solutions page") # below is a 'user' solution, which I played with # to make the above solution # this is hard coded to 3x3 a = '---'.join(' ') b = ' '.join('||||') print('\n'.join((a, b, a, b, a, b, a)))
true
56280fb746e3ecab8bd857bfb66615ed32819dbd
lew18/practicepython.org-mysolutions
/ex02-odd_or_even.py
975
4.40625
4
""" https://www.practicepython.org Exercise 2: Odd or Even 1 chile Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: 1. If the number is a multiple of 4, print out a different message. 2. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. """ number = int(input("Enter an integer: ")) if (number % 4) == 0: print(str(number) + " is evenly divisible by 4.") elif ((number %2) == 0): print(str(number) + " is even.") else: print(str(number) + " is odd.") divisor = int(input("Enter a second integer: ")) if number % divisor: print("%d is not a divisor of %d." % (divisor, number)) else: print("%d is a divisor of %d." % (divisor, number))
true
7cd4741918ca8944686e2aa3905aa0e59fe022ee
OtchereDev/python-mini-project
/age_check.py
383
4.40625
4
print('Hello user, Welcome to the age grouping app \n') age= int(input('\n Please what is your age in numbers? ')) if age == 0 or age <= 12: print('Kid') elif age<=30 or age <= 19: print('Teenager') elif age<=20 or age<=30: print('Young Adult') elif age<=31 or age<=64: print('Adult') elif age>=65: print('Senior') else: print('Please enter a number age.')
false
d51ea53c283dcd6fc2af776a8e0600f72a26efa9
iaryankashyap/ReadX
/Code/ReadX.py
1,069
4.34375
4
# This program calculates the difficulty of a body of text by assigning it a grade # gets user input about the text text = input("Text: ") letters = 0 words = 0 sentences = 0 counter = 0 for i in text: counter += 1 for i in range(counter): # counts the letters using ascii code if (ord(text[i]) >= 65 and ord(text[i]) <= 122): letters += 1 # counts the words by reading spaces elif (ord(text[i]) == 32 and (ord(text[i - 1]) != 33 and ord(text[i - 1]) != 46 and ord(text[i - 1]) != 63)): words += 1 # counts the sentences by finding dots, exclamation marks and interrogatives elif (ord(text[i]) == 33 or ord(text[i]) == 46 or ord(text[i]) == 63): sentences += 1 words += 1 L = letters * 100 / words S = sentences * 100 / words # Coleman-Liau index is computed using the formula index = round(0.0588 * L - 0.296 * S - 15.8) # Finally outputs the result to the user if (index < 1): print("Before Grade 1") elif (index >= 16): print("Grade 16+") else: print("Grade:", index) raw = input()
true
468f10c5d3c13113a73f4fc36c454a082cd2d3a0
Sunsmailer/PythonByMediasoft
/PythonByMediasoft/lesson2duplicates.py
449
4.21875
4
#первый вариант duplicates = ['1', '2', '3', '3', '6', '4', '5', '6'] new_duplicates = [] [new_duplicates.append(item) for item in duplicates if item not in new_duplicates] new_duplicates.sort() print(new_duplicates) #второй вариант dup1 = {'1', '2', '3', '3', '6', '4', '5', '6'} dup2 = {'1', '2', '3', '4', '5','6'} dup = dup1.union(dup2) #через пересечение dup = sorted(dup) print(dup)
false
6d38db8cf36b30a5d45a44aa94592a57b4212251
ashwithaDevireddy/PythonPrograms
/conditional.py
280
4.125
4
var=float(input("Enter the number :")) if var > 50: print("greater") elif var == 50: print("equal") // used if multiple conditions are implemented else: print("smaller") output: Enter the number :2 smaller Enter the number :50 equal Enter the number :51 greater
true
b9fdb656f713c1ac6f5a408d006ca9823f46b773
rishabhgupta/HackerRank-Python
/datatypes.py
2,430
4.1875
4
# 1. LISTS """ You have to initialize your list L = [] and follow the N commands given in N lines. """ arr = [] n = input() for i in range(int(n)): input_str = input() split_str = input_str.split(' ') if split_str[0] == 'insert': arr.insert(int(split_str[1]),int(split_str[2])) elif split_str[0] == 'print': print(arr) elif split_str[0] == 'remove': arr.remove(int(split_str[1])) elif split_str[0] == 'append': arr.append(int(split_str[1])) elif split_str[0] == 'sort': arr.sort() elif split_str[0] == 'reverse': arr.reverse() elif split_str[0] == 'pop': arr.pop() # 2. TUPLES """ You are given an integer N in one line. The next line contains N space-separated integers. Create a tuple of those N integers. Lets call it T. Compute hash(T) and print it. """ n = input() input_str = input() lst_int = [int(x) for x in input_str.split(" ")] tup = tuple(lst_int) print(hash(tup)) # 3. SETS - SYMMETRIC DIFFERENCE """ Given two set of integers M and N and print their symmetric difference in ascending order. """ N = int(input()) int_list1 = list(map(int,input().split())) N = int(input()) int_list2 = list(map(int,input().split())) setA = set(int_list1) setB = set(int_list2) setADB = setA.difference(setB) setBDA = setB.difference(setA) res = [] for i in setADB: res.append(i) for i in setBDA: res.append(i) res.sort() for i in res: print(i) # List Comprehensions """ Given three integers X, Y and Z denoting the dimensions of a Cuboid. Print a list of all possible coordinates on the three dimensional grid... """ x, y, z, n = (int(input()) for _ in range(4)) print([[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a+b+c!=n ]) # Find second largest number in a list num, input_list = int(input()), [int(x) for x in input().split(' ')] l = list(set(input_list)) l.sort() print(l[-2]) # Nested list """ There is a classroom of 'n' students and you are given their names and marks in physics. Print the name of each student who got the second lowest marks in physics. """ num = int(input()) complete_list = [[input(), float(input())] for _ in range(num)] complete_list.sort(key=lambda x: x[1]) marks_sorted = sorted({mark[1] for mark in complete_list}) result = sorted(value[0] for value in complete_list if value[1]==marks_sorted[1]) for name in result: print(name)
true
8ba19ee0a4811e3f73a66d95e82614ac2b553973
weifengli001/pythondev
/vendingmachine/test.py
2,787
4.28125
4
""" CPSC-442X Python Programming Assignment 1: Vending Machine Author: Weifeng Li UBID: 984558 """ #Global varable paid_amount = 0.0#The total amount of insert coins total = 0 #The total costs change = 0 # change drinks = {"Water" : 1, "Soda" : 1.5, "Juice" : 3} # The drinks dictionary stores drinks and their price snackes = {"Chips" : 1.25, "Peanuts" : 0.75, "Cookie" : 1} #The snackes dictionary stores snackes and their price """ entering function parameter: factor, is the value of the coin """ def vending(factor = 0.25): global paid_amount, total, change print("Welco to the UB vending machine.") cnt = input("Enter the number of quarters you wish to insert: ") paid_amount = int(cnt) * factor change = paid_amount - total print("You entered ", paid_amount, " dollars.") main_menu() #main menu def main_menu(): global paid_amount, total, change while True: print("------------------------------------") print("Select category: ") print("1. Drinks") print("2. Snacks") print("3. Exit") selection = input("Select an option: ") if(selection == '1'): drinks_menu() elif(selection == '2'): snackes_menu() elif(selection == '3'): #change = paid_amount - total print("Paid amount: ", paid_amount, ", total purchase: ", total, ", change: ", change) return else: print("Invalid selection.") #drinks menu def drinks_menu(): global paid_amount, total, change while True: print("-------------------------------------") print(" Juice ($3)") print(" Water ($1)") print(" Soda ($1.5)") drink = input("Enter your drink selection (x to exit): ") if(drink == 'x'): break elif(drinks.get(drink) == None): print("Invalid selection.") else: if(drinks[drink] > change): print("You don't have enough money to buy", drink) else: total += drinks[drink] change -= drinks[drink] #snackes menu def snackes_menu(): global paid_amount, total, change while True: print("-----------------------------------------") print(" Chips: ($1.25)") print(' Peanuts: ($0.75)') print(" Cookie: ($1)") snack = input("Enter your snack selection (x to exit): ") if(snack == 'x'): break elif(snackes.get(snack) == None): print("Invalid selection.") else: if(snackes[snack] > change): print("You don't hava enough money to buy", snack) else: total += snackes[snack] change -= snackes[snack] vending()
true
0055ee064f2ecc83380d31b3de93f6fa181d2aa5
kriyazhao/Python-DataStructure-Algorithms
/7.1_BinaryTree.py
2,786
4.15625
4
#-------------------------------------------------------------------------- # Define a binary tree using List def BinaryTree(root): return [root, [], []] def insertLeft(root, branch): leftChild = root.pop(1) if len(leftChild) < 1: root.insert(1, [branch, [], []]) else: root.insert(1, [branch, leftChild, []]) return root def insertRight(root, branch): rightChild = root.pop(2) if len(rightChild) < 1: root.insert(2, [branch, [], []]) else: root.insert(2, [branch, [], rightChild]) return root def getRootVal(root): return root[0] def setRootVal(root, newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] BTree = BinaryTree(7) insertLeft(BTree, 2) insertLeft(BTree, 3) insertRight(BTree, 11) insertRight(BTree, 9) print BTree leftChild = getLeftChild(BTree) print "the left child of root 7 is:", leftChild setRootVal(leftChild, 5) print BTree insertLeft(leftChild, 4) print BTree print getLeftChild(leftChild) #-------------------------------------------------------------------------- # Define a binary tree using Nodes and References class BinaryTree: def __init__(self, rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self, newBranch): if self.leftChild == None: self.leftChild = BinaryTree(newBranch) else: branch = BinaryTree(newBranch) branch.leftChild = self.leftChild self.leftChild = branch def insertRight(self, newBranch): if self.rightChild == None: self.rightChild = BinaryTree(newBranch) else: branch = BinaryTree(newBranch) branch.rightChild = self.rightChild self.rightChild = branch def getLeftChild(self): return self.leftChild def getRightChild(self): return self.rightChild def setRootVal(self,obj): self.key = obj def getRootVal(self): return self.key def __repr__(self): return "current root is: {0} \nthe left child is: {1} \nthe right child is: {2}".format(self.key, self.leftChild, self.rightChild) def __iter__(self): if self != None: yield self.key if self.leftChild != None: for elem in self.leftChild: yield elem if self.rightChild != None: for elem in self.rightChild: yield elem BTree2 = BinaryTree("a") BTree2.insertLeft("b") BTree2.insertRight("c") BTree2.getLeftChild().insertRight("d") BTree2.getRightChild().insertLeft("e") BTree2.getRightChild().insertRight("f") for branch in BTree2: print branch
true
35d14bfa9ce714b65bf4f014cecab4b9be4d5901
linnienaryshkin/python_playground
/src/basics_tkinter.py
1,596
4.28125
4
from tkinter import * # Create an empty Tkinter window window = Tk() def from_kg(): # Get user value from input box and multiply by 1000 to get kilograms gram = float(e2_value.get())*1000 # Get user value from input box and multiply by 2.20462 to get pounds pound = float(e2_value.get())*2.20462 # Get user value from input box and multiply by 35.274 to get ounces ounce = float(e2_value.get())*35.274 # Empty the Text boxes if they had text from the previous use and fill them again # Deletes the content of the Text box from start to END t1.delete("1.0", END) # Fill in the text box with the value of gram variable t1.insert(END, gram) t2.delete("1.0", END) t2.insert(END, pound) t3.delete("1.0", END) t3.insert(END, ounce) # Create a Label widget with "Kg" as label e1 = Label(window, text="Kg") e1.grid(row=0, column=0) # The Label is placed in position 0, 0 in the window e2_value = StringVar() # Create a special StringVar object # Create an Entry box for users to enter the value e2 = Entry(window, textvariable=e2_value) e2.grid(row=0, column=1) # Create a button widget # The from_kg() function is called when the button is pushed b1 = Button(window, text="Convert", command=from_kg) b1.grid(row=0, column=2) # Create three empty text boxes, t1, t2, and t3 t1 = Text(window, height=2, width=20) t1.grid(row=1, column=0) t2 = Text(window, height=2, width=20) t2.grid(row=1, column=1) t3 = Text(window, height=2, width=20) t3.grid(row=1, column=2) # This makes sure to keep the main window open window.mainloop()
true
9c64dee86c030a1784532286137edefaa9a33543
NtateLephadi/csc1015f_assignment_4
/bukiyip.py
761
4.1875
4
# convert a decimal number to bukiyip. def decimal_to_bukiyip(a): bukiyip = '' quotient = 2000000 while quotient > 0: quotient = a // 3 remainder = a % 3 bukiyip += str(remainder) a = quotient return bukiyip[::-1] # convert a bukiyip number to decimal def bukiyip_to_decimal(a): decimal = 0 string_a = str(a) power = 0 for i in string_a[::-1]: decimal += int(i) * pow(3, power) power += 1 return int(decimal) # add two Bukiyip numbers. def bukiyip_add(a, b): return decimal_to_bukiyip(bukiyip_to_decimal(a) + bukiyip_to_decimal(b)) # multiply two Bukiyip numbers. def bukiyip_multiply(a, b): return decimal_to_bukiyip(bukiyip_to_decimal(a) * bukiyip_to_decimal(b))
false
8e526b0f26f52a9b3f606d9ca4e65b85e8ceba4d
pevifol/Lista_de_exercicios
/Lista 1 e 2/Primeiros multiplos de 5 ou 7.py
810
4.3125
4
''' Este programa define uma função chamada primul, que utiliza o parametro x e retorna os primeiros X multiplos de 7, e os primeiros X multiplos de 5, no formato de lista. Em seguida, o programa pergunta educadamente, e executa o primul(x) até o valor digitado. ''' def primul(x): z=x+1 list5=[] list7=[] for p in range(z): q=1 q=5*p m=1 m=7*p if q==0: pass else: list5.append(q) list7.append(m) list5.sort() list7.sort() print('Os primeiros '+str(x)+' multiplos de 5 são:') print(list5) print('Os primeiros '+str(x)+' multiplos de 7 são:') print(list7) def main() q=float(input(Defina até que multiplo de 5 e 7 você deseja saber, por favor.)) primul(q)
false
7580ac5ec609dc67bcd19be51e92dfd3b0c053e2
sajalkuikel/100-Python-Exercises
/Solutions/3.Exercise50-75/68.py
723
4.125
4
# user friendly translator # both earth and EaRtH should display the translation correctly # # d = dict(weather="clima", earth="terra", rain="chuva", sajal= "सजल", kuikel="कुइकेल") # # # def vocabulary(word): # try: # return d[word] # except KeyError: # return "The word doesn't exist in this dictionary" # # # word = input("Enter the word: ").lower() # changes everything entered to lowercase # print(vocabulary(word)) d = dict(weather = "clima", earth = "terra", rain = "chuva") def vocabulary(word): try: return d[word] except KeyError: return "We couldn't find that word!" word = input("Enter word: ").lower() print(word) print(vocabulary(word))
true
3a76f1bbcf4aab994b7fa62a7be456cf5be16957
nazam9519/lists_and_structures
/dlinkedlist/dlinkedlist.py
929
4.125
4
#doubly linked list from linkedlist import double_linkedlist from linkedlist import linkedlist from IData_Structure import stack_i from IData_Structure import queue def main(): stacky = stack_i() stacky.push(1) stacky.push(2) print(stacky.peek()) stacky.pop() print(stacky.peek()) nqueue = queue() print("queue time") nqueue.enQ(1) nqueue.enQ(2) nqueue.print_list() nqueue.deQ() nqueue.print_list() nqueue.enQ(3) nqueue.print_list() return 0 listitem1 = linkedlist() listitem1.delete(1) x = 10 i = 1 # """ while x<=20: # listitem1.insertafter(x) # x+=1 #listitem1.delete(20) #listitem1.printlist() listitem2 = double_linkedlist() listitem2.delete(1) while i<=10: listitem2.insertafter(i) i+=1 listitem2.delete(9) listitem2.printList() if __name__ == "__main__": main()
false
112071c49cbf91b77f12e542f3252a3533b750bb
cadenjohnsen/quickSelectandBinarySearch
/binarySearch.py
2,074
4.375
4
#!/usr/bin/env python3 from random import randint # function to execute the binary search algorithm def binarysearch(num, array): row = 0 # start at the top col = int(len(array[0])) - 1 # start at the far right while((row < int(len(array))) and (col >= 0)): # search from top right to bottom left if (num == array[row][col]): # check if num is at that position return row, col # answer found if (num < array[row][col]): col-=1 # go left else: row+=1 # go down return -10, -10 # return an impossible answer # function to create a randomly sized 2D array in numerical order def createRandomArray(): array = [] # define empty array i, j = 0, 0 k = 0 num = randint(0, 10) # number to be searched for in array m = randint(1,5) # width of array n = randint(1, 5) # length of array rows, cols = (n, m) # set rows and cols values result = -5 # set default as impossible value result2 = -5 # set default as impossible value for i in range(cols): # loop through array adding random values temp = [] # declare temp array for j in range(rows): temp.append(k) # add the new k value into the temp array k += 1 # increment k by 1 array.append(temp) # add the new number onto the final array return num, array # function to call and execute other functions def main(): num, array = createRandomArray() result, result2 = binarysearch(num, array) print ("num:", num) # prints the number being searched for print ("array:", array) # prints the array that was created if ((result >= 0) or (result2 >= 0)): # check if a logical result location was found print ("(",result, ",", result2, ")") # print the location else: # the answer is not possible print ("Not Found") # print that it does not exist # beginning of the program to call main and start execution if __name__ == "__main__": main()
true
dccd11a977c0cffa7796fd48c9ac7b91f4f392c6
theOGcat/lab4Python
/lab9.py
774
4.3125
4
#LorryWei #104952078 #lab9 #Example program that calculate the factorial n! , n! is the product of all positive #integers less than or equal to n #for example, 5! = 5*4*3*2*1 = 120 #The value of 0! is 1 # #PsuedoCode Begin: # #using for loops #for i = 1; i <=n ++1 #factorial *= i #print out the list that from the factorial # #PsuedoCode End. numList = [] f = 1 n = int(input("Please enter a positive integer between 1 and 20: ")) if (n == 0): print("j = ",0,";"," ",0,"! = ",1) numList.append(1) elif (n > 20 or n < 0): print("The number entered is out of range.") exit(0) for j in range(1,n+1): f = f*j numList.append(f) print("j = ",j,";"," ",j,"! = ",f) print("factorial_list = ",numList)
true
c5192b712f8bc5d41532ff4cbdc11407297740ed
theOGcat/lab4Python
/q1.py
1,598
4.34375
4
#LorryWei #104952078 #Assignment3 Question1 #Example of using function randrange(). Simulates roll of two dices. #The random module function are given below. The random module contains some very useful functions #one of them is randrange() #randrange(start,stop) #PsuedoCode Begin: # #import randrange function from random. #define funtion that print out each dice. #in the main function. using randrange(1,7) to simulate giving a random number between 1 and 7 # #PsuedoCode End. from random import randrange import random def numDice(dice): if dice==1: print('+-------+') print('| |') print('| * |') print('| |') print('+-------+') elif dice==2: print('+-------+') print('| * |') print('| |') print('| * |') print('+-------+') elif dice==3: print('+-------+') print('| *|') print('| * |') print('|* |') print('+-------+') elif dice==4: print('+-------+') print('|* *|') print('| |') print('|* *|') print('+-------+') elif dice==5: print('+-------+') print('|* *|') print('| * |') print('|* *|') print('+-------+') elif dice==6: print('+-------+') print('| * * * |') print('| |') print('| * * * |') print('+-------+') for x in range(0,2): dice=random.randrange(1,7) numDice(dice)
true
ea6e3ceef83f99f3a5f5c8c985a07198e7113d6e
Dev-Castro/ALP_FATEC-FRV
/expressoes_aritmeticas/ex002.py
274
4.1875
4
# Expressões Aritméticas ''' 2) Implemente um algoritmo (fluxograma) e o programa em Python que recebe dois números inteiros e mostre o resultado da multiplicação deles ''' n1 = int(input("n1: ")) n2 = int(input("n2: ")) m = n1 * n2 print('Multiplicação: %i' % m)
false
8946f235acdf5e0fa706a826264c799e8a8f6c4b
Rikharthu/Python-Masterclass
/Variables.py
2,123
4.1875
4
greeting = "Hello" Greeting = "Greetings" # case-sensitive name = "Bruce" print(name) name = 5 # not an error print(name) _myName = "Bob" _myName2 = "Jack" # TODO # FIXME age = 21 print(age) # OK # print(greeting+age) #error, age is expected to be a string, since theres no implicit conversion print(greeting + age.__str__()) # OK print("Hello " + str(24)) # Numbers import sys a = 13 print("{0} in binary is {1}, it's size is {2} bytes and type is {3}" .format(a, bin(a), sys.getsizeof(a), type(a))) print("Max int size is {0}".format(sys.maxsize)) b = 3 print(a + b) print(a - b) print(a * b) print(a / b) # returns a float print(a // b) # 4, returns as a whole number print(a % b) # 1, remainder for i in range(1, a // b): print(i) c = a + b d = c / 3 e = d - 4 print(e * 12) print(type(e)) # === Strings === parrot = "Norwegian Blue" print("{0} is a {1}, it's size is {2} bytes, length is {3}" .format(parrot, type(parrot), sys.getsizeof(parrot), parrot.__len__())) # get separate characters at given positions print(parrot) print(parrot[0]) print(parrot[3]) # loop through string's characters for c in parrot: print(c) # negative index start counting in reverse position, starting from the end print(parrot[-1]) # e (Norwegian Blu*e*) print(parrot[-2]) # u (Norwegian Bl*u*e) # get range: print(parrot[0:6]) # Norweg # extract substring starting from #6 til the end of the string print(parrot[6:]) # ian Blue print(parrot[-4:-2]) # Bl # starting from position #0 extract all characters up to an index # non-inclusive # with a step of 2 print(parrot[0:6:2]) # Nre ('N'o'rw'e'g) print(parrot[0:6:3]) number = "9,223,372,036,854,775,807" print(number[1::4]) # ,,,,,, numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9" print(numbers[0::3]) # 123456789 string1 = "he's " string2 = "probably " print(string1 + string2) print("he's probably" + " pining") print("Hello " * 5) # Hello Hello Hello Hello Hello string1 *= 5 print(string1) # he's he's he's he's he's today = "Friday" # check if "Friday" contains a substring "day" print("day" in today) # True print("parrot" in "fjord") # False
true
ba5801191299b1c6c21e2562aeeb081de04507cb
Alex-Iskar/learning_repository
/lesson_3/hw_3_4.py
679
4.4375
4
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y) def my_func_1(arg_x, arg_y): rez = arg_x**arg_y return rez def my_func_2(arg_x, arg_y): rez = 1 for step in range(abs(arg_y)): rez = rez * 1 / arg_x return rez x = int(input("Введите действительное положительное значение переменной x: ")) y = int(input("Введите целое отрицательное значение переменной y: ")) print(my_func_1(x, y)) print(my_func_2(x, y))
false
8e8adfcf5c491b468107c9df4c447bf5109deb39
EvaOEva/python1
/03-可变类型和不可变类型.py
1,426
4.34375
4
# 可变类型:可以在原有数据的基础上对数据进行修改(添加或者删除或者修改数据),修改后内存地址不变 # 不可变类型: 不能在原有数据的基础上对数据进行修改,当然直接赋值一个新值,那么内存地址会发生改变 # 可变类型: 列表,集合,字典,对数据进行修改后内存地址不变 # 不可变类型: 字符串,数字,元组,不能再原有数据的基础上对数据进行修改 my_list = [1, 5, 6] # 查看内存地址 print(my_list, id(my_list)) my_list[0] = 2 my_list.append(7) del my_list[1] print(my_list, id(my_list)) my_dict = {"name": "李四", "age": 10} print(my_dict, id(my_dict)) my_dict["name"] = "王五" my_dict["sex"] = "男" del my_dict["age"] print(my_dict, id(my_dict)) my_set = {5, 10} print(my_set, id(my_set)) my_set.add("666") my_set.remove(5) print(my_set, id(my_set)) # 可变类型: 允许在原有数据的基础上修改的数据,修改后内存地址不变 # ------------不可变类型的操作------------------ my_str = "hello" print(id(my_str)) # my_str[0] = 'a' my_str = "world" print(id(my_str)) my_num = 5 print(id(my_num)) # my_num[0] = 1 my_num = 6 print(id(my_num)) my_tuple = (1, 5) print(id(my_tuple)) # my_tuple[0] = 2 my_tuple = (4, 6) print(id(my_tuple)) # 不可变类型:修改数据内存地址会发生变化, 其实修改的是变量存储的内存地址
false
88d33fb6f7c4026f0efdba747832d154f799220a
EvaOEva/python1
/14-生成器.py
1,055
4.40625
4
# 生成器是一个特殊的迭代器,也就是说它可以通过next函数和for循环取值 # 迭代器和生成器的好处是: 根据需要每次生成一个值,不像列表把所有的数据都准备好,这样列表比较占用内存,而生成器和迭代器内存占用非常少 # 值只能往后面取不能往前面取值 # 1. 使用生成器的表达式 # result = [x for x in range(4)] # print(result, type(result)) result = (x for x in range(4)) print(result) # 测试: 使用next获取下一个值 # value = next(result) # print(value) # for value in result: # print(value) # 2. 使用yield创建生成器 def show_num(): for i in range(5): print("1111") # 代码遇到yield会暂停,然后把结果返回出去,下次启动生成器在暂停的位置继续往下执行 # yield特点: 可以返回多次值,return只能返回一次只 yield i print("2222") g = show_num() value = next(g) print(value) value = next(g) print(value) # for value in g: # print(value)
false
e6fe97b2a4b264dcd8f52461ed0175c72f35a748
EvaOEva/python1
/16-单例.py
569
4.1875
4
# 单例: 在应用程序中不管创建多少次对象只有一个实例对象 class Person(object): # 私有的类属性 __instance = None # 创建对象 def __new__(cls, *args, **kwargs): # if cls.__instance == None: if not cls.__instance: print("创建对象") # 把创建的对象给类属性 cls.__instance = object.__new__(cls) return cls.__instance def __init__(self, name, age): print("初始化") p1 = Person("张三", 20) p2 = Person("李四", 21) print(p1, p2)
false
c15e0bc88eb33491c412f24183dda888e9558c18
realhardik18/minor-projects
/calculator.py
1,663
4.34375
4
print("this is a basic calculator, for help enter '!help'") user_command=input(">") while user_command!="!quit": if user_command=="!help": print("to use the below functions type !start") print("for addition enter a ") print("for multiplying enter m") print("for dividing enter d") print("for subtraction enter s") print("(note:- once you have finshed a calculation, please enter !start to perform another calculation)") print("to quit enter !quit") user_command=input(">") if user_command=="!start": print("now you can perform the calculations!!") user_num_1=float(input("enter the first number here: ")) user_num_2=float(input("enter the second number here:")) user_command=str(input("enter the operation here: ")) if user_command=="a": result=user_num_1+user_num_2 print(f"the sum of {user_num_1} and {user_num_2} is {result}") user_command=input(">") if user_command=="s": result=user_num_1-user_num_2 print(f"when {user_num_2} is subtracted from {user_num_1} the result is {result}") user_command=input(">") if user_command=="m": result=user_num_1*user_num_2 print(f"the product of {user_num_1} and {user_num_2} is {result}") user_command=input(">") if user_command=="d": result=user_num_1/user_num_2 remainder=user_num_1%user_num_2 print(f"when {user_num_1} is divided by {user_num_2} the quotient is {result} and reaminder is {remainder}") user_command=input(">")
true
a193ed75e54ffb9fdd78a93a526f696e2467bae9
deepdatanalytics/ASSIGNMENTS
/00_Ders/060820_OOP1.py
2,953
4.15625
4
# class Employee: # raise_amnt = 1.04 #class attribute oldu. Objeleri de kapsıyor dolayısıyla. # def __init__(self,firstname,lastname,email,pay): # self.firstname = firstname # self.lastname = lastname # self.email = email # self.pay = pay # def fullname(self): # return "{} {}".format(self.firstname, self.lastname) # def apply_raise(self): # self.pay = int(self.pay * self.raise_amnt) # @classmethod # def set_raise_amnt(cls,amount): # cls.raise_amnt = amount # emp_1 = Employee("Martin","Lane","martin.lane@clarus.com",4000) #Instance alma. Yani obje oluşturma. # print(emp_1.firstname) # print(emp_1.lastname) # print(emp_1.email) # print(emp_1.fullname()) # # print(emp_1.raise_amnt) # print(Employee.raise_amnt) # Employee.raise_amnt = 1.06 # print(emp_1.raise_amnt) # print(Employee.raise_amnt) # emp_1.raise_amnt = 1.07 # print(emp_1.raise_amnt) # print(Employee.raise_amnt) #Class Var ve Obj var iki farklı kavram var. # Employee.raise_amnt = 1.08 # print(emp_1.raise_amnt) # print(Employee.raise_amnt) # emp_2 = Employee("Martin2","Lane2","mart@daf.com",5000) # print(emp_1.raise_amnt) # print(emp_2.raise_amnt) # print(Employee.raise_amnt) # print(emp_1.__dict__) # print(emp_2.__dict__) # print(emp_1.pay) # print(emp_2.pay) ### Class Metodlar ve # emp_1 = Employee("Martin","Lane","martin@clarusway.com",4000) # emp_2 = Employee("Martin2","Lane","lane@clarus.com",5000) # Employee.set_raise_amnt(1.10) # print(Employee.raise_amnt) # print(emp_2.raise_amnt) # Employee.raise_amnt = 2 # print(Employee.raise_amnt) # print(emp_2.raise_amnt) class Employee: raise_amnt = 1.04 #class attribute oldu. Objeleri de kapsıyor dolayısıyla. def __init__(self,firstname,lastname,email,pay): self.firstname = firstname self.lastname = lastname self.email = email self.pay = pay def fullname(self): return "{} {}".format(self.firstname, self.lastname) def apply_raise(self): self.pay = int(self.pay * self.raise_amnt) @classmethod def set_raise_amnt(cls,amount): cls.raise_amnt = amount @classmethod def from_string(cls,emp_str): firstname, lastname, email, pay = emp_str.split("-") return cls(firstname, lastname, email, pay) @staticmethod def is_workday(date): if date.weekday() == 5 or date.weekday() == 6: return False else: return True # emp_str_1 = "Martin-Lane-martin@clarus.com-5000" # new_emp_1 = Employee.from_string(emp_str_1) # print(new_emp_1.email) # new_emp_1_1 = Employee(new_emp_1.firstname, new_emp_1.lastname, new_emp_1.email, new_emp_1.pay) # print(new_emp_1_1.email) ######################### STATIC METHOD ################################### import datetime my_date = datetime.date(2020,8,8) print(Employee.is_workday(my_date))
false
2d7854170ec59e5368a1570547a74466e7fec9d3
divu050704/Algo-Questions
/all_negative_elements.py
661
4.28125
4
def move_negative_elements(x): print('Original list:\t',x)#We will first print the original list size = int(len(x))#Length of the list for i in range(0,size): if x[i] < 0:#if x[i] is negative main = x[i]#we will first save the element in variable because we are going to pop the element afterwards x.pop(i)#We will pop the element x.insert(0,main)#and insert it in the first index print('Sorted list:\t',x)#We will print the final list at last l = [2,3,4,-2,-3,-4] move_negative_elements(l) ''' OUTPUT OF THE PROGRAM Original list: [2, 3, 4, -2, -3, -4] Sorted list: [-4, -3, -2, 2, 3, 4] '''
true
480682406029aacf02ab366cab99dbd00034b8e0
sushgandhi/Analyze_Bay_Area_Bike_Share_Data
/dandp0-bikeshareanalysis/summarise_data.py
2,980
4.15625
4
def summarise_data(trip_in, station_data, trip_out): """ This function takes trip and station information and outputs a new data file with a condensed summary of major trip information. The trip_in and station_data arguments will be lists of data files for the trip and station information, respectively, while trip_out specifies the location to which the summarized data will be written. """ # generate dictionary of station - city mapping station_map = create_station_mapping(station_data) with open(trip_out, 'w') as f_out: # set up csv writer object out_colnames = ['duration', 'start_date', 'start_year', 'start_month', 'start_hour', 'weekday', 'start_city', 'end_city', 'subscription_type'] trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames) trip_writer.writeheader() for data_file in trip_in: with open(data_file, 'r') as f_in: # set up csv reader object trip_reader = csv.DictReader(f_in) # collect data from and process each row for row in trip_reader: new_point = {} # convert duration units from seconds to minutes ### Question 3a: Add a mathematical operation below ### ### to convert durations from seconds to minutes. ### new_point['duration'] = float(row['Duration'])/60 # reformat datestrings into multiple columns ### Question 3b: Fill in the blanks below to generate ### ### the expected time values. ### trip_date = datetime.strptime(row['Start Date'], '%m/%d/%Y %H:%M') new_point['start_date'] = trip_date.strftime('%Y-%m-%d') new_point['start_year'] = trip_date.strftime('%Y') new_point['start_month'] = trip_date.strftime('%m') new_point['start_hour'] = trip_date.strftime('%H') new_point['weekday'] = trip_date.strftime('%A') # remap start and end terminal with start and end city new_point['start_city'] = station_map[row['Start Terminal']] new_point['end_city'] = station_map[row['End Terminal']] # two different column names for subscribers depending on file if 'Subscription Type' in row: new_point['subscription_type'] = row['Subscription Type'] else: new_point['subscription_type'] = row['Subscriber Type'] # write the processed information to the output file. trip_writer.writerow(new_point)
true
b3a4a8f603b92c15e59fb7389c2b06ba96c11a7a
sweetpand/Algorithms
/Leetcode/Solutions/math/7. Reverse Integer.py
576
4.1875
4
""" Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ n = x if x > 0 else -x res = 0 while n: res = res * 10 + n % 10 n = n / 10 if res > 0x7fffffff: return 0 return res if x > 0 else -res
true
6eebb728c48a8b14b0875c97c733a1624542fd5d
sweetpand/Algorithms
/Leetcode/Solutions/Longest_Palindrome_Substring.py
1,231
4.1875
4
#Question: Given a string, find the longest palindrome in it #Difficulty: Iterate through each element and determine if its a palindrome #Difficulty: Easy def longestPalindrome(s): #Keep track of largest palindrome found so far gmax = "" #Helper function to find the longest palindrome given a left starting index and a right starting index def checkPal(s, l, r): #As long as l >= 0 and r is less than length of the string and the items at s and l are equal while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1 #Return s[l+1:r] because the while loop will exit after it is done one extra decrement of l, (ie s[l] != s[r] anymore), and up to r because python list slicing goes up to but not including return s[l + 1: r] #For each index in s for i in range(len(s)): #Check the palindrome as an odd palindrome, so where both l and r are equal, and as an even length palindrome o, e = checkPal(s, i, i), checkPal(s, i, i + 1) #Set gmax to the longest palindrome found if len(o) > len(gmax): gmax = o if len(e) > len(gmax): gmax = e return gmax
true
13ada5c6d5e949bac39b65e40dded49cbd61e802
dillon4287/CodeProjects
/Python/Coding Practice/linked_list/linked_list.py
1,061
4.15625
4
class Node: def __init__(self, data) -> None: self.value = data self.Next = None class linked_list: def __init__(self) -> None: self.head = None def addLast(self, data): if(self.head is None): self.head = Node(data) else: root = self.head while(root.Next is not None): root = root.Next root.Next = Node(data) def insert(self, data): if(self.head == None): print("is none ") self.head = Node(data) else: h = self.head while(h.Next is not None): h = h.Next h.Next = Node(data) def reverse(self): last = None cur = self.head while(cur is not None): temp = cur.Next cur.Next = last last = cur cur = temp self.head = last def printList(self): root = self.head while(root is not None): print(root.value) root = root.Next
true
9b80e28d7892712937b7b010f9798f5a974a861b
hyeonukjeong/Algorithm
/kr/hs/dgsw/nyup/part01/design01/basic.py
395
4.1875
4
''' 1. 곱하기와 나누기 ''' print (3 * 2) print (3 / 2) print (3 ** 4) ''' 2. 할당문 ''' a = 1 b = 2 print (a + b) ''' 3. 문자 ''' c = "You need " d = 'Python.' print (c + d) ''' 4. 조건문 ''' e = 5 if e > 3: print ("e는 3보다 크다.") ''' 5. 반복문 ''' for f in [1, 3, 7]: print (f) ''' 6. 함수 ''' def add (g, h): return (g + h) print (add (3, 5))
false
51dda073f8280d086e89356b67ee4aa0779f30a7
ator89/Python
/MITx_Python/week2/week2_exe3_guessMyNumber.py
1,217
4.125
4
import random secret = int(input("Please think of a number between 0 and 100!")) n = random.randint(0,100) low = 0 high = 100 while n != secret: print("Is your secret number " + str(n) + "?") option = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if option == 'h': high = n elif option == 'l': low = n elif option == 'c': print("Game over. Your secret number was:", n) else: print("Invalid option, try again") n = random.randint(low,high) low = 0 high = 100 ans = int((high + low) / 2) guess = False print('Please think of a number between 0 and 100!') while guess != True: print("Is your secret number " + str(ans) + "?") option = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if option == 'h': high = ans elif option == 'l': low = ans elif option == 'c': print("Game over. Your secret number was:", ans) guess = True else: print("Invalid option, try again") ans = int((high + low) / 2)
true
1b1fe1a95570be4c2444f919cbf5b4eab9a1bd8b
harshithamagani/python_stack
/python/fundamentals/hello_world.py
808
4.46875
4
print("Hello World!") x = "Hello Python" print(x) y = 42 print(y) name = "Zen" print("My name is", name) name = "Zen" print("My name is " + name) #F-Strings (Literal String Interpolation) first_name="Zen" last_name="Coder" age=27 print(f"My name is {first_name} {last_name} and I am {age} years old.") #string.format() print("My name is {} {} and I am {} year old.".format(first_name,last_name,age)) print ("My name is {} {} and I am {} years old.".format(age,first_name,last_name)) #%-formatting hw = "Hello %s" % "world" # with literal values py = "I love Python %d" % 3 print(hw, py) # output: Hello world I love Python 3 name = "Zen" age = 27 print("My name is %s and I'm %d" % (name, age)) # or with variables # output: My name is Zen and I'm 27 x = "hello world" print(x.title())
true
1e7f9513f24543c2d3248a8c066300f033c6ba78
harshithamagani/python_stack
/python/fundamentals/Function_Basic_II/valsGreatThanSecnd.py
753
4.375
4
#Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False #Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] #Example: values_greater_than_second([3]) should return False def values_greater_than_second(list): newList = [] if len(list) <= 2: return False secVal = list[1] for item in list: # TODO: write code... if item > secVal: newList.append(item) print(len(newList)); return newList print(values_greater_than_second([1,2,3,4,5]))
true
9444dff462f8659dd24b92f896d5e4726f72cd93
Anju3245/Sample-example
/ex66.py
393
4.1875
4
print("enter number frist:") frist = input() print("enter second number:") second = input() print("enter third number:") third = input() if frist > second: if frist > third: print(f"{frist} is the largest") else: print(f"{third} is the largest ") else: if second > third: print(f"{second} the largest") else: print(f"{third} is the largest ")
true
3c083f3459f90d53a318a1f3528a0349aa77b509
thegr8kabeer/Current-Date-And-Time-Shower-Python
/current _date_and_time.py
635
4.1875
4
# A simple python project made by Thegr8kabeer to display the current date and time # Easy to understand syntax for the person who knows the basics of Python by using the built-in Pyhton modules time and datetime # Feel free to edit my code and do some experiments!!! # Don't forget to follow me on instagram at https://instagram.com/thegr8kabeer/ import time,datetime epochseconds = time.time() print(epochseconds) t = time.ctime(epochseconds) print(t) dt = datetime.datetime.today() print('Current Date: {}/{}/{}'.format(dt.day,dt.month,dt.year)) print('Current Time: {}:{}:{}'.format(dt.hour,dt.minute,dt.second))
true
f86d1082e54213ae28e0f7d67e235a45aa8bb441
jatindergit/python-programs
/is-prime.py
394
4.21875
4
number = int(input('Enter any integer')) def is_prime(n): if n == 1: prime = False elif n == 2: prime = True else: prime = True for check_number in range(2, int(n/2) - 1): if n % check_number == 0: prime = False return prime if is_prime(number): print('Number is prime') else: print("Number is not prime")
false
e30351f4fb9d2a579809bca75303940edd726416
beenorgone-notebook/python-notebook
/py-book/py-book-dive_into_py3/examples/roman3.py
2,328
4.125
4
'''Convert to and from Roman numerals This program is part of 'Dive Into Python 3', a free Python book for experienced programmers. Visit http://diveintopython3.org/ for the latest version. ''' roman_numeral_map = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) def to_roman(n): '''convert integer to Roman numeral''' if not (0 < n < 4000): raise OutOfRangeError('number out of range (must be 1...3999)') result = '' for numeral, integer in roman_numeral_map: while n >= integer: result += numeral n -= integer return result class OutOfRangeError(ValueError): pass # Copyright (c) 2009, Mark Pilgrim, All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.
true
7e389217ee1a884961db1858d48fcd11f2ae42a6
beenorgone-notebook/python-notebook
/py-recipes/use_translate_solve_alphametics.py
2,039
4.15625
4
def alphametics(puzzle): ''' Solve alphametics puzzle: HAWAII + IDAHO + IOWA + OHIO == STATES 510199 + 98153 + 9301 + 3593 == 621246 The letters spell out actual words, but if you replace each letter with a digit from 0–9, it also “spells” an arithmetic equation. The trick is to figure out which letter maps to each digit. All the occurrences of each letter must map to the same digit, no digit can be repeated, and no “word” can start with the digit 0. ''' from re import findall from itertools import permutations # Get all characters in puzzle words = findall('[A-Z]+', puzzle.upper()) unique_chars = set(''.join(words)) # Check if characters in use is less than 10 or not number_of_chars = len(unique_chars) number_of_digits = 10 assert number_of_chars <= number_of_digits, 'Too many letters.' # get 1st character of each "word" first_letters = {w[0] for w in words} # Create sorted_chars in which first_chars is in head part. sorted_chars = ''.join(first_letters) + \ ''.join(unique_chars - first_letters) n = len(first_letters) # Loop throw permutations of 10 digits 0-9 and # create an arithmetic equation. Check if equation is True. chars = tuple(ord(c) for c in sorted_chars) digits = tuple(ord(c) for c in '0123456789') # We need ord() because translate() only works with ordinals. zero = digits[0] for guess in permutations(digits, number_of_chars): if zero not in guess[:n]: equation = puzzle.translate(dict(zip(chars, guess))) if eval(equation): return equation if __name__ == '__main__': import sys for puzzle in sys.argv[1:]: print(puzzle) solution = solve(puzzle) if solution: print(solution) puzzles = ['HAWAII + IDAHO + IOWA + OHIO == STATES', 'SEND + MORE == MONEY', 'PIG + FOX == LOVE', 'LEO + CRIS == INVISIBLES'] for p in puzzles: print(alphametics(p))
true
c6f454afce86b20fd2be8c3fd955f810ef5a0d27
DscAuca/into-to-python
/src/intro/string.py
2,597
4.125
4
print("hello world") print('hello world') print('"i think you\'re aweosme tho"') print('this is "going to work" as i said') name='salvi' print('welcome '+ name +' you\'re awesome') print(3*('i repeat you\'re awesome ')) print(len('aesome shit')/len(name)) print(name[0]) # Quiz: Fix the Quote # The line of code in the following quiz will cause a SyntaxError, thanks to the misuse of quotation marks. First run it with Test Run to view the error message. Then resolve the problem so that the quote (from Henry Ford) is correctly assigned to the variable ford_quote. # TODO: Fix this string! ford_quote = 'Whether you think you can, or you think you can't--you're right.' # We’ve already seen that the type of objects will affect how operators work on them. What will be the output of this code? coconut_count = "34" mango_count = "15" tropical_fruit_count = coconut_count + mango_count print(tropical_fruit_count) # Quiz: Write a Server Log Message # In this programming quiz, you’re going to use what you’ve learned about strings to write a logging message for a server. # You’ll be provided with example data for a user, the time of their visit and the site they accessed. You should use the variables provided and the techniques you’ve learned to print a log message like this one (with the username, url, and timestamp replaced with values from the appropriate variables): # Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20. # Use the Test Run button to see your results as you work on coding this piece by piece. username = "Kinari" timestamp = "04:50" url = "http://petshop.com/pets/mammals/cats" # TODO: print a log message using the variables above. # The message should have the same format as this one: # "Yogesh accessed the site http://petshop.com/pets/reptiles/pythons at 16:20." # Quiz: len() # Use string concatenation and the len() function to find the length of a certain movie star's actual full name. Store that length in the name_length variable. Don't forget that there are spaces in between the different parts of a name! given_name = "William" middle_names = "Bradley" family_name = "Pitt" name_length = #todo: calculate how long this name is # Now we check to make sure that the name fits within the driving license character limit # Nothing you need to do here driving_license_character_limit = 28 print(name_length <= driving_license_character_limit) # We've just used the len function to find the length of strings. What does the len function return when we give it the integer 835 instead of a string? #835 #error #3
true
209e2d4a62767c2e446e9e53eaf1af476467d63d
DscAuca/into-to-python
/src/data structure/compound_datatype.py
1,772
4.625
5
elements = {"hydrogen": {"number": 1, "weight": 1.00794, "symbol": "H"}, "helium": {"number": 2, "weight": 4.002602, "symbol": "He"}} helium = elements["helium"] # get the helium dictionary hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight oxygen = {"number":8,"weight":15.999,"symbol":"O"} # create a new oxygen dictionary elements["oxygen"] = oxygen # assign 'oxygen' as a key to the elements dictionary print('elements = ', elements) #This is how I added values to the elements dict. The syntax for adding elements to nested data structures is about the same as it is for reading from them. elements['hydrogen']['is_noble_gas'] = False elements['helium']['is_noble_gas'] = True #List are sortable, you can add an item to a list with .append and list items are always indexed with numbers starting at 0. #Sets are not ordered, so the order in which items appear can be inconsistent and you add items to sets with .add. Like dictionaries and lists, sets are mutable. # You cannot have the same item twice and you cannot sort sets. For these two properties a list would be more appropriate #Each item in a dictionary contains two parts (a key and a value), the items in a dictionary are not ordered, and we have seen in this lesson examples of nested dictionaries. #Because dictionaries are not ordered, they are not sortable. And you do not add items to a dictionary with .append. elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}} elements['hydrogen']['is_noble_gas'] = False elements['helium']['is_noble_gas'] = True
true
b9b9661b9bb7997c0121d7bc378ad1045abfcd99
VMGranite/CTCI
/02 Chapter - Linked Lists in Python/2_4_Partition.py
798
4.4375
4
#!/usr/bin/env python3 # 1/--/2020 # Cracking the Coding Interview Question 2.4 (Linked Lists) # Partition: Write code to partition a linked list around a value x, # such that all nodes less than x come before all node greater than # or equal to x. If x is contained within the list, the values # of x only need to be after the elements less than x (see below). # The partition element x can appear anywhere in the "right partition" # it does not need to appear between the left and right partitions # EXAMPLE: # Input: 3 > 5 > 8 > 5 > 10 > 2 > 1 [Partition 5] # Output: 3 > 1 > 2 > 10 > 5 > 5 > 8 import Linked_List my_list = Linked_List.linked_list() my_list.append(3) my_list.append(5) my_list.append(8) my_list.append(5) my_list.append(10) my_list.append(2) my_list.append(1) my_list.display()
true
6292be73038d38e901f1f978c2e64daadcd73922
paramjeetsingh31/paramcmru
/programe 11.py
507
4.46875
4
# Python program to illustrate # Iterating over a list print("python") l = ["param", "jeet", "singh"] for i in l: print(i) # Iterating over a tuple (immutable) print("\nTuple python") t = ("param", "jeet", "singh") for i in t: print(i) # Iterating over a String print("\nString python") s = "param" for i in s : print(i) # Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i]))
false
4006054a3e31786ea7b93aa99cc2be4a305f5949
candytale55/Copeland_Password_Username_Generators
/username_password_generators_slice_n_shift.py
1,429
4.21875
4
# username_generator take two inputs, first_name and last_name and returns a username. The username should be # a slice of the first three letters of their first name and the first four letters of their last name. # If their first name is less than three letters or their last name is less than four letters it should use their entire names. def username_generator(first_name, last_name): if len(first_name)>=3 and (len(last_name)>=4): username = first_name[:3] + last_name[:4] elif (len(first_name)<3) and (len(last_name)>=4): username = first_name + last_name[:4] else: username = first_name + last_name return username # TESTS: print(username_generator("Abe", "Simpson")) # AbeSimp print(username_generator("Homer", "Simpson")) # HomSimp print(username_generator("Ty", "Johnson")) # TyJohn print(username_generator("Ty", "Chi")) # TyChi print(username_generator("Mi", "Li")) # MiLi # For the temporary password, they want the function to take the input user name and shift all of the letters # by one to the right, so the last letter of the username ends up as the first letter. # If the username is AbeSimp, then the temporary password generated should be pAbeSim. def password_generator(username): return username[-1] + username[0:len(username)-1] username = username_generator("Abe", "Simpson") print(username) # AbeSimp password = password_generator(username) print(password) # pAbeSim
true
a9fe4064f0aa9a13bc6afcfec7b666f3977ff9e9
mjdecker-teaching/mdecke-1300
/notes/python/while.py
1,958
4.28125
4
## # @file while.py # # While-statement in Python based on: https://docs.python.org/3/tutorial # # @author Michael John Decker, Ph.D. # #while condition : # (tabbed) statements # condition: C style boolean operators # tabbed: space is significant. # * Avoid mixing tabs and spaces, Python relies on correct position # and mixing may leave things that look indented correctly, but are not # * http://www.emacswiki.org/emacs/TabsAreEvil # # How might you compute fibonacci (while number is less than 10)? last = 0 current = 1 while last < 10 : print(last) temp = current current = last + current last = temp # Python improvement 1) multiple assignment # first is in C++, other is not last, current = 0, 1 while last < 10 : # need to indent print(last) # no temp!!! All, rhs is evaluated before any actual assignment last, current = current, last + current # conditions # * boolean: True, False while True : print('Do not do this: ^C to stop') while False : print('Never executed') # * integer: 0 False, True otherwise count = 10; while count : print(count) count -= 1 # * sequence: len() == 0 False, True otherwise sequence = ['bar', 'foo'] while sequence : print(sequence[-1]) tos = sequence.pop() # Python supports usually comparisons and # 'and', 'or' and 'not'(C++ has these, but have different precedence) # https://docs.python.org/3/library/stdtypes.html # notice that ! is not suppported. Python 2 had <> as well (!=) # conditions can be chained (but are ands) x = 1 y = 2 z = 3 x < y <= z # print is a bit ugly... # Here is simple print usage: Multiple arguments are handled # They are space separated, no quotes for strings, and ending in a newline print("256 ** 2:", 256 ** 2) last, current = 0, 1 while last < 10 : # We can specifiy the end character (this is a keyword argument, more when we see functions) print(last, end=',') last, current = current, last + current
true
b47f30bb8fcea15b3b08ec5cf0cd32412ec2b652
sdesai8/pharmacy_counting
/src/helper_functions.py
2,962
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 00:17:08 2019 @author: savan """ from decimal import Decimal def isPositiveDecimal(number): """ To validate if value is positive decimal number Parameters: arg1 (string): like example: prescriber_id/drug_cost Returns: Decimal: Return Updated decimal value otherwise False """ try: tmp = float(number) #print("number : " + str(number)) if tmp >= 0: return Decimal(number) except ValueError: return False except TypeError: return False return False def isValidationTrue(data): """ To validate the data Parameters: arg1 (list): [prescriber_id, prescriber_first_name, prescriber_last_name, drug_name, drug_cost] Returns: list: Return Updated fields with True otherwise False """ #length of data item must be 5 as mention in description if (len(data) != 5): return False if (data is None): return False pres_id = isPositiveDecimal(data[0]) drug_cost = isPositiveDecimal(data[-1]) #print("pres_id: " + str(pres_id) + "and drug_cost: " +str(drug_cost)) if (pres_id is not False and drug_cost is not False): data[0] = pres_id data[-1] = drug_cost try: data[3] = data[3].replace('-', ' ') except AttributeError: return False else: return False return data def insertDataItem(data, drugs): """ Insert data item in drugs dictionary where drug_name is key with dictionary of Unique prescriber_id's and total cost as a value. Parameters: arg1 (list): [prescriber_id, prescriber_first_name, prescriber_last_name, drug_name, drug_cost] arg2 (dict): Dictionary of data items Returns: dict: Dictionary with inserted/updated data items. """ if isValidationTrue(data): #print("Data item is valid!") dic_to_be_inserted = {} if (data[3] in drugs): dic_to_be_inserted = drugs[data[3]] if (data[0] not in dic_to_be_inserted): dic_to_be_inserted[data[0]] = True dic_to_be_inserted['drug_cost'] += data[-1] else: drugs[data[3]] = dic_to_be_inserted dic_to_be_inserted[data[0]] = True dic_to_be_inserted['drug_cost'] = data[-1] else: print("Data item " + str(data) +" is not valid to be insrted in to drugs dictionary") return False return True
true
883db011c2393aec6b1ee725ac2eeba0e356d8cb
xubonnie/ICS4U
/Modular Programming/scope.py
468
4.125
4
__author__ = 'eric' import math def distance(x1, y1, x2, y2): d = math.sqrt((x2-x1)**2 + (y2-y1)**2) return d def main(): x_1 =input("Enter an x-value for the first point: ") y_1 =input("Enter an y-value for the first point: ") x_2 = input("Enter an x-value for the second point: ") y_2 = input("Enter an y-value for the second point: ") dist = distance(x_1, y_1, x_2, y_2) print "The distance between the points is", dist main()
true
2ad269ec438578eb8d482e862b0477df3ec346cf
alextrujillo4/EZ-PZ-language
/semantic_cube.py
1,990
4.15625
4
# Oscar Guevara A01825177 # Gerardo Ponce A00818934 # Listas de operadores. operators = ['+', '-', '*', '/'] comparators = ['==', '>', '>=', '<', '<=', '<>'] # Verificar el tipo de resultado de una expresión. def semantic(left, right, operator): if(left == 'int'): if(right == 'int'): if(operator in operators or operator == '='): return 'int' elif(operator in comparators): return 'bool' else: return 'error' elif(right == 'float'): if(operator in operators): return 'float' elif(operator in comparators): return 'bool' else: return 'error' else: return 'error' elif(left == 'float'): if(right == 'float'): if(operator in operators or operator == '='): return 'float' elif(operator in comparators): return 'bool' else: return 'error' elif(right == 'int'): if(operator in operators): return 'float' elif(operator in comparators): return 'bool' else: return 'error' else: return 'error' elif(left == 'string'): if(right == 'string'): if(operator == '=' or operator == '+'): return 'string' elif(operator == '==' or operator == '<>'): return 'bool' else: return 'error' else: return 'error' elif(left == 'bool'): if(right == 'bool'): if(operator == '=' or operator == '==' or operator == '<>'): return 'bool' elif(operator == 'and' or operator == 'or'): return 'bool' else: return 'error' else: return 'error' else: return 'error'
false
c2f444f85f06775591739985f9c60f745927dad7
cynen/PythonStudy
/03-DataStructure/Queue.py
1,339
4.125
4
#coding=utf-8 class Queue(object): def __init__(self): self.__items=[] def enqueue(self,item): '''往队列中添加一个item元素''' self.__items.insert(0,item) #self.__items.append(item) def dequeue(self): '''从队列头部删除一个元素''' if self.size(): return self.__items.pop() # 弹出第一个元素. #return self.__items.pop(0) # 弹出第一个元素. else: return None; def is_empty(self): '''判断一个队列是否为空''' #return self.__items == [] return not self.__items def size(self): '''返回队列的大小''' return len(self.__items) if __name__=="__main__": q = Queue() print(q.size()) print(q.is_empty()) q.dequeue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print(q.size()) print(q.is_empty()) q.dequeue() q.dequeue() q.dequeue() q.dequeue() print(q.is_empty()) """ def enqueue(self,item): '''往队列中添加一个item元素''' self.__items.append(item) def dequeue(self): '''从队列头部删除一个元素''' if self.size(): return self.__items.pop(0) # 弹出第一个元素. else: return; """
false