blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b8bd7096aa800ba40dfd70bdcb94e63c47b78043
niranjan2822/Interview1
/program to print odd numbers in a List.py
1,328
4.53125
5
# program to print odd numbers in a List ''' Example: Input: list1 = [2, 7, 5, 64, 14] Output: [7, 5] Input: list2 = [12, 14, 95, 3, 73] Output: [95, 3, 73] ''' # Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. # If the condition satisfies, then only print the number. # Python program to print odd Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list for num in list1: # checking condition if num % 2 != 0: print(num, end=" ") # output : 21 45 93 # Using while loop : # Python program to print odd Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] i = 0 # using while loop while (i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end=" ") # increment i i += 1 # Using list comprehension : # Python program to print odd Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd) # Using lambda expressions # Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos)
true
8a0fcc9d999434e6952ca9bb6c5d2d2f2ca36e6c
niranjan2822/Interview1
/Uncommon elements in Lists of List.py
2,104
4.5
4
# Uncommon elements in Lists of List ''' Input: The original list 1 : [[1, 2], [3, 4], [5, 6]] output : [[3, 4], [5, 7], [1, 2]] # The uncommon of two lists is : [[5, 6], [5, 7]] ''' # Method 1 : Naive Method # This is the simplest method to achieve this task and uses the brute force approach of executing a loop and to check # if one list contains similar list as of the other list, not including that. # using naive method # initializing lists test_list1 = [[1, 2], [3, 4], [5, 6]] test_list2 = [[3, 4], [5, 7], [1, 2]] # printing both lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # using naive method # Uncommon elements in List res_list = [] for i in test_list1: if i not in test_list2: res_list.append(i) for i in test_list2: if i not in test_list1: res_list.append(i) # printing the uncommon print("The uncommon of two lists is : " + str(res_list)) # OUTPUT : The original list 1 : [[1, 2], [3, 4], [5, 6]] # The original list 2 : [[3, 4], [5, 7], [1, 2]] # The uncommon of two lists is : [[5, 6], [5, 7]] # Method 2 : Using set() + map() and ^ # The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. # Firstly converting inner lists to tuples using map, and outer lists to set, # use of ^ operator can perform the set symmetic difference and hence perform this task. # Further if it is required to get in lists of list fashion, we can convert outer and inner containers back to list using map(). # Uncommon elements in Lists of List # using map() + set() + ^ # initializing lists test_list1 = [[1, 2], [3, 4], [5, 6]] test_list2 = [[3, 4], [5, 7], [1, 2]] # printing both lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # using map() + set() + ^ # Uncommon elements in Lists of List res_set = set(map(tuple, test_list1)) ^ set(map(tuple, test_list2)) res_list = list(map(list, res_set)) # printing the uncommon print("The uncommon of two lists is : " + str(res_list))
true
6fc03e029814d1e7f48e0c65921d19a276c15b06
CHilke1/Tasks-11-3-2015
/Fibonacci2.py
586
4.125
4
class Fibonacci(object): def __init__(self, start, max): self.start = start self.max = max def fibonacci(self, max): if max == 0 or max == 1: return max else: return self.fibonacci(max - 1) + self.fibonacci(max - 2) def printfib(self, start, max): for i in range(start, max): print("Fibonacci of %d %d: " % (i, self.fibonacci(i))) while True: start = int(input("enter start : ")) max = int(input("Enter maximum: ")) myfib = Fibonacci(start, max) myfib.printfib(start, max) quit = input("Run again?Y/N: ") if quit == "N" or quit == "n": break
true
e0ec66c76e6f734caf5262867aac6245414ba8e9
bvo773/PythonFun
/tutorialspy/basic/listPy.py
557
4.40625
4
# (Datatype) List - A container that stores ordered sequence of objects(values). Can be modified. # listName = [object1, object2, object3] def printFruits(fruits): for fruit in fruits: print(fruit) print("\n") fruits = ["Apple", "Orange", "Strawberry"] fruits[0] #Accessing a list fruits[1] = "Mango" #Modifying a list fruits.append("Kiwi") #Adding an element the 'end' of the list fruits.insert(1,"Banana") # Insert an element at certain index fruits.remove("Strawberry") printFruits(fruits) fruits.sort() printFruits(fruits)
true
6dfc3a9d06ee4401a3d78ddb27e8bacd01884138
rwankurnia/fundamental-python
/Dictionary/dictionary.py
2,195
4.15625
4
# # DICTIONARY # # Menggunakan kurung kurawal {} # # Tidak menggunakan index, melainkan property # # Nama property ditulis menggunakan kutip (seperti string) # price = { # "apple" : 10000, # "grape" : 15000, # "orange" : 15000 # } # price["grape"] // 15000 # print(price["grape"]) ## 15000 # ================================ # d = { # "numInt" : 123, # "numList" : [0, 1, 2], # "numStr" : "Hello", # "numDict" : {"insideKey" : 100} # } # print(d["numList"]) ## [0, 1, 2] # print(d["numDict"]) ## {'insideKey': 100} # print(d["numDict"]["insideKey"]) ## 100 # print(d["numList"][2]) ## 2 # # ================================= heroes = { "batman" : {"name" : "Bruce", "age" : 41}, "ironman" : {"name" : "Tony", "age" : 42}, "thor" : {"name" : "Thor", "age" : 39} } # heroes["ironman"] # heroes["ironman"]["name"] # KEYS # Untuk mendapatkan semua keys dari dictionary keys = heroes.keys() # keys # dict_keys("batman", "ironman", "thor") for i in keys: print(i) # #============================================= # # VALUES # # Untuk mendapatkan semua value dari dictionary # heroes = { # "batman" : {"name" : "Bruce", "age" : 41}, # "ironman" : {"name" : "Tony", "age" : 42}, # "thor" : {"name" : "Thor", "age" : 39} # } # values = heroes.values() # # i = ("name" : "Bruce", "age" : 41) # for i in values: # print( # "Name: " + i["name"] # ) #========================== # # TUPLE # # Mengunakan kurung () # # Mengenal indexing, dimulai dari 0 # # Nilainya tidak dapat dirubah # colorTpl = ("red", "green", "blue", "green", "blue") # colorTpl[1] # Green # colorTpl[-1] # Blue # # Error, tidak bisa merubah nilai tuple # # colorTpl[0] = "Merah" # # Count # # Menghitung banyak data pada tuple # count = colorTpl.count("green") #2 # print(f"Jumlah warna hijau : {count}") # # Index # # Mencari index data tertentu # index = colorTpl.index("blue") # print(f"Index warna blue : {index}") # Persons # persons = ( # {"name" : "John", "job" : "Assassins"}, # {"name" : "Bruce", "job" : "Hunter"}, # {"name" : "Jajang", "job" : "OB"} # ) # persons[1]["name"] = "BruceLee" # print(persons[1])
false
2e21c5f9cde84b02370c12f0c17daa41d5c56b10
sseun07/pythonBasic
/Lecture3.py
1,369
4.71875
5
''' Where do you use for-loop? RANGE-함수 - range(a,b) *a is optional (is inclusive) // a 보다 크거나 같고, b 보다는 작은것 - create list ''' for each in range(16,25): print(each) l=[1,2,3,7,10,20,35] print(l[0]) for each in range(len(l)): print(l[each]) ''' len=length of the list ''' ''' NEGATIVE INDEX l[-1] : 뒤에서 첫번째 l[-2] : 뒤에서 두번째 print(l[-1]) ''' #HW: for loop 은 어디에 쓰는지 RESEARCH by (2021.06.24 7pm) #used to iterate over a sequence (either list, tuple, dictionary, set, or string). #for loop allows to sort list like/such as [0,5,4,2] >> [0,2,4,5] #2D List: l=[[1,2,3],[4,5,6]] **list 안에 list #3D List: l=[[1,2,3],[4,5,6,[7,8]]] #4D List: l=[[1,2,3],[[[4,5]]]] >> 이렇게 멀리까지 가면 속도가 느려짐 #for loop 을 Range 1=한번 돌린다 면 괜찮음 ''' l=[[1,2,3],[4,5,6]] for each in l: for number in each: print(number) = 1,2,3,4,5,6 l=[[1,2,3],[4,5,6]] print(l[0][0]) = 1 (index) ''' l=[[1,2,3],[4,5,6]] #2x3 print(l[0]) for each in range(len(l)): for number in range(len(l[each])): print(l[each][number]) #But what if the list was: [1,2,3], [4,5,6,7] >> there are list like this but bit difficult to use as above for loop #HW: Frequency that our eye perceives // Need to create and explain about "sorting algorithm using for loop"
false
575a0095523dd275b7e6a5f89266f4feae0afdbb
UCD-pbio-rclub/Pithon_JohnD
/July_18_2018/Problem_1.py
803
4.125
4
# Problem 1 # Write a function that reports the number of sequences in a fasta file import string import re import glob def fastaCount(): files = glob.glob('*') filename = input('Enter the name of the fasta file if unsure, enter ls for \ current directory listings: ') if filename == 'ls': for i in files: print(i) filename = input('Enter the name of the fasta file: ') if filename in files: with open(filename, 'r') as f: count = 0 line = f.readline() while line != '': if line.startswith('>'): count += 1 line = f.readline() print('There are', count, 'fasta records in', filename) else: print('File could not be found')
true
4cae14c7bc79058cc405ab09c1d622b1e07e2f2a
reginald1992/PythonFoundation
/PythonBasis/FunctionalProgrammingPartialFunction.py
1,316
4.46875
4
""" 偏函数--functools.partial的作用:把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。 """ import functools print(int('123456')) print(int('123456', base=8)) print(int('123456', 16)) print(int('101001', 2)) def int2(x, base=2): return int(x, base) print(int2('100000')) print(int2('101010101')) ''' functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int2: ''' int8 = functools.partial(int, base=8) print(int8('1234567')) print(int8('123623541237')) ''' 注意到上面的这个int8函数,仅仅是把base的默认值设定成了8,但是在调用函数时候还是可以传入别的数值 ''' print(int8('121212356', base=16)) ''' 最后,创建偏函数时,实际上可以接收函数对象、*args、**kw这三个参数,当传入int6 = functools.partial(int, base=6), 实际上固定了int()函数的关键字base,也就是: ''' int6 = functools.partial(int, base=6) # 相当于 kw = {'base': 2} int('121212356', **kw) # 当传入 max2 = functools.partial(max, 10) # 实际上会把10作为*args的一部分自动加到左边 max2(5, 6, 7) # 相当于 args = (10, 5, 6, 7) max(*args)
false
402fbd754c53584ec8400f07a3c697f5c07e1b94
Atul-Bhatt/Advanced-Python
/itertools.py
1,304
4.28125
4
# advanced iterator functions in ther itertools package import itertools def testFunction(x): if x > 40: return False return True def main(): # TODO: cycle iterator can be used to cycle over a collection names = ["John", "Casey", "Nile"] cycle_names = itertools.cycle(names) print(next(cycle_names)) print(next(cycle_names)) print(next(cycle_names)) print(next(cycle_names)) # TODO: use count to create a simple counter count = itertools.count(100, 10) print(next(count)) print(next(count)) print(next(count)) # TODO: accumulate creates an iterator that accumulate values values = [10, 70, 34, 23, 50, 12, 11] print(list(itertools.accumulate(values))) print(list(itertools.accumulate(values, max))) # TODO: use chain to connect sequences together letters = "ABCDEF" byte_values = [0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x33, 0x34, 0x12, 0x55] print(list(itertools.chain(values, letters, byte_values))) # TODO: dropwhile and takewhile will return values until a certain # condition is met that stops them print(list(itertools.dropwhile(testFunction, values))) print(list(itertools.takewhile(testFunction, values))) if __name__ == '__main__': main()
true
0a2ec74b681d34d78fff26dad5ee7599e538e590
weida8/Practice
/TreeConvert.py
2,460
4.15625
4
# File: TreeConvert.py # Description: HW 9 # Student's Name: Wei-Da Pan # Student's UT EID: wp3479 # Course Name: CS 313E # Unique Number: 50595 # # Date Created: 11/19/15 # Date Last Modified: 11/20/15 #class that create a binary tree class BinaryTree(object): def __init__(self, initVal): self.data = initVal self.left = None self.right = None def getLeftChild(self): return self.left def getRightChild(self): return self.right def setRootVal(self, value): self.data = value def getRootVal(self): return(self.data) def insertLeft(self, newVal): n = BinaryTree(newVal) n.left = self.left self.left = n def insertRight(self, newVal): n = BinaryTree(newVal) n.right = self.right self.right = n #staticmethod is needed that in order to make sure #that it not the first argument taken in @staticmethod def convert(pyList): if(pyList == []): return(None) else: #recursively converting the list into the binary tree newTree = BinaryTree(pyList[0]) newTree.left=BinaryTree.convert(pyList[1]) newTree.right=BinaryTree.convert(pyList[2]) return(newTree) @staticmethod #reordering the list into and printing it out in inorder order def inorder(tree): if(tree != None): BinaryTree.inorder(tree.getLeftChild()) print(tree.getRootVal(), end = " ") BinaryTree.inorder(tree.getRightChild()) #reordering the list into and printing it out in preorder order @staticmethod def preorder(tree): if(tree): print(tree.getRootVal(), end = " ") BinaryTree.preorder(tree.getLeftChild()) BinaryTree.preorder(tree.getRightChild()) #reordering the list into and printing it out in postorder order @staticmethod def postorder(tree): if(tree != None): BinaryTree.postorder(tree.getLeftChild()) BinaryTree.postorder(tree.getRightChild()) print(tree.getRootVal(), end = " ") def __str__(self): return(str(self.data)) def main(): #take in line to line and calling each order method to print it out inFile = open("treedata.txt", "r") for line in inFile: newList = eval(line) print("\nlist: " + str(newList)) newTree = BinaryTree.convert(newList) print("inorder: " ) BinaryTree.inorder(newTree) print("\npreorder: ") BinaryTree.preorder(newTree) print("\npostorder: ") BinaryTree.postorder(newTree) print("\n") main()
true
f356cdb6113fd2cc22d315f8cba8875327760c12
rivwoxx/python-Le
/exs/bi7.py
501
4.25
4
''' Escribir un programa que determine si un año es bisiesto. Un año es bisiesto si es múltiplo de 4 (por ejemplo 1984). Los años múltiplos de 100 no son bisiestos, salvo si ellos son también múltiplos de 400 (2000 es bisiesto, pero; 1800 no lo es). ''' def is_leap(year): if (year % 100 != 0 or year % 400 == 0) and year % 4 == 0: print('{year} is a leap year.'.format(year=year)) else: print('{year} is not a leap year.'.format(year=year)) is_leap(1997)
false
55e3fdb3e74b84f64e6bfc288f4a68b43001a38b
CharlieRider/project_euler
/problem4/problem4.py
960
4.40625
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99 Find the largest palindrome made from the product of two 3-digit numbers. """ def is_numeric_palindrome(n): str_n = str(n) if len(str(n)) % 2 == 0: first_split_reversed = "".join(reversed(str_n[:int(len(str_n) / 2)])) second_split = str_n[int(len(str_n) / 2):] if first_split_reversed == second_split: return True return False def largest_multiplicative_palindrome(num_digits): max_range = int('9' * num_digits) largest_palindrome = 0 for x in range(max_range, -1, -1): for y in range(max_range, -1, -1): multiple = x * y if is_numeric_palindrome(multiple): if multiple > largest_palindrome: largest_palindrome = multiple return largest_palindrome largest_multiplicative_palindrome(3)
true
e3b2ea406823f0843bf6abb13b4acc0f8f07843a
sabinzero/various-py
/operations/main.py
254
4.1875
4
a=input("enter first number: ") b=input("enter second number: ") c=input("enter third number: ") S=a+b+c print "sum of the numbers = %d" % S P=a*b*c print "product of the numbers = %d" % P A=(a+b+c)/3 print "average of the numbers = %f" % A
true
a090f50bee3b3f2a57726d560582ae0e97524071
sabinzero/various-py
/prime number/main.py
210
4.15625
4
from math import sqrt num = input("enter number: ") x = int(sqrt(num)) for i in range(2, x + 1): if num % i == 0: print "number is not prime" exit(0) print "number is prime"
true
1d4dbbd05c87e7e6c175bf0c3950f6f9d444f3ed
KKrishnendu1998/NUMERICAL_METHODS_ASSIGNEMENT
/fibonacci_module.py
566
4.28125
4
'''it is a module to print first n fibonacci numbers creator : Krishnendu Maji ''' def fibonacci(n): # defining the function to print 1st n fibonacci numbers# a = 0 #the value of 1st number# b = 1 #the value of second number# i = 0 print('first '+str(n)+' fibonacci numbers are :\n',a,'\n',b) #printing the 1st two values# count = 2 while (i >= 0 and count < n): c = a + b print(c) #printing the next values# a = b b = c count +=1
true
170f02f6857b192722fb5a7aa1682ca982ff0444
neelesh98965/code-freak
/python/Red Devil/FizzBuzz.py
538
4.3125
4
""" Write a function called fizz_buzz that takes a number. 1. If the number is divisible by 3, it should return “Fizz”. 2. If it is divisible by 5, it should return “Buzz”. 3. If it is divisible by both 3 and 5, it should return “FizzBuzz”. 4. Otherwise, it should return the same number. """ def fizz_buzz(n): if (n % 3 == 0 and n % 5 == 0): return("FizzBuzz") if(n%3==0): return("Fizz") if(n%5==0): return("Buzz") return(n) print(fizz_buzz(int(input("Enter the number "))))
true
a3aac3528312d90213978df624bd7bb84f088e43
YChaeeun/WTM_learningPython
/1_input/0509_input.py
1,619
4.125
4
# 0509 # 자료형 이해하기 & 파이썬 입출력 연습하기 # 자료형 # 문제 1 : 3.14를 문자열, 정수, 실수로 출력하기 num = 3.14 numTostring = str(num) floatToint = int(num) intTofloat = float(floatToint) print(numTostring, type(numTostring)) print(floatToint, type(floatToint)) print(intTofloat, type(intTofloat)) print() # 줄 한 칸 띄기 # 입출력 # 문제 1 : 실수를 입력받아 그 제곱 출력하기 num = float(input("실수를 하나 입력하세요: ")) print("제곱할 숫자는?", num) print(f"제곱한 수는 {num**2}입니다") print() # 문제 2 : 이름과 출생 연도를 입력받고 다음과 같이 출력하세요 name = input("이름: ") birthYear = int(input("출생연도: ")) #print("당신의 이름은", name, "이며", "당신의 나이는", 2019-birthYear, "살 입니다.") print(f"당신의 이름은 {name}이며, 당신의 나이는 {2019 - birthYear}살 입니다.\n") # 문제 3 : 정수 3개를 입력받아 그 합과 평균을 출력하세요 #n1, n2, n3 = input("정수 3개를 입력하세요 : ").split() #n1 = int(n1) #n2 = int(n2) #n3 = int(n3) n1, n2, n3 = map(int, input("정수 3개를 입력하세요 : ").split()) #print("총합은", n1+n2+n3 ) #print("평균은", float((n1+n2+n3)/3)) print(f"총합은 {n1+n2+n3}" ) print(f"평균은 {float((n1+n2+n3)/3)}\n") # 소수점 아래 자리수 정해서 출력하기 # %.nf -> 소수점아래 n 자리까지 표시하기 print("평균은 %.1f (소수점 아래 한자리)" % float((n1+n2+n3)/3)) print("평균은 %.2f (소수점 아래 두 자리)" % float((n1+n2+n3)/3))
false
9705a09929ca2aeb3b1547f5560b7f8bb8e3aa13
NeilNjae/szyfrow
/szyfrow/support/text_prettify.py
2,075
4.3125
4
"""Various functions for prettifying text, useful when cipher routines generate strings of letters without spaces. """ import string from szyfrow.support.segment import segment from szyfrow.support.utilities import cat, lcat, sanitise def prettify(text, width=100): """Segment a text into words, then pack into lines, and combine the lines into a single string for printing.""" return lcat(tpack(segment(text), width=width)) def tpack(text, width=100): """Pack a list of words into lines, so long as each line (including intervening spaces) is no longer than _width_""" lines = [text[0]] for word in text[1:]: if len(lines[-1]) + 1 + len(word) <= width: lines[-1] += (' ' + word) else: lines += [word] return lines def depunctuate_character(c): """Record the punctuation of a character""" if c in string.ascii_uppercase: return 'UPPER' elif c in string.ascii_lowercase: return 'LOWER' else: return c def depunctuate(text): """Record the punctuation of a string, so it can be applied to a converted version of the string. For example, punct = depunctuate(ciphertext) plaintext = decipher(sanitise(ciphertext)) readable_plaintext = repunctuate(plaintext, punct) """ return [depunctuate_character(c) for c in text] def repunctuate_character(letters, punctuation): """Apply the recorded punctuation to a character. The letters must be an iterator of base characters.""" if punctuation == 'UPPER': return next(letters).upper() elif punctuation == 'LOWER': return next(letters).lower() else: return punctuation def repunctuate(text, punctuation): """Apply the recored punctuation to a sanitised string. For example, punct = depunctuate(ciphertext) plaintext = decipher(sanitise(ciphertext)) readable_plaintext = repunctuate(plaintext, punct) """ letters = iter(sanitise(text)) return cat(repunctuate_character(letters, p) for p in punctuation)
true
d9ef06541e511a83aefdc6cb947720a5414079d1
keitho18/tkinter_freecodecamp_course
/tkinter_tutorials/grid.py
437
4.125
4
from tkinter import * root = Tk() #Creating a label widget myLabel1 = Label(root, text="Hello World") myLabel2 = Label(root, text="My name is Keith") #Putting the widgets into the GUI using the grid coordinates #If there are empty grid cells, then the GUI will skip them when the GUI is displayed myLabel1.grid(row=0, column=0) myLabel2.grid(row=0, column=1) #We need a continual loop to run the GUI root.mainloop()
true
454b50d9a8b007d16f4f52d8f7d446e450a71275
hubbm-bbm101/lab5-exercise-solution-b2210356106
/Exercise3.py
440
4.21875
4
import random number = random.randint(0, 20) guess = 0 print("A random number is generated between 0 and 20. Please type your guess.") while guess != number: guess = int(input("Your guess = ")) if guess < number: print("Please increase your guess and try again.") elif guess > number: print("Please decrease your guess and try again.") else: print("Congratulations! You guessed it right.")
true
1ce97a7b2be9a31028359bb93d3a12b1084f76a8
Azumait/grammar1-1
/back_python_1_basic1/1_python_grammar1/9.py
1,524
4.125
4
# [정식 클래스 만들기] class Human(): # 모델링(초기화) def __init__(self, name, weight, language): self.name = name self.weight = weight self.language = language # print시의 처리 def __str__(self): # print했을 때 클래스는 위치만 나오는데, 이걸 지정하면 이대로 나온다. return "{}은 {}키로이며, {}언어를 구사해요.".format(self.name, self.weight, self.language) # 개인 메소드 만들기 def str2(self): return "{}은 {}키로에요.".format(self.name, self.weight) def weightCheck(self): print("{}은 {}키로에요.".format(self.name, self.weight)) def eat(self): self.weight = self.weight + 1 self.weightCheck() def diet(self): self.weight = self.weight - 1 self.weightCheck() def greet(self): if (self.language == 'Korean'): print('안녕하세요!') elif (self.language == 'English'): print('Hello!') else: print('fqlkj2##@?') person1 = Human("Yang", 68, "Korean") # print(person1) # print(person1.str2()) person2 = Human("Lee", 47, "English") # print(person2) # print(person2.str2()) person3 = Human("ET", 250, "외계어") # person1, 2, 3는 Human 클래스의 인스턴스(복제본)들입니다. person1.eat() person2.eat() person1.diet() person1.diet() person2.diet() person2.diet() person1.greet() person2.greet() person3.greet() person3.diet() person3.eat()
false
4c5654b4cd2ba4ef00f930a9f94276750bf644c6
Azumait/grammar1-1
/back_python_1_basic1/1_python_grammar1_min/4.py
1,193
4.4375
4
# Method(parameter) 만들기 # 블럭 지정 후 ctrl + / = 주석처리 # definition 정의 # def add(a, b): # result = a + b # print(result) # # 호출 # add(1, 3) # def printHello(): # print('Hello') # printHello() # def add10(a): # result = a + 10 # print(result) # add10(1) # add10(10) # def addmulti(a): # result = a * 10 # print(result) # addmulti(10) # # 에러의 처리 방법 # try: # def adddiv(a): # result = a / 0 # print(result) # adddiv(100) # except Exception as log: # print("에러원인 :", log) def add2(a, b): result = a + b print("{} + {} = {}".format(a,b,result)) def minus2(a, b): result = a - b print("{} - {} = {}".format(a,b,result)) def multi2(a, b): result = a * b print("{} * {} = {}".format(a,b,result)) # 에러의 처리 방법 try: def div2(a, b): result = a / b print("{} / {} = {}".format(a,b,result)) except Exception as log: print("에러원인 :", log) # 캐스팅 : 데이터타입 바꾸기 int(), float(), str() # 인풋 : 사용자 입력받기 a = int(input()) b = int(input()) add2(a, b) minus2(a, b) multi2(a, b) div2(a, b)
false
5380f0cbaeddd4b3e88654b829628255db3c1109
Cayce2514/Python
/collatz.py
812
4.21875
4
def getNumber(): global number while number == 0: try: number = int(input("Please enter a number: ")) except ValueError: print("That doesn't seem to be a number, please enter a number") return number def collatz(number): if (number % 2 == 1): print('You picked an odd number.') elif (number % 2 == 0): print ('You picked an even number.') else: print ("That doesn't seem to be a number, quitting") print("Let's print out the Collatz sequence starting with your number...") print(number) while number > 1: if (number % 2 == 1): number = 3 * number + 1 print(number) else: number = number // 2 print(number) number = 0 getNumber() print("You entered " + str(number) + ".") collatz(number)
true
8271197763e942373597f67a4cf3ab3131e01085
boini-ramesh408/week1_fellowship_peograms
/algoriths/BubbleSort.py
402
4.1875
4
from com.bridgelabz.python.utility.pythonUtil import bubble_sort list=[]#to take run time values in sorting first take one emply list and add the elements to the empty list try: num=int(input("enter the number")) for i in range(0,num): element = int(input()) list.append(element) bubble_sort(list) except ValueError: print("enter only integer values....")
true
4d7a37c3c1fa3ab8e02e8c046af3c2b006b66a9f
diparai/IS211_Assignment4
/sort_compare.py
2,389
4.1875
4
import argparse # other imports go here import time import random def get_me_random_list(n): """Generate list of n elements in random order :params: n: Number of elements in the list :returns: A list with n elements in random order """ a_list = list(range(n)) random.shuffle(a_list) return a_list def insertion_sort(a_list): for index in range(1,len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position-1] > current_value: a_list[position] = a_list[position-1] position = position - 1 a_list[position] = current_value def shell_sort(a_list): sublist_count = len(a_list)//2 while sublist_count > 0: for start_position in range(sublist_count): sublist_count = sublist_count // 2 def python_sort(a_list): return sorted(a_list) if __name__ == "__main__": """Main entry point""" random.seed(100) list_sizes = [500,1000,5000] total_time = 0 for list_size in list_sizes: for i in range(100): mylist = get_me_random_list(list_size) start = time.time() ordered_list = python_sort(mylist) end = time.time() sort_time = end - start total_time += sort_time average = total_time /100. print(f'Average time to sort a list of {list_size} using Python is {average: 0.8f} seconds') for list_size in list_sizes: for i in range(100): mylist = get_me_random_list(list_size) start = time.time() insertion_sort(mylist) end = time.time() sort_time = end - start total_time += sort_time average = total_time / 100 print(f'Average time to sort a list of {list_size} using Insertion sort is {average: 0.8f} seconds') for list_size in list_sizes: for i in range(100): mylist = get_me_random_list(list_size) start = time.time() shell_sort(mylist) end = time.time() sort_time = end - start total_time += sort_time average = total_time / 100. print(f'Average time to sort a list of {list_size} using Shell sort is {average: 0.8f} seconds')
true
eabb73a4092281f19c17ab551327848bcf523dc5
kahei-li/python_revision
/days-calculator/time-till-deadline.py
514
4.15625
4
from datetime import datetime user_input = input("enter your goal with a deadline separated by colon. e.g. goal:dd/mm/yyyy\n") input_list = user_input.split(":") goal = input_list[0] deadline = input_list[1] print(input_list) deadline_date = datetime.datetime.strptime(deadline, "%d/%m/%Y") # converting input date into python module datetime format today_date = datetime.datetime.today() time_till = deadline_date - today_date print(f"Dear user! Time remaining for your goal: {goal} is {time_till.days} days")
true
7908203039fd811602f482efc1a9153a39d855f7
Mjk29/CS_100_H03
/Python Files/9_14_16/MattKehoe_HW01.py
1,026
4.1875
4
flowers= ['rose', 'bougainvillea','yucca', 'marigold', 'daylilly', 'lilly of the valley'] print ('potato' in flowers) thorny = flowers[:3] poisonous = flowers[-1] dangerous = thorny + poisonous print (dangerous) print (poisonous) print ( thorny) print ( flowers) xpoint = [0,10,6,7] ypoint = [0,10,6,8] radius = 10 for i in range(0, 4): print (xpoint[i], ',', ypoint[i]) print (((xpoint[i]**2)+ (ypoint[i]**2)) < radius**2) print (radius**2) i += i string1='phone' print (string1) x = len(string1) for i in range(0, x): string2.append = string1[i] print(string2) i += i print(string1.split()) string2.reverse() print(string2) grades = ['A', 'F', 'C', 'F', 'A', 'B', 'A'] rank = ['A','B','C','D','F'] frequency = [] x=len(grades) for i in range(0, x): frequency.append(grades.count(rank[i])) i += i """the loop should be able to advance through the different ranks of a-f, but I cant figure out the correct syntax to do it. """ print(frequency)
true
8804d6c08269a6939b6739d5bd6821e937735b33
asimonia/datastructures-algorithms
/Recursion/listsum.py
428
4.1875
4
""" A recursive algorithm must have a base case. A recursive algorithm must change its state and move toward the base case. A recursive algorithm must call itself, recursively. """ def listsum(numList): theSum = 0 for i in numList: theSum = theSum + i return theSum def listsum2(numList): """Recurisve version of listsum""" if len(numList) == 1: return numList[0] else: return numList[0] + listsum2(numList[1:])
true
2d2d40ad0d0e97894f8cdec6bef72a46a5544c14
mukeshsinghmanral/Python-part-2
/py/fib.py
456
4.3125
4
def fib(n): ''' this is to find fibonacci series upto some limit''' a,b=0,1 print("fibonacii series of",n,"terms is :",end=' ') print(a ,b ,end=' ') for i in range(n-2): c=a+b print(c,end=' ') a=b b=c try: n=int(input('enter number of terms: ')) if n==1: print(0) elif n<=0: print('invalid number of terms!') else: fib(n) except Exception: print('ENTER A INTEGER TYPE VALUE.\nDON\'T YOU GET IT!!')
false
8df137c1bf7a5a3cd1c5009006b31f3af7b91fcf
Dinu28/Python3
/Lesson9.py
256
4.125
4
#!/usr/bin/env python #File operations ################################### #Find a word in the file fil=open("test1.txt","r") buff=fil.read() word=raw_input("Enter a word to search:") if(word in buff): print("Yes,Found it!") else: print("Not Found!")
true
c8a4dbda658b550211919b6e07a9330b1acf222a
Squareroot7/Python
/LargestPalindromNum.py
1,774
4.25
4
#Largest palindrom number #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. #you have to find the LARGEST, so maybe you have to start from the biggest numbers, as 999x999 def main(): largest=0 numero= int(input('Inserire un numero ')) if(Palindroma(numero))!=None: print(Palindroma(numero)) for i in range(999,100,-1): #io non avevo usato i due cicli ma usando i*(i-1) avevo fatto le combinazioni più alte ed era uscito. stampava se il risultato era palindromo for j in range(999,100,-1): num1=i*j if Palindroma(num1) != None: if(num1>largest): largest=num1 if(num1<largest): break print(largest) #if num1!=None and num2!=None: # if num1>num2: # print("This is the largest prime number %d" %num1 ) # break # else: # print("This is the largest prime number %d" %num2 ) # break def Palindroma(numero): num=str(numero) lenght=len(num) first = num[0] last= num[lenght-1] if lenght%2==0: for i in range(round(lenght/2)): if num[i]==num[lenght-1-i] and (i+1==lenght-1-i): return num #elif i+1==lenght-1-i: # print('Il numero non è palindromo') else: for i in range(round((lenght-1)/2)): if num[i]==num[lenght-1-i] and i+2==(lenght-1-i): return num #elif i+2==lenght-1-i: # print('Il numero non è palindromo') main()
false
fffc9f5427e0bc5d91fa09b44a6c0e13ef77cf0c
somesh-paidlewar/Basic_Python_Program
/make_a_triangle.py
673
4.5
4
#To draw a Triangle with three points as input with mouse from graphics import * win = GraphWin('Make a Triangle',600,600) win.setCoords(0.0,0.0,10.0,10.0) message = Text(Point(5,0.5), 'Click any three points to draw a Triangle') message.draw(win) #Get and draw three vertices of the Triangle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) #Use the polygon tool to make the triangle triangle = Polygon(p1,p2,p3) triangle.setFill('peachpuff') triangle.setOutline('cyan') triangle.setWidth(3) triangle.draw(win) #Ask user to quit by clicking anywhere else message.setText('Click anywhere to quit') win.getMouse()
true
2a134c9eb2849803e9b6265b619288a47511652f
kanika011/Python-Code-Questions
/IsomorphicStrings.py
1,145
4.125
4
#Isomorphic strings #Given two strings s and t, determine if they are isomorphic. #Two strings are isomorphic if the characters in s can be replaced to get t. #All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. #Example 1: #Input: s = "egg", t = "add" #Output: true #Example 2: #Input: s = "foo", t = "bar" #Output: false #Example 3: #Input: s = "paper", t = "title" #Output: true class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ D={} i=0 j=0 while i<len(s): D[s[i]]=t[j] i=i+1 j=j+1 l=[] for i in D.values(): l.append(i) l.sort() for i in range(len(l)-1): if l[i] == l[i+1]: return False p=[] for k in range(0,len(s)): p.append(D.get(s[k])) if p == list(t): return True else: return False
true
b2fce549968e6dfcb39beaf39acbcc7ed0481a90
somenbg/algorithm
/binary_search_recursive.py
920
4.21875
4
def binary_search_recursive(list_to_search: list, start_index: int, end_index: int, element_to_search: int): ''' Usage: list = [1,2,3,4,5,6] binary_search_recursive(list, 0, len(list1)-1, 1) Output: "Element '1' is at index '0'" ''' if start_index <= end_index: mid_index = (start_index+end_index)//2 if list_to_search[mid_index] < element_to_search: return binary_search_recursive(list_to_search, mid_index+1, end_index, element_to_search) elif list_to_search[mid_index] > element_to_search: return binary_search_recursive(list_to_search, start_index, mid_index-1, element_to_search) else: return "Element '{}' is at index '{}'".format(element_to_search, mid_index) else: return "Element {} is not in the list".format(element_to_search)
true
3bbdb091f3f0afd7ee58958a94ba72895fb3aa8e
AAlfaro29/Phyton
/list_exer.py
702
4.25
4
#foods = ["orange", "apple", "banana", "strawberry", "grape", "blueberry",["carrot", "cauliflower","pumpkin"], "passionfruit", "mango", "kiwifruit"] #print(foods[0]) #print(foods[2]) #print(foods[-1]) #print(foods[0:3]) #print(foods[7:12]) #print(foods[-5]) - Needs to ask #names= ["Chilli","Roary", "Remus", "Prince Thomas of Whitepaw", "Ivy"] #email = ["chilli@thechihuahua.com", "roary@moth.catchers", "remus@kapers.dog", "hrh.thomas@royalty.wp", "noreply@goldendreamers.xyz"] #print(names[0],email[0]) #print(names[1],email[1]) #print(names[2],email[2]) #print(names[3],email[3]) #print(names[4],email[4]) #4 name1 = str(input("enter first name? ")) name2 = str(input("enter second name? ")) name3 = str(input("enter third name? ")) list = ['name1', 'name2', 'name3'] print len (list)
false
39113ba692269c24d4eaf98ee6d54fe100b75365
mworrall1101/code-from-school
/summer16/Week09/string_stuff.py
427
4.15625
4
# string_stuff.py # # # # B. Bird - 06/28/2016 S = ' Pear, Raspberry, Peach ' #The .split() method of a string splits the string #by the provided separator and returns a list #of the resulting tokens. for token in S.split(','): print("Token: '%s'"%token) #The .strip() method of a string removes all leading #and trailing whitespace from a string. for token in S.split(','): print("Token: '%s'"%token.strip())
true
e8a664bcd25858d0c99fccf359811bfff2e9f26d
Donzellini/pythonCampinasTech
/Aula_10/listas4.py
241
4.125
4
lista_comida = ["arroz", "feijão", "carne", "batata"] #ler de trás para frente -> usa o negativo print(lista_comida[-2]) #ler de trás para frente usando o range print(lista_comida[-2:]) print(lista_comida[:-2]) print(lista_comida[1:-2])
false
d3ad6c8f300e06192cac0fa87484d1b09ed88d75
Donzellini/pythonCampinasTech
/Aula_04/listas.py
658
4.53125
5
#!/usr/bin/python list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print(list) # Prints complete list print(list[0]) # Prints first element of the list print(list[1:3]) # Prints elements starting from 2nd till 3rd print(list[2:]) # Prints elements starting from 3rd element print(tinylist * 2) # Prints list two times print(list + tinylist) # Prints concatenated lists print(list[2:5]) numero = "1" print(type(numero)) numero = int(numero) #int é uma das funções para converter variáveis. uma variável em string ocupa um espaço maior na memória do que uma variável do tipo number print(type(numero))
false
4553c0b52c2f8fd2721499a87a8c64872bef1c8d
agustashd/Automate-the-boring-stuff
/ch4/commaCode.py
977
4.1875
4
''' Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. Be sure to test the case where an empty list [] is passed to your function. spam = ['apples', 'bananas', 'tofu', 'cats'] ''' def concatenate(valueList): if valueList == []: print('The list is empy') elif len(valueList) == 1: print(valueList[0]) else: lastOne = valueList.pop(-1) print(', '.join([str(val) for val in valueList]) + ' and ' + lastOne) test1 = ['apples', 'bananas', 'tofu', 'cats'] test2 = [] test3 = [1, 'bananas', 3, 'cats', 'END'] test4 = ['one'] test5 = ['one', 'two'] tests = [test1, test2, test3, test4, test5] for test in tests: concatenate(test)
true
1144eb1687350bcfbfa25102e7de4636da85d61d
sahilsoni1/geekindian
/shutil/rotatingfile.py
1,156
4.125
4
import os,shutil import time def make_version_path(path,version): """ it gives version for log file """ if version == 0: return path else: return path +"."+str(version) def rotate(path,version): """ The rotate function uses a technique common in recursive functions """ old_path =make_version_path(path,version) if not os.path.exists(old_path): raise IOError("%s doesn’t exist" %path) new_path = make_version_path(path,version +1) if os.path.exists(new_path): rotate(path,version +1) shutil.move(old_path,new_path) def make_file(file_name): """ It helps to create the text file in same folder. if file is exist than delete privious data and write new data. """ a=open(file_name,"w")#create a file objects data_length=a.write(file_name+"This is how you create a new text file.\n")# write data in file print("%d bytes have in %s"%(data_length,file_name)) a.close()# close the file if(os.path.isfile(file_name)): return True else: return False def rotate_log_file(path): if not os.path.exists(path): new_file = make_file(path) del new_file rotate(path,0) if __name__ == '__main__': rotate_log_file("log")
true
ce54ffffe84ab5c19a06282eda2c062c0586b4d3
LukeBriggsDev/GCSE-Code-Tasks
/p02.1/even_squares.py
584
4.1875
4
""" Problem: The function even_squares takes in a number. If the number is: * even - print out the number squared * odd - print out the number Tests: >>> even_squares(20) 400 >>> even_squares(9) 9 >>> even_squares(8) 64 >>> even_squares(73) 73 """ # This code tests your solution. Don't edit it. import doctest def run_tests(): doctest.testmod(verbose=True) def even_squares(num): result = None if num % 2 == 0: result = num**2 else: result = num print(result) if __name__ == "__main__": run_tests()
true
42078806e06e85ff312f658f360bee67090a6494
LukeBriggsDev/GCSE-Code-Tasks
/p02.2/palindrome.py
1,177
4.6875
5
""" Problem: A palindrome is a word that is spelt the same forwards as it is backwards, such as "racecar" or "mum". The function 'is_palindrome' should test whether a word is a palindrome or not and print either "Palindrome" or "Non-palindrome" The function should be case-insensitive, so "Racecar" should still be counted as a palindrome. Tests: >>> is_palindrome("racecar") Palindrome >>> is_palindrome("RaceCar") Palindrome >>> is_palindrome("AManAPlanACanalPanama") Palindrome >>> is_palindrome("Test") Non-palindrome >>> is_palindrome("Aloha") Non-palindrome """ import doctest def run_tests(): doctest.testmod(verbose=True) def is_palindrome(word): """Conventional, imperative version""" backwards_word = "" for i in range(len(word) - 1, -1, -1): backwards_word += word[i] if word.lower() == backwards_word.lower(): print("Palindrome") else: print("Non-palindrome") def is_palindrome_oner(word): """One line version""" print("Palindrome" if word.lower() == word[::-1].lower() else "Non-palindrome") if __name__ == "__main__": run_tests()
true
639636ad47e0e10703c90b1e623421743a3ba33c
LukeBriggsDev/GCSE-Code-Tasks
/p03.1a/more_nines.py
613
4.15625
4
""" Problem: The function print_nines takes an input, n, and should then print the first n terms in the 9 times table, exactly as in the nines problem. Test: >>> print_nines(2) 1 x 9 = 9 2 x 9 = 18 >>> print_nines(7) 1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 """ # Use this to test your solution. Don't edit it! import doctest def run_tests(): doctest.testmod(verbose=True) # Edit this code def print_nines(n): for i in range(1,n+1): print(i,"x",9,"=",i*9) if __name__ == "__main__": run_tests()
true
9f2d951b4fbb73d2239d1117f33a336b71fffc76
LukeBriggsDev/GCSE-Code-Tasks
/p02.4/most_frequent.py
905
4.3125
4
""" Problem: Given a list of integers, nums, and two integers, a and b, we would like to find out which one occurs most frequently in our list. If either a or b appears more often, print that number. If neither appears at all, print "Neither". If they appear the same number of times, print "Tie". Tests: >>> mode([1, 2, 3, 3], 2, 3) 3 >>> mode([1, 2, 2, 3, 4], 2, 3) 2 >>> mode([1, 2, 2, 1, 2], 3, 4) Neither >>> mode([2, 2, 3, 3], 2, 3) Tie >>> mode([], 1, 2) Neither """ import doctest def run_tests(): doctest.testmod(verbose=True) def mode(nums, a, b): a_count = nums.count(a) b_count = nums.count(b) if a_count > b_count: print(a) elif a_count < b_count: print(b) elif a_count == 0 and b_count == 0: print("Neither") else: print("Tie") if __name__ == "__main__": run_tests()
true
15af75b362e2f496104423ac33660cc60e009582
LukeBriggsDev/GCSE-Code-Tasks
/p03.1x/triangles.py
599
4.15625
4
""" Problem: The triangle numbers are: 1, 3, 6, 10, 15, 21, 28, ... They are generated by starting at 0 and going up by 1, then adding one more to the difference each time. The function triangle_numbers takes an integer n, and should then print the nth triangle number. Tests: >>> triangle_number(1) 1 >>> triangle_number(3) 6 >>> triangle_number(7) 28 >>> triangle_number(50) 1275 """ import doctest def run_tests(): doctest.testmod(verbose=True) def triangle_number(n): return sum(range(1, n+1)) if __name__ == "__main__": run_tests()
true
c2bc9cab220eece67f690d0bd3466911cb95eb87
tangxin20/study
/4_func.py
1,877
4.15625
4
#def f(x): # return x**3 #a=f(int(input("Please input a number:"))) #if a < 100: # print("result < 100") #if a < 50: # print("result < 50") #else: # print("error") #def f(): # return 1+2 #print(f()) #def f(x,y,z): # return x*y*z #a = int(input("please input first number:") ) #b = input("please input second number:") #c = input("please input third number:") #d = f(a,b,c) #print("The result is:"+str(d)) #def f(): # """ # 返回n的平方的值 # :param n:ini. # :return:int,n的平方 # """ # n = int(input("Please input a number:")) # return n**2 #print("您输入数字的平方值为:"+str(f())) #def f(): # n = str(input("Please input a string:")) # print(n) #f() #def f(a,b,c,d=2,e=3): # """ # 返回a+b+c+d+e的值 # :param a:int. # :param b:int. # :param c:int. # :param d:int. # :param e:int. # :return:int,求a,b,c,d,e之和。 # """ # return(a+b+c+d+e) #print(f(10,10,10,10,10)) #def fun1(): # """ # 将输入的数字取整数并除以2,然后将结果返回。 # :return:int,取整并除以2 # """ # a = input("Please input a number:") # try: # c = int(a)/3 # return int(c) # except (ValueError): # print("Please input a int number") #b=fun1() #print(b) #def fun2(): # """ # 调用全局参数b,然后将b乘以4的结果打印出来。 # :return: 无返回,直接打印b*4的结果。 # """ # global b # try: # c = b*4 # print("The result is: " +str(c) ) # except (TypeError): # print("not number!") #fun2() #def to_float(): # """ # 将字符串转换成浮点数 # :return:没有值返回,直接打印出转换的浮点数 # """ # try: # a = input("input a number:") # print(float(a)) # except (ValueError): # print("only for number!") #to_float()
false
f357f7ba592e69d95b90dac903f458d673707915
Nhlaka10/Finance-calculators
/finance_calculators.py
2,440
4.25
4
# Use import math to use math functions import math # Display the statement below so the user can know their options print( """Please choose either \'Investment\' or \'Boond\' from the menu below to proceed:\n\nInvestment - to calculate the amount of interest you will earn on intrest.\nBond - to calculate the amount you will have to pay on a home loan.""" ) # Request input from user transaction_type = input("Enter here: ") if transaction_type.lower().strip(" ") == "investment": amount = float(input("Please enter the amount you are depositing: ")) intrest_rate_percent = float(input("Please enter the intrest rate ,e.g 8 or 10: ")) num_years = int(input("Please enter the number of years you are investing for: ")) intrest_type = input('Do you want "Compound" or "Simple" intrest: ') # Calculate and display answer to user based on what the user has selected if intrest_type.lower().strip(" ") == "simple": intrest_rate = intrest_rate_percent * 1 / 100 Accum_amount = amount * (1 + intrest_rate * num_years) print(f"The amount you will get after your investment is R{Accum_amount}") elif intrest_type.lower().strip(" ") == "compound": intrest_rate = intrest_rate_percent * 1 / 100 Accum_amount = amount * math.pow((1 + intrest_rate), num_years) print(f"The amount you will get after your investment is R{Accum_amount}") else: print( 'You have entered an invalid option. Please enter "Compound" or "Simple" only: ' ) # calculate and display the answer here if the user selected "Bond" isntead of "Investment" elif transaction_type.lower().strip(" ") == "bond": house_value = float( input("Please enter the present value of the house.E.g 100000: ") ) intrest_rate_percent = float(input("Please enter the intrest rate, e.g 7: ")) num_months_repaymet = int( input("Please enter the number of months you plan to repay the bond.E.g.120: ") ) intrest_rate = intrest_rate_percent / 12 repayment = house_value / ( (1 - (1 + (intrest_rate / 100)) ** (-1 * num_months_repaymet)) / (intrest_rate / 100) ) print(f"The amount you will repay each month is R{repayment}") # Dispaly the following if the user inputs an invalid option else: print( 'You have entered an invalid option. Please enter "Investment" or "Bond" only:' )
true
8d4740404f053c5aee554d5479b45754ca2fabbd
facamartinez/MatClas
/e02_for.py
1,026
4.15625
4
#for lets you iterate a fixed amount of times unaCadena = "esta es una cadena de texto" for letter in unaCadena: print(letter) def isVocal(letter): vocales = "aeiou" return letter in vocales for letter in unaCadena: if not isVocal(letter): print(letter) '''The range() Function To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.''' for x in range(6): print(x) '''for anidados''' '''mostrar la combinatoria de las letras de dos cadenas de caracteres''' cadena1 = "1234" cadena2 = "5678" for l1 in cadena1: for l2 in cadena2: print(l1+l2) isMultiplo = lambda y,z: y%z==0 def cantidadMultiplos(a,b): cantidad = 0 for x in range(1,b): if isMultiplo(x,a): cantidad += 1 return cantidad print(cantidadMultiplos(4,100))
false
544922a19e4b926da2a05630f73d9362ec470a3c
ionuttdt/ASC
/lab1/task2.py
942
4.1875
4
""" Basic thread handling exercise: Use the Thread class to create and run more than 10 threads which print their name and a random number they receive as argument. The number of threads must be received from the command line. e.g. Hello, I'm Thread-96 and I received the number 42 """ from random import randint, seed from threading import Thread import sys # n = input() # try: # n = int(n) # except ValueError: # print("ERROR") # exit(-1) n = sys.argv[1] try: n = int(n) except ValueError: print("ValueError") exit(-1) def func(id, nr): #print("Hello, I'm Thread-",id ,"and I received the number", nr) print(f"Hello, I'm Thread-{id} and I received the number {nr}") thread_list = [] seed() for i in range(n): thread = Thread(target=func, args=(i, randint(0, 100))) thread.start() thread_list.append(thread) for i in range(len(thread_list)): thread_list[i].join()
true
a6f759f475a64cf716cad64148a52785e5903344
mdemiral19/Python-By-Example
/Challenge 043.py
771
4.5
4
'''Challenge 043: Ask which direction the user wants to count (up or down). If they select up, then ask them for the top number nd then count from 1 to that number. If they select down, ask them to enter a number below 20 and then count down from 20 to that number. If they entered something other than up or down, display the message "I don't understand.''' direction = input('Do you want to count up or down? Either enter \'up\' or \'down\': ') if direction == 'up': topnumber = int(input('Please enter a number: ')) for i in range(0, topnumber + 1, 1): print(i) elif direction != 'up': downnumber = int(input('Please enter a number below 20: ')) for i in range(20, downnumber - 1, -1): print(i) else: print('I don\'t understand.')
true
5b011da48b6b1b24690a9a3f5afd7dc59b4b54ff
mdemiral19/Python-By-Example
/Challenge 034.py
975
4.3125
4
'''Challenge 034: Display the following message: " 1) Square 2) Triangle Enter a number: " If the user enters 1, then it should ask them for the length of one of ts sides and display the area. If they select 2, it should ask for the base andheight of the trianlge and display the area. If they type in anything else, it should give them a suitable error message.''' import math print('1) Square\n2) Triangle') num = int(input('Please enter either 1 or 2 according to your desired calculation: ')) if num == 1: side = float(input('Please enter the side, preferably in cm: ')) area = side**2 print('The area of the square is', area) elif num == 2: height = float(input('Please enter the height, preferably in cm: ')) base = float(input('Please enter the base, preferably in cm: ')) area = 0.5 * height * base print('The area of the triangle is', area) else: print('Wrong option, this operation is not possible. Please choose either 1 or 2.')
true
c084467ce703925b8d6f6ba47507bc60170bd0b0
mdemiral19/Python-By-Example
/Challenge 032.py
443
4.28125
4
'''Challenge 032: Ask for the radius and the depth of a cylinder and work out the total volume (circle area*depth) rounded to three decimal places.''' import math radius = float(input('Please enter the radius of a cylinder, preferably in cm: ')) depth = float(input('Please enter the depth of a cylinder, preferably in cm: ')) area = math.pi * (radius**2) cylindervolume = area * depth print('The cylinder volume is', round(cylindervolume,3))
true
43782231cb4e7c72c50cade19c0a019443e6b0c2
mulualem04/ISD-practical-7
/ISD practical7Q5.py
334
4.25
4
def count_spaces(userinput): # function definition spaces = 0 for char in userinput : if char == " " : spaces = spaces + 1 # increment return spaces # the function returns the space between words userinput = input("Enter a string: ") print(count_spaces(userinput)) # Call the function within a print
true
4aa53accdfe795005d435abda989a8cfe28bb590
hwchen/thinkpython
/thinkpython4-3exercises.py
1,346
4.46875
4
#thinkpython chapter 4.3 exercises import math from swampy.TurtleWorld import * world = TurtleWorld() bob = Turtle() def square (t, length): """ Draws a square of length "length" using turtle "t" """ for i in range(4): fd(t, length) lt(t) def polygon(t,length,n): """ Draws a polygon with n sides and each side length n using turtle 't' """ for i in range(n): fd(t, length) lt(t, (360/n)) #polygon(bob, 100, 5) def circle(t, r): """ Draws a circle with radius r using turtle t. The idea is that 'segment' is the length of the straight line that the turtle travels before turning inwards. It's calculated by dividing the circle arbitrarily into a segment angle 'x' and calculating the length of the segment using trig. """ x = math.radians(360/100) segment = r*(math.tan(x)) print(segment) for i in range(100): fd(t, segment) lt(t, 360/100) #circle(bob, 100) def arc(t,r,x): """ A more general version of circle. Prints the same circle as in fn circle, but cuts off after x degrees. steps is how 360 is divided up, not how each arc is divided. """ steps = 100 arc = r*(math.sin(math.radians(360/steps))) print(arc) for i in range(steps * x/360 ): fd(t, arc) lt(t, 360/steps) arc (bob,50, 180) wait_for_user()
false
83ec58ac871dd5136c3e2f26b273c38da989da71
cff874460349/tct
/res/gui/moveCircle.py
1,380
4.25
4
# use a Tkinter canvas to draw a circle, move it with the arrow keys try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk class MyApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title("move circle with arrow keys") # create a canvas to draw on self.cv = tk.Canvas(self, width=400, height=400, bg='white') self.cv.grid() # create a square box with upper left corner (x,y) self.x = 120 self.y = 120 size = 150 box = (self.x, self.y, self.x + size, self.y + size) # create a circle that fits the box self.circle = self.cv.create_oval(box, fill='red') # bind arrow keys to movement self.bind('<Up>', self.move_up) self.bind('<Down>', self.move_down) self.bind('<Left>', self.move_left) self.bind('<Right>', self.move_right) def move_up(self, event): # move_increment is 5 pixels y = -5 # move circle by increments x, y self.cv.move(self.circle, 0, y) def move_down(self, event): y = 5 self.cv.move(self.circle, 0, y) def move_left(self, event): x = -5 self.cv.move(self.circle, x, 0) def move_right(self, event): x = 5 self.cv.move(self.circle, x, 0) app = MyApp() app.mainloop()
true
176b9967b350927dec77cbce6c7cdcbc26cf85e6
monica141/lecture4
/classes2.py
886
4.28125
4
class Flight: #creating a new class with the innit method def __init__(self, origin, destination, duration): self.origin = origin self.destination = destination self.duration = duration #printing the information of the flight #we take self to know the object we are operating with def print_info(self): #self refers to the object we are trying to prin information for and the object is the object we take print(f"Flight origin: {self.origin}") print(f"Flight destination: {self.destination}") print(f"Flight duration: {self.duration}") def main(): #printing the flight information f1 = Flight(origin="New York", destination="Paris", duration=540) f1.print_info() f2 = Flight(origin="Tokyo", destination="Shanghai", duration=185) f2.print_info() if __name__ == "__main__": main()
true
c86bf31fad69b37cfe9e483e05d3ba58f0b14cb2
parthpanchal123/Algorithms
/insertionsort.py
399
4.15625
4
def insertion_sort(arr): for i in range(1, len(arr)): hole = i value = arr[i] while(hole > 0 and arr[hole - 1] > value): arr[hole] = arr[hole-1] hole -= 1 arr[hole] = value return arr if __name__ == "__main__": print('Enter elements to sort') my_arr = list(map(int, input().split(" "))) print(insertion_sort(my_arr))
false
992564ad8cbb1880feee3ea651ee605530691294
KyleRichVA/sea-c45-python
/hw/hw13/trigram.py
1,954
4.28125
4
""" Short Program That Generates Over 100 Words Of A Moby Dick Style Story Using Trigrams. """ import random # get the file used to create the trigram file = open("mobydick.txt", "r") # take the text and store in memory line by line lines = [] for line in file: lines.append(file.readline()) file.close() # Used to store individual words and trigrams. words = [] trigrams = {} # Go through each line and split it up into indivdual words for line in lines: words += line.replace('--', ' ').replace('\n', '').split(' ') # Go through each word and set up a trigram (word, nextword): wordafternextword for i, word in enumerate(words): # if are able to get 3 words without a index out of range. if(i + 1 in range(len(words)) and i + 2 in range(len(words))): # if a two word sequence already appeared. if((word, words[i + 1]) in trigrams.keys()): trigrams[(word, words[i + 1])].append(words[i + 2]) # otherwise create a new trigram for that sequence else: trigrams[(word, words[i + 1])] = [words[i + 2]] # the random starting trigram and printing for the text generation. start = random.choice(list(trigrams.keys())) print(start[0], start[1], trigrams[start][0], end=' ') # set up the next trigram key nextKey = (start[1], trigrams[start][0]) lastWord = start[1] # generates new text while the the last two words printed exist in the trigram wordsPrinted = 0 wordLimit = random.randint(125, 201) # will stop generating new text after between 125 and 200 words have been made. while(nextKey in trigrams.keys() and wordsPrinted < wordLimit): # used to select a random 3rd word from the trigram ran = random.choice(range(len(trigrams[nextKey]))) newWord = trigrams[nextKey][ran] print(newWord, end=' ') # set up the next trigram lastWord = nextKey[1] nextKey = (lastWord, newWord) wordsPrinted += 1 # print a new line to look nice in the terminal print()
true
1cc335521cf917c62a4d914afe3390215c19acff
RyanAVelasco/Jaoventure.net_Exercises
/Chapter_7.py
2,678
4.34375
4
import random print(""" === 7.1: Exercises with classes === Use the python documentation on classes at https://docs.python.org/3/tutorial/classes.html to solve the following exercises. 1. Implement a class named "Rectangle" to store the coordinates of a rectangle given by (x1, y1) and (x2, y2). 2. Implement the class constructor with the parameters (x1, y1, x2, y2) and store them in the class instances using the "self" keyword. 3. Implement the "width()" and "height()" methods which return, respectively, the width and height of a rectangle. Create two objects, instances of "Rectangle" to test the calculations. 4. Implement the method "area" to return the area of the rectangle (width*height). 5. Implement the method "circumference" to return the perimeter of the rectangle (2*width + 2*height). 6. Do a print of one of the objects created to test the class. Implement the "__str__" method such that when you print one of the objects it print the coordinates as (x1, y1)(x2, y2).""") print(""" === Answer === 'Each question seems to build upon one another so I'll do it all at the same time.' """) class Rectangle: def __init__(self, x1, x2, y1, y2): self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 def width(self): print(find.__str__()) return self.x1 + self.x2 def height(self): print(find.__str__()) return self.y1 + self.y2 def area(self): print(find.__str__()) return (self.x1 + self.x2) * (self.y1 + self.y2) def circumference(self): print(find.__str__()) return 2 * (self.x1 + self.x2) + 2 * (self.y1 + self.y2) def __str__(self): return (self.x1, self.y1), (self.x2, self.y2) find = Rectangle(0, 10, 30, 30) print("Area:", find.area()) print("Circumference:", find.circumference()) print(""" === 7.3: Exercises with inheritance === Use the "Rectangle" class as implemented above for the following exercises: 1. Create a "Square" class as subclass of "Rectangle". 2. Implement the "Square" constructor. The constructor should have only the x1, y1 coordinates and the size of the square. Notice which arguments you’ll have to use when you invoke the "Rectangle" constructor when you use "super". 3. Instantiate two objects of "Square", invoke the area method and print the objects. Make sure that all calculations are returning correct numbers and that the coordinates of the squares are consistent with the size of the square used as an argument.""") print(""" === Answer === 'I'm truly boggled right now.. No clue how to do this so I'll come back to it after learning more about Classes and sub-classes.'""")
true
a506b8fc0cc4b443bf6fffaf64de0840b7cc0af0
Yushgoel/Python
/agefinder.py
290
4.125
4
from datetime import datetime now = datetime.now() print now date_of_birth = raw_input("Please enter your date of birth in DD-MM-YYYY.") #date_of_birth = int(date_of_birth) birth_year = date_of_birth.year current_year = now.year age = current_year - birth_year print "age = " + age
true
14d8c42d50341ba093681093f0679d6426cbc8cd
Yushgoel/Python
/ctrsumavg.py
239
4.15625
4
n = raw_input("How many numbers do you want to enter?") n = int(n) count = 0 sums = 0 while count < n: num = raw_input("Please enter a number.") num = int(num) sums = sums + num count = count + 1 avg = sums / n print sums print avg
true
863968686f97dc5f0cb1bc620e6af53dbc497e17
Yushgoel/Python
/powers.py
264
4.15625
4
exponent = raw_input("Please enter the exponent.") exponent = int(exponent) num = 1 exponent_plus_one = exponent + 1 while num <= 10: ctr = 1 product = num while ctr <= exponent: product = product * num ctr = ctr + 1 print product num = num + 1
false
0dc6f4e34e40bdc59ed515a5349ce6a3c558d181
shashankgupta2810/Train-Ticket
/Book_train_ticket.py
1,514
4.125
4
class Train(): # create a class # def init function and pass the variable what you required to book the ticket like train name , soucre ,seats, etc. def __init__(self,train_name,train_no,source,destination,status,seats,seatNo): self.seats=seats self.train_no=train_no self.train_name= train_name self.source=source self.destination=destination self.status=status self.seatNo = seatNo # Create the fuction to book ticket def bookTrain(self): print(f'Train name {self.train_name} and No is {self.train_no}') print(f'Booking form {self.source}') print(f'To {self.destination}') # Create the function to check the status of train seats is available or not def getStatusOfTrain(self): print(f'Status of the train is {self.status}') # Create a function to maintain Booking status def bookingStatusOfTicket(self): if self.seats > 0: print(f'No. of seats available {self.seats}') self.seats=self.seats-1 else: print(f'Seats is available {self.seats} you can try for another train or date') def cancelTicket(self,seatNo): self.seatscancel= seatNo print(f'{self.seatNo} ticket canceled') ticket=Train('Ayodhya Express',1234,'LTT','Ayodhya','confirm',3,1) ticket.bookTrain() ticket.bookingStatusOfTicket() ticket.bookingStatusOfTicket() ticket.cancelTicket(1) ticket.bookingStatusOfTicket() ticket.getStatusOfTrain()
true
b99e7805a06f924b0edbce4113bc4bcd2b8c4a45
nirajkvinit/python3-study
/dive-into-python3/ch3/setcompr.py
546
4.5625
5
# Set comprehensions a_set = set(range(10)) print(a_set) print({x ** 2 for x in a_set}) print({x for x in a_set if x % 2 == 0}) print({2**x for x in range(10)}) ''' 1. Set comprehensions can take a set as input. This set comprehension calculates the squares of the set of numbers from 0 to 9 . 2. Like list comprehensions and dictionary comprehensions, set comprehensions can contain an if clause to filter each item before returning it in the result set. 3. Set comprehensions do not need to take a set as input; they can take any sequence. '''
true
65373d7f63b195850dc94333f6520941c9a8bb5e
shay-d16/Python-Projects
/4. Advanced Python Concepts/os_and_open_method.py
1,103
4.125
4
# Make sure to import os so that Python will have the ability to use # and access whatever method we're using import os # Make sure that when you call on a class and you want to access # it's methods within the class, you have mention the class first, # then put a period, then the method. EX: print(os.getcwd()) def writeData(): # similar to the open() process data = '\nHello World!' # we're going to 'write', but unfortunately that would overwrite on top of it # so we have to use 'append' # open for writing, appending to the end of the file if it exists with open('test.txt', 'a') as f: f.write(data) f.close() def openFile(): # While this test.txt file is open we call it 'f' for file with open('test.txt', 'r') as f: data = f.read() # While file is open, read it and store it in data variable print(data) # To make sure you aren't creating any memory leaks with you software # you need to make sure you close that file when you're done f.close() if __name__ == "__main__": writeData() openFile()
true
23e1259ea3b50551b6f76dd2ffef23674635780d
shay-d16/Python-Projects
/5. Object-Oriented Programming/parent_class_child_instances.py
2,889
4.5625
5
# Python 3.9.4 # # Author: Shalondra Rossiter # # Purpose: More on 'parent' and 'child' classes # ## PARENT CLASS class Organism: name = "Unknown" species = "Unknown" legs = 0 arms = 0 dna = "Sequence A" origin = "Unknown" carbon_based = True # Now that you've defined this class and set the basic outline # you can give this class object a method # Methods within this class block stay on the same indention level # as the attributes inside this class. def information(self): # The self parameter is a reference to the current instance of # the class, and is used to access variables that belongs to # the class. It does not have to be named self, you can call it # whatever you like, but it has to be the first parameter of # any function in the class. msg = "\nName: {}\nSpecies: {}\nLegs: {}\nArms: {}\nDNA: {}\nOrigin: {}\nCarbon Based: {}".format(self.name,self.species,self.legs,self.arms,self.dna,self.origin,self.carbon_based) # Remember that even though the attributes in the string have # capital letters, the actual variables are lowercase so you # would have to use lowercase for the program to run. # Variables are case-sensitive. return msg ## CHILD CLASS INSTANCE class Human(Organism): name = "MacGuyver" species = "Homosapien" legs = 2 arms = 2 origin = "Earth" def ingenuity(self): msg = "\nCreates a deadly weapon using only a paper clip, chewing gum and a roll of duct tape!" return msg ## ANOTHER CHILD CLASS INSTANCE class Dog(Organism): name = "Spot" species = "Canine" legs = 4 arms = 0 dna = "Sequence B" origin = "Earth" def bite(self): msg = "\nEmits a loud, menacing growl and bites down ferociously on its target!" return msg ## ANOTHER CHILD INSTANCE class Bacterium(Organism): name = "X" species = "Bacteria" legs = 0 arms = 0 dna = "Sequence C" origin = "Mars" def replication(self): msg = "\nThe cells begin to divide and multiply into two separate organisms!" return msg if __name__ == "__main__": human = Human() print(human.information()) print(human.ingenuity()) dog = Dog() print(dog.information()) print(dog.bite()) bacteria = Bacterium() print(bacteria.information()) print(bacteria.replication()) # Here you are instatiating a 'Human' object, a 'Dog' object # and a 'Bacterium' object, and then calling in the inherited # information() method that they all posses, and then call on # each of their specific methods. You have already overrid # certain information that will take place # Once they are instatiated, even though they inherited # these values, you can override these values
true
ef3e2f58e52b8fd1c8855d36ba46a7899121a6aa
shay-d16/Python-Projects
/5. Object-Oriented Programming/polymorphism_submission_assignment.py
1,888
4.34375
4
# Python 3.9.4 # # Author: Shalondra Rossiter # # Purpose: Complete and submit this assignment given to me by the # Tech Academy # # Requirements: Create two classes that inherit from another class # 1. Each child should have at least two of their own attributes # 2. The parent class should have at least one method (function) # 3. Both child classes should utilize polymorphisms on the parent # class method # 4. Add comments throughout your Python explaining your code # ## PARENT CLASS FAIRY class Fairy(): name = "Queen Clarion" species = "Never Fairy" location = "Pixie Hollow" def getFairyInfo(self): getName = self.name getSpecies = self.species getLocation = self.location msg = ("\nName: {}\nSpecies: {}\nLocation: {}".format(self.name,self.species,self.location)) print(msg) ##CHILD CLASS TINKERFAIRY class TinkerFairy(Fairy): name = "Tinker Bell" talent = "Tinker-talent" home = "Tinker's Nook" # This is the same method in the parent class 'Fairy', but instead # of using 'species' and 'location', we're using 'talent' and 'home'. def getFairyInfo(self): getName = self.name getTalent = self.talent getHome = self.home msg = ("\nName: {}\nTalent: {}\nHome: {}".format(self.name,self.talent,self.home)) print(msg) ## CHILD CLASS GARDENFAIRY class GardenFairy(Fairy): name = "Rosetta" talent = "Garden-talent" home = "Spring Valley" def getFairyInfo(self): getName = self.name getTalent = self.talent getHome = self.home msg = ("\nName: {}\nTalent: {}\nHome: {}".format(self.name,self.talent,self.home)) print(msg) # The following code invokes the methods inside each class queen = Fairy() queen.getFairyInfo() tinker = TinkerFairy() tinker.getFairyInfo() garden = GardenFairy() garden.getFairyInfo()
true
6119b3691c83d69b0000ea78f73f6ef01aac41e5
rajkumargithub/pythonexercises
/forloop.py
204
4.1875
4
#cheerleading program word = raw_input("who do you go for? ") for letter in word: call = "Gimme a " + letter + "!" print letter + "!" print call print "What does that spell?" print word + "!"
true
74d20b8caf905bd6457d8e185acc130715929305
WillianPessoa/LIpE-Resolution-of-Exercises
/A01E04_area-circulo.py
472
4.46875
4
#!/usr/bin/python3 # A única vez que nomeamos uma variável com suas letras maiúsculas é quando # sabemos que essa variável não vai mudar de valor (CONSTANTE) PI = 3.14159 # int() é utilizado para converter o texto inserido em número inteiro. raio = int( input("Insira o valor do raio em cm: ") ) # Calculando a area area = PI * (raio**2) # %d é substituído pelo valor da variável área no formato inteiro print ("A área do círculo é %d cm²" % area)
false
a2b2dd7fe076d007f6fac4de31341cc1324b5453
mukasama/portfolio
/Python Codes/lab 10.py
1,659
4.25
4
class Clock(object): def __init__(self,hours=0,minutes=0,seconds=0): h = hours m = minutes s = seconds ''' hours is the number of hours minutes is the number of minutes seconds is the number of seconds ''' self.hours = hours self.minutes = minutes self.seconds = seconds #print(self.hours,'H') #print(self.minutes,'M') #print(self.seconds,'S') def str_update(self,input_str): '''Take a string of the form 10:20:55 (2 digits for all but hours) No return value''' hours,minutes,seconds=[int(n) for n in input_str.split(':')] self.hours=hours self.minutes=minutes self.seconds=seconds def print_clock(self): print(self.hours,'hours',self.minutes,'minutes',self.seconds,'seconds') def add_clocks(self,clock): h1 = self.hours m1 = self.minutes s1 = self.seconds h2 = clock.hours m2 = clock.minutes s2 = clock.seconds s3 = s1+s2 mx=divmod(s3,60) s3 = mx[1] m3 = mx[0] m3 = m1+m2+m3 hx = divmod(m3,60) m3 = hx[1] h3 = hx[0] h3 = h3 +h1+h2 clock3 = Clock(h3,m3,s3) return(clock3) clock1 = Clock(40,30,25) clock2 = Clock(50,40,35) string = "1234:25:33" print('Clock1') clock1.print_clock() print('Clock2') clock2.print_clock() clock3 = clock1.add_clocks(clock2) print('Clock3(clock1 + clock2)') clock3.print_clock() print('Updates Clock1') clock1.str_update(string) clock1.print_clock()
true
3be4b3b4da244586baa07363a7ec27559c9ad41e
nandadao/Python_note
/note/download_note/first_month/day03/demo02.py
789
4.5
4
""" 选择语句 选择性的执行语句 if 条件: 满足条件执行的代码 else: 不满足条件执行的代码 if 条件1: 满足条件1执行的代码 elif 条件2: 满足条件3执行的代码 else: 以上条件都不满足执行的代码 练习:exercise01~06 """ sex = input("请输入性别:") if sex == "男": print("您好,先生!") # 否则如果 elif sex == "女": print("您好,女士!") else: print("性别未知") # 调试:让程序中断,逐语句执行,查看程序流程,审查变量取值。 # 步骤: # 1. 加断点(在可能出错的行) # 2. 调试运行 # 3. 逐语句执行F8 # 4. 停止调试 Ctrl + F2
false
a03f14911cbfb93f24b7830fbcbbdcbc8682253a
nandadao/Python_note
/note/my_note/first_month/day05/exercise06.py
660
4.1875
4
""" 练习:根据月日,计算是这一年的第几天 3月5日 31 + 28 + 5 """ # month = int(input("请输入月份:")) # day = int(input("请输入日子:")) # # days_of_month = (31,28, 31,30, 31,30, 31,31,30, 31,30,31) # # day_of_today = day # # sum求和 # day_of_today = sum(days_of_month[:month-1]) + day # # # 传统思想,其他语言也可以使用这种思想 # # for i in range(month-1): # # day_of_today += days_of_month[i] # print("这是今年的第%d天" % day_of_today) # print(days_of_month[:month-1]) # list01 = [10, (20, 30), 40] # list02 = list01[:] # list01[1] = "悟空" # print(list02)
false
e2b112d234add91f30b186d31c325b237fcc9516
nandadao/Python_note
/note/my_note/first_month/day04/demo06.py
866
4.25
4
""" 通用操作 """ # name = "八戒" # print(id(name)) # name += "唐僧" # print(id(name)) # print(name) # # name02 = "唐僧" # name02 *= 2 # print(name02) # 比较:依次比较两个容器中元素大小,一旦不同则返回比较结果 # print("孙悟空" > "唐僧") # print(ord("孙"), ord("唐")) # # # # 成员比较 # print("大圣" in "我是齐天大圣") # 索引 # 0 1 2 3 。。。 len(s)-1 # -len(s) -2 -1 # 容器名[索引] message = "我是齐天大圣孙悟空" # print(message[3]) # print(message[333]) # 索引越界 # 切片 # 容器名[开始:结束:间隔] print(message[2:6]) print(message[:4]) # 开始值不写,默认为开头 print(message[::2]) # 结束值不写默认为末尾 print(message[2:-3:1]) print(message[2:-3:-1]) # 空的,什么都没有 print(message[-100:100])
false
9388c68d99efc86a53a16b8ad293d0e605d03779
nandadao/Python_note
/note/my_note/first_month/day17/exercise05.py
432
4.15625
4
""" 练习:获取list01中所有大于10的整数 """ list01 = [11, 2, "a", True, 33] # 生成器函数(写完后,给别人用) def get_bigger_than_10(): for item in list01: if type(item) is int and item > 10: yield item for item in get_bigger_than_10(): print(item) # 生成器表达式 for item in (item for item in list01 if type(item) is int and item > 10 ): print(item)
false
d2e88a5bf1e1069e8491f6285e0877c14c0aca69
nandadao/Python_note
/note/download_note/first_month/day17/demo01.py
1,423
4.25
4
""" yield 练习:exercise01 """ class MyRange: """ 可迭代对象 """ def __init__(self, stop): self.__stop = stop # 程序执行过程: # 调用不执行 # 调用__next__才执行 # 到yield暂时离开 # 再次调用__next__继续执行 # ... # 程序执行原理: "你看见的代码,实际不是这个样子" # 将yield关键字以前的代码定义到next方法中 # 将yield关键字以后的数据作为next方法返回值 # def __iter__(self): # print("准备数据") # yield 0 # # print("准备数据") # yield 1 # # print("准备数据") # yield 2 # # print("准备数据") # yield 3 # # print("准备数据") # yield 4 def __iter__(self): begin = 0 while begin < self.__stop: yield begin# 暂时离开,再次调用继续执行 begin += 1 mr = MyRange(10) iterator = mr.__iter__() while True: try: # 2. 获取下一个元素 item = iterator.__next__() print(item) # 3. 如果没有元素则结束循环 except StopIteration: break # for item in MyRange(5): # print(item) # 0 1 2 3 4 # 循环一次 计算一个 返回一个 # for item in MyRange(99999999999999999999999999999999999999999): # print(item)
false
f262be6a1baaca368304396d1b3be983469477e7
nandadao/Python_note
/note/my_note/first_month/day04/homework_day04.py
1,435
4.125
4
# 3.(扩展) # 循环 # 一个小球从100米落下,每次弹回原高度一半, # 请计算: # 一:总共弹起多少次(最小弹起的高度0 # .01 # m) # 二:整个过程,经过多少米 # count = 0 # jump = 0 # height = 100 # while height/2 > 0.01: # height /= 2 # jump += height*2 # count += 1 # # print(height) # # print(jump) # print("总共弹了" + str(count) + "次。") # print("整个过程,经过了" + str(jump+100) + "米。") # # print(height) # 4. # 判断一个字符串是否为回文: # 上海自来水来自海上 # (用切片[-len(s) // 2] # 是否 # 等于 ) # message = input("请输入一个字符串:") # # if str_01[:len(str_01) // 2] == str_01[:(-len(str_01) // 2):-1]: # # print("是回文") # # else: # # print("不是回文") # # if message == message[::-1]: # print("是回文") # else: # print("不是回文") # 5. # 在终端中,循环录入你喜欢的人。(列表) # 如果录入空字符串,则打印: # 一:所有人(一行一个) # 二:前三个人list01[:3] # 三:打印总人数len(list01) list_01 = [] while True: favorite = input("请输入你喜欢的人:") if favorite: list_01.append(favorite) else: for item in list_01: print(item) print(list_01[:3]) print(len(list_01)) break
false
72136b5c889d3986ac88156eebf186d5d37984b5
nandadao/Python_note
/note/download_note/first_month/day04/demo07.py
752
4.21875
4
""" 列表 list """ # 1. 创建 # -- 创建空列表 list01 = [] list02 = list() # -- list01 = [100,"悟空",True] # list(可迭代对象) list02 = list("我是齐天大圣") # 2. 添加 # -- 追加 list01.append("八戒") # -- 插入 list01.insert(1,"唐僧") print(list01) # 3. 修改 # 将唐三藏地址,赋值给列表第二个元素 list01[1] = "唐三藏" # 遍历[10,20],将每个元素赋值给切片位置的元素 list01[-2:] = [10,20] list01[-2:] = "ok" print(list01) # 4. 删除 # -- 根据元素移除 list01.remove("唐三藏") # -- 根据索引/切片删除 del list01[0] del list01[-2:] print(list01) # 5. 查询 # 索引 print(list02[-1]) # 切片 print(list02[:5]) # 循环 for item in list02: print(item)
false
ff3f00389d5bf9cea8a70f14e539a6702b148bcf
nandadao/Python_note
/note/download_note/first_month/day13/demo05.py
476
4.15625
4
""" 反向运算符(特别不重要) 作用:当前类对象与其他类对象做算数运算 """ class Vector1: def __init__(self, x=0): self.x = x def __str__(self): return "向量的分量是:" + str(self.x) def __add__(self, other): return Vector1(self.x + other) def __radd__(self, other): return Vector1(self.x + other) v01 = Vector1(10) print(v01 + 10)#v01.__add__(10) print(10 + v01)# v01.__radd__(10)
false
ba740f93917a3481227bcd8a39abab404243a4d3
nandadao/Python_note
/note/my_note/first_month/day17/exercise04.py
921
4.28125
4
""" 练习:定义函数:my_enumerate函数,实现下列效果 """ list01 = [1, 2, 55, 3] dict01 = {"a":1, "b":2, "c":3} def my_enumerate(iterable): my_index = 0 for item in iterable: yield (my_index,item) my_index += 1 # for index, item in my_enumerate(list01): # print(index, item) # print("-----------------") # for index, item in my_enumerate(dict01): # print(index, item) # # print("————————————————————") # for index, item in enumerate(dict01): # print(index, item) list02 = ["悟空", "八戒", "唐僧"] list03 = [101, 102, 103] # 练习2:自定义一个函数my_zip, 实现下列效果 def my_zip(iterable01, iterable02): for i in range(len(iterable01)): yield (iterable01[i], iterable02[i]) for item in my_zip(list02,list03): print(item) # ('悟空', 101) # ('八戒', 102) # ('唐僧', 103)
false
9355b32a5516f3857b35be5d74781167bb9e0f3b
bobby-palko/100-days-of-python
/07/main.py
1,568
4.3125
4
from art import logo # Alphabet list to use for our cipher alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # Sweet ASCII art print(logo) is_finished = False def caesar(text, shift, direction): # Cut down large shift values to stay in the range of the list shift = shift % len(alphabet) if direction == "decode": shift = -shift shifted_text = "" for char in text: # We're only scrambling letters, so ignore spaces, numbers, symbols. if char in alphabet: # Set the index of the replacement letter replacement_index = alphabet.index(char) + shift # Check to see if shifting will cause an index out of range, and wrap accordingly if replacement_index >= len(alphabet): replacement_index -=len(alphabet) # Update the new String with the shifted letter shifted_text += alphabet[replacement_index] else: shifted_text += char print(f"The {direction}d text is {shifted_text}.") # Loop the program until we're done while not is_finished: direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) caesar(text, shift, direction) still_use = input("Would you like to continue? Y/N: ").lower() if still_use == "n": is_finished = True print("Goodbye!")
true
32bf5473060c794b71de30c3d96e9d76d82af0b3
monty8800/PythonDemo
/base/42.IO编程-序列化.py
2,801
4.15625
4
# 1.序列化 - pickling ,使用pickle模块来实现 import pickle d = dict(name='mwu', age=10, score=88) print(pickle.dumps(d)) # pickle.dumps()方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。 # 1.1序列化 # 或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object: # f = open('./demo/files/dump.txt','wb') # pickle.dump(d,f) # f.close() # 1.2反序列化 f = open('./demo/files/dump.txt', 'rb') d = pickle.load(f) f.close() print(d) # {'name': 'mwu', 'age': 10, 'score': 88} # 2.Json import json # 2.1序列化 du = json.dumps(d) print(du) # {"name": "mwu", "age": 10, "score": 88} # with open('./demo/files/jsondump.json','w') as f: # json.dump(d,f) # 将json写入文件 # 2.2反序列化 d = json.loads(du) print(d) # {'name': 'mwu', 'age': 10, 'score': 88} # 从文件反序列化 with open('./demo/files/jsondump.json', 'r') as f: j = json.load(f) print(j) # {'name': 'mwu', 'age': 10, 'score': 88} # 3.JSON进阶 类序列化 class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score s = Student('mwu', 12, 100) # print(json.dumps(s)) # TypeError: Object of type Student is not JSON serializable # 错误的原因是Student对象不是一个可序列化为JSON的对象。 # 如果连class的实例对象都无法序列化为JSON,这肯定不合理! # 可选参数default就是把任意一个对象变成一个可序列为JSON的对象,我们只需要为Student专门写一个转换函数,再把函数传进去即可: def student2dict(std): return { 'name': std.name, 'age': std.age, 'score': std.score } print(json.dumps(s, default=student2dict)) # {"name": "mwu", "age": 12, "score": 100} # 这样,Student实例首先被student2dict()函数转换成dict,然后再被顺利序列化为JSON: # 不过,下次如果遇到一个Teacher类的实例,照样无法序列化为JSON。我们可以偷个懒,把任意class的实例变为dict: print(json.dumps(s, default=lambda obj: obj.__dict__)) # {"name": "mwu", "age": 12, "score": 100} # 因为通常class的实例都有一个__dict__属性,它就是一个dict,用来存储实例变量。也有少数例外,比如定义了__slots__的class。 # 同样的道理,如果我们要把JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象,然后,我们传入的object_hook函数负责把dict转换为Student实例: def dict2student(d): return Student(d['name'], d['age'], d['score']) json_str = '{"age": 20, "score": 88, "name": "Bob"}' print(json.loads(json_str, object_hook=dict2student)) # <__main__.Student object at 0x10e0a1978>
false
47496831eb874ccad1a30d98aa88d2ddd07e9af4
monty8800/PythonDemo
/base/15.迭代器.py
2,023
4.15625
4
# 迭代器 from collections.abc import Iterable, Iterator print(isinstance([],Iterable)) # True print(isinstance({},Iterable)) # True print(isinstance('',Iterable)) # True print(isinstance((x for x in range(1,11)),Iterable)) # True print(isinstance(100,Iterable)) # False # 迭代对象(Iterable)和迭代器(Iterator) # 以上几种为True的都是迭代对象,但它们不是迭代器 print(isinstance([],Iterator)) # False print(isinstance({},Iterator)) # False print(isinstance('',Iterator)) # False print(isinstance((x for x in range(1,11)),Iterator)) # True print(isinstance(100,Iterator)) # False # 将迭代对象变成迭代器 print(isinstance(iter([]),Iterator)) # True print(isinstance(iter('abc'), Iterator)) # True # Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。 # 可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是 # 惰性的,只有在需要返回下一个数据时它才会计算。 # Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。 # 小结: # 凡是可作用于for循环的对象都是Iterable类型; # 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列; # 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。 # Python的for循环本质上就是通过不断调用next()函数实现的,如下 for x in [1, 2, 3, 4, 5]: pass # 完全等同于下面的代码: # 首先获得Iterator对象: it = iter([1, 2, 3, 4, 5]) # 循环: while True: try: # 获得下一个值: x = next(it) except StopIteration: # 遇到StopIteration就退出循环 break
false
711991ea38eb5526374a935c5dbc8ed13e54dd64
AyebakuroOruwori/Python-Kids-Projects
/Comparing Dataset Entries-Storing Data in Variables.py
2,145
4.28125
4
#We would be using our knowledge abount booleans and comparison to compare the data of two students from a collection of grade submissions. #We'll kick it off by saving the id, average grade, and recent test score in variables for each of the two student entries. #Let's start saving the data for the first student entry! Create the variable ID_1 that stores "#4" id_1 = "#4" #Next, let's save the student's average grade by creating the variable AVERAGE_GRADE_1 with the value "A". average_grade_1 = "A" #Finally, save the student's test with the variable TEST_SCORE_1 and set it to 90. test_score_1 = 90 #Let's move onto the next student entry! Like before, create id_2 that stores the value "#5". id_2 = "#5" #Create the variable AVERAGE_GRADE_2 and store the second student's average grade, "A". average_grade_2 = "A" #Finally, create TEST_SCORE_2, and store the second stident's test score, 70. test_score_2 = 70 ##Now that we've saved the data for each student entry, we're ready to compare them. # Next, we'll check for duplicate IDs, compare their average grade, and finally compare their test scores. #Create a no_duplicates variable that stores the result of the inequality comparison != between ID_! and ID_2. no_duplicates = id_1 != id_2 #Start displaying the result of the comparison by using print with "No duplicate entries:" print("no_duplicates entries:") #Finally, display the value of the no_dupliocates variable. print(no_duplicates) #Next, create the variable same_average and store the result of comparing average_grade_1 and average_grade_2 with ==. same_average = average_grade_1 == average_grade_2 #Display the string "Same average grade:" and on the next line display the variable same_average. print("Same average grade:") print(same_average) #Next, instead a new variable called higher_score, use > to check if test_score_1 is greater than test_score_2. higher_score = test_score_1 > test_score_2 #To finish up, check the result by displaying "id_1 has a higher score:" then on the next line, display the variable higher_score. print("id_1 has a higher score:") print (higher_score)
true
e9cd0a70a1fd8d694a59377a57f0dab0f9ca53cf
mirzatuzovic/ORS-PA-18-Homework05
/task4.py
666
4.25
4
""" =================== TASK 4 ==================== * Name: Can String Be Float * * Write a script that will take integer number as * user input and return the product of digits. * The script should be able to handle incorrect * input, as well as the negative integer numbers. * * Note: Please describe in details possible cases * in which your solution might not work. * * Use main() function to test your solution. =================================================== """ broj=int(input("Unesite broj: ")) broj=abs(broj) pr=1 while broj>0: pr*=broj%10 broj=broj//10 def main(): proizvod = pr print("Proizvod cifara je: ", proizvod) main()
true
fb713e764b44c44aa5d91bd92d99c079ba4de8e2
NBakalov19/SoftUni_Python_Fundamentals
/01.Python_Intro_Functions_And_Debugging/newHome.py
1,233
4.1875
4
import math flowers_type = input() flowers_count = int(input()) budget = int(input()) flowers = { "Roses": 5, "Dahlias": 3.8, "Tulips": 2.8, "Narcissus": 3, "Gladiolus": 2.5 } money_needed = flowers_count * flowers[flowers_type] discount = 0 if flowers_type == 'Roses' and flowers_count > 80: discount = 0.1 * money_needed elif flowers_type == 'Dahlias' and flowers_count > 90: discount = 0.15 * money_needed elif flowers_type == 'Tulips' and flowers_count > 80: discount = 0.15 * money_needed elif flowers_type == 'Narcissus' and flowers_count < 120: discount = 0.15 * money_needed elif flowers_type == 'Gladiolus' and flowers_count < 80: discount = 0.2 * money_needed total_money_needed = money_needed if flowers_type == 'Gladiolus' or flowers_type == 'Narcissus': total_money_needed = money_needed + discount else: total_money_needed = money_needed - discount difference = math.fabs(total_money_needed - budget) if total_money_needed <= budget: print(f"Hey, you have a great garden with {flowers_count} {flowers_type} and {difference:.2f} leva left.") else: print(f'Not enough money, you need {difference:.2f} leva more.')
true
3366b1aa278766d24fd285173d621674bcd78c57
umangbhatia786/PythonPractise
/GeeksForGeeks/Strings/replace_occurences.py
248
4.28125
4
#Python Program to replace all occurrences of string with another def replace_occurrences(input_str, word, replace_with): return input_str.replace(word, replace_with) my_str = 'geeksforgeeks' print(replace_occurrences(my_str,'geeks','abcd'))
true
39bfcad28fc2da53c90e9b3ae748400ce0d4c526
umangbhatia786/PythonPractise
/GeeksForGeeks/Strings/get_uncommon_words.py
486
4.46875
4
#Python Code get list of uncommon words from 2 different strings def get_uncommon_words(input_str1, input_str2): '''Function that uses List Comprehension to get uncommon words out of two strings''' word_list_1 = input_str1.split(' ') word_list_2 = input_str2.split(' ') return [word for word in word_list_2 if word not in word_list_1] '''Testing the Code with Inputs Now''' A = "Geeks for Geeks" B = "Learning from Geeks for Geeks" print(get_uncommon_words(A,B))
true
977be7873ecfb430347dd0502e047f728b692e8c
umangbhatia786/PythonPractise
/GeeksForGeeks/List/second_largest.py
250
4.125
4
#Python Program to find 2nd Largest num input_list = [1,5,3,6,8,7,10] def get_second_largest(int_list): sorted_list = sorted(int_list) return sorted_list[-2] print(f'Second largest number in given list is {get_second_largest(input_list)}')
true
e7e09e72227e2aa8b496af46e1e02440c0cc8eed
umangbhatia786/PythonPractise
/General/FormatString.py
224
4.3125
4
#Method from python 2 --> 3.5 str1 = 'My name is {} and age is {}'.format('Umang', 26) print(str1) #Method from python 3.5+ # f strings name = 'Cheems' age = 26 str2 = f'My name is {name} and age is {age}' print(str2)
true
8038c7618f323f8a5dd8f47e0228e4eabea1dd20
xettrisomeman/pythonsurvival
/generatorspy/theproblem.py
1,346
4.6875
5
#lets focus on generators #generator is special functions which yields one value at a time #generator gives iterator #we need syntax that generates one item at a time , then #"yiels" a value , and waits to be called again, saving #state information #this is called generators a special case of iterator, #We need a way to restart the iteration at the beginning #whenever we need to (reusing the generator) #we can use the iterator in any "for" statement #we can also use the iterator with "in" and "not in " syntax #iterator: an iterator is an object that can be looped upon. #HOW GENERATORS WORKS? #the "yield" keyword enables you to write a generator function #we use generator when we dont wanna store all the values in the memory , which is really a generator factory #yield means that it will output the value , and save the state #when we put yield in function , the functions becomes factory #fatory means: it wont return value when we call a function , but a function address #we cannot use generator from directly calling it #use using next() #EXAMPLE def make_fibo_gen(n): a,b =0 while a < n: yield a a , b = a+b ,a my_gen = make_fibo_gen(1000) print(next(my_gen)) #Generators save space in memory by computing values when they are needed, # instead of storing them in memory for use later.
true
d72c60c547025346f483a3b17ba2a18c2917aeed
xettrisomeman/pythonsurvival
/listcompre/usingcompre.py
552
4.59375
5
#now using list comprehension #list comprehension is shortcut #it consists of two pats within brackets []. #the first part is the value to be produced ,for example ,i. #second part of list comprehension is the for statement header. # syntax : [value for_statement_header] #example old_list = [1,2,3] #take each element from old_list and double it new_list = [i*2 for i in old_list] print(new_list) #it is same like appending using for loop """ new_list = [] for i in old_list: new_list.append(i*2) """ #-->new_list = [i*2 for i in old_list]
true
52017324a577c708e9f4398a07225f1bcc558249
xhmmss/python2.7_exercise
/codewars/Highest_and_Lowest.py
898
4.15625
4
# In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. # Example: # high_and_low("1 2 3 4 5") # return "5 1" # high_and_low("1 2 -3 4 5") # return "5 -3" # high_and_low("1 9 3 4 -5") # return "9 -5" # Notes: # All numbers are valid Int32, no need to validate them. # There will always be at least one number in the input string. # Output string must be two numbers separated by a single space, and highest number is first. def high_and_low(numbers): array = [int(i) for i in numbers.split(' ')] numbers = "" + str(max(array)) + " " + str(min(array)) return numbers def high_and_low-clever(numbers): array = [int(i) for i in numbers.split(' ')] return "%s %s" % (max(array),min(array)) print high_and_low("1547 294 2059 127 577 3208 1479 1716 220 1417 1828 2317 248 2137 306 2363 2745 314 1273 2049 1472 865")
true
0755152309220626c10382ed0db8b8441e025135
xhmmss/python2.7_exercise
/codewars/Bit_Counting.py
410
4.15625
4
# Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. # Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case def countBits(n): return bin(n)[2:].count('1') # clever # return bin(n).count("1") print countBits(7)
true
44306f1c153fc23eae0df5070e49b8e704a1191f
deenababu92/-Python-Basics-Conditional-Loops
/assigntment 1 Python Basics, Conditional Loops.py
999
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """1.Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.""" n=[] for i in range(2000,3201): if (i%7==0) and (i%5 != 0): n.append(str(i)) print (','.join(n)) # In[ ]: # In[2]: """2. Write a Python program to accept the user's first and last name and then getting them printed in the the reverse order with a space between first name and last name.""" fname = input("Enter your first name ") lname = input("Enter your last name ") print(lname[::-1] + " " + fname[::-1]) # In[3]: """Write a Python program to find the volume of a sphere with diameter 12 cm. Formula: V=4/3 * π * r 3 diameter = 2r radius = diameter/2""" pi = 3.1415926535897931 r= 6.0 V= 4.0/3.0*pi* r**3 print('The volume of the sphere is: ',V) # In[ ]: # In[ ]:
true
3c0578cca5584c4cbc44002976132d01fc3b14e7
sharifh530/Learn-Python
/Beginner/Data types/12.list_slicing.py
357
4.40625
4
# List slicing is also work as a string slicing li = ["work", 5, "dinner", True] print(li) # Reverse print(li[::-1]) # String is immutable but list is not immutable we can change the values of list li[0] = "sleep" print(li) # Copy list li1 = li[:] li1[1] = "work" print(li) print(li1) # modify list li1 = li li1[3] = False print(li) print(li1)
true
a890d305695336c1d5d8bd65a8fcd5659dd10d41
nampng/self-study
/python/CTCI/Chapter1/p1-7.py
576
4.3125
4
# 1.7 Rotate Matrix # Given an image represented by an N x N matrix, where each pixel in the image is # represented by an integer, write a method to rotate the image by 90 degrees. # Can you do this in place? # Super uneligant. Must optimize and also find a way to do it in place. def Rotate(image): array = [] for i in image[-1]: array.append([i]) for row in image[-2::-1]: for i in range(len(row)): array[i].append(row[i]) print(array) if __name__ == "__main__": arr1 = [[1,2,3], [4,5,6], [7,8,9]] Rotate(arr1)
true
0053c1ad24ed7f0443333f1fc41b78bc3eb5d46a
phani-1995/bridgelabzMumbaiWeek1
/testingprograms/sqrt.py
952
4.28125
4
# import math def sqrt(c,epsilon): t=c while abs(t - c/t) > epsilon*t: t= ((c/t)+t)/2 return t epsilon=1 * 10 ** (-15) c=int(input("Enter a positive integer: ")) if (c<=0): print("number cant be negative or zero") c = int(input("Enter a positive integer: ")) print("Square root of number is: ", sqrt(c,epsilon)) sqrt(c,epsilon) ################################################################ # # def sqrt(c, e): # # Newtons method # t = c # while abs(t - c / t) > e: # t = (c / t + t) / 2 # return t # # # if __name__ == '__main__': # epsilon = 1 * 10 ** -15 # positive_int = int(input("Enter a positive number")) # # checks weather given num is positive or not # if positive_int <= 0: # print("Number cant be negitive or zero:") # positive_int = int(input("Enter a positive number")) # # print("Squareroot of number is: ", sqrt(positive_int, epsilon)) #
false
65c7ab612f9546a57e475e8c93fe9feadf4eb33d
cbohara/python_cookbook
/data_struct_and_algos/counter.py
788
4.375
4
#!/usr/local/bin/python3 from collections import Counter # determine the most frequent occuring item in a sequence words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] # super easy! word_count = Counter(words) top_three = word_count.most_common(3) print(top_three) # can also combine and subtract counts more_words = ['why','are','you','not','looking','in','my','eyes'] more_words_count = Counter(more_words) print(word_count) print(more_words_count) # combine counts combo = word_count + more_words_count print(combo) difference = word_count - more_words_count print(difference)
true
a590ad2c64004662cceed2b509b6b55ce885ddc9
joncurrier/generations
/3-Django/app/recipes/utils.py
2,816
4.21875
4
def format_duration(duration): """ Format a timedelta to be human-readable. Argument Format example < 1 minute "55 seconds" < 5 minutes "3 minutes" OR "3 minutes and 15 seconds" < 1 hour "17 minutes" else "2 hours and 14 minutes" """ if duration is None: return None t = duration.seconds d = duration.days hours = t // 3600 minutes = (t % 3600) // 60 seconds = t % 60 if d == 1: if hours == 0: return '1 day' elif hours == 1: return '1 day and 1 hour' else: return '1 day and {} hours'.format(hours) elif d > 1: return '{} days'.format(d) elif t < 60: return '{} seconds'.format(seconds) elif t == 60: return '1 minute' elif t < 120: return '1 minute and {} seconds'.format(seconds) elif t < 300: if seconds != 0: return '{} minutes and {} seconds'.format(minutes, seconds) else: return '{} minutes'.format(minutes) elif t < 3600: return '{} minutes'.format(minutes) elif t < 7200: if minutes != 0: return '1 hour and {} minutes'.format(minutes) else: return '1 hour' else: if minutes != 0: return '{} hours and {} minutes'.format(hours, minutes) else: return '{} hours'.format(hours) def convert_to_fraction(x): """ Convert x to a fraction or mixed fraction. Returns an (integer part, numerator, denominator) tuple. Possible denominators are 2, 3, 4, 5, 6, 8, and 16. """ assert x >= 0, "convert_to_fraction requires a nonnegative argument" denoms = [2, 3, 4, 5, 6, 8, 16] integer_part, numerator, denominator = int(x), 0, 0 x -= integer_part min_diff = x for denom in denoms: for num in (int(x * denom), int(x * denom) + 1): diff = abs(num / denom - x) if diff < min_diff: min_diff = diff numerator, denominator = num, denom return integer_part, numerator, denominator def format_fraction(x): """ Prints a mixed fraction as human-readable text. Expects an input tuple of (integer part, numerator, denominator), such as that returned by convert_to_fraction. """ if x[0] == 0: if x[1] == 0: return str(0) else: return '{}/{}'.format(x[1],x[2]) else: if x[1] == 0: return str(x[0]) else: return '{} {}/{}'.format(x[0], x[1], x[2]) def format_quantity(quantity, unit, food): """ Beautifies a quantity of an ingredient. """ quantity_print = '' if quantity == int(quantity): quantity_print = format(round(quantity), 'd') else: quantity_print = format_fraction(convert_to_fraction(quantity)) return '{} {} {}'.format(quantity_print, unit, food)
true
c98a68b64296f59da92b4cf1d1ee7c3700f82318
sadsfae/misc-scripts
/python/hugs.py
1,295
4.25
4
#!/usr/bin/env python # everybody needs hugs, track it using a dictionary # simple exercise to use python dictionary import sys # create blank dictionary of hug logistics huglist = {} # assign people needing hugs as keys huglist['wizard'] = 5 huglist['panda'] = 1 huglist['koala'] = 2 huglist['tiger'] = 0 huglist['moose'] = 3 huglist['gorbachev'] = 4 # print initial hug list with urgency def HugList(): print "People who need Hugs and How Bad!!" for needhuggers in huglist: print (needhuggers, huglist[needhuggers]) HugList() # add another thing to hug, with urgency rating addhug = raw_input("Add another thing needing hugs: ") # add it's hug urgency addhugrating = raw_input("What is it's hug rating? 0-5: ") addhugrating = int(addhugrating) def HugAddList(): if 0 <= addhugrating <= 5: pass else: print "Hug Rating must be between 0 and 5" sys.exit() # add the new thing to hug huglist[addhug] = addhugrating print "We've updated the hug list, get to hugging!" print huglist # if hug urgency is 5, it needs hugs badly! if addhugrating == 5: print "---------------------------" print "ALERT:: %s needs hug badly!" % (addhug) def main(): HugAddList() if __name__ == '__main__': main()
true