blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4f9b344063339fec622fae3a4ac18ceff57d10be
AlexandreCassilhas/W3schoolsExamples
/Dictionaries.py
1,370
4.3125
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": "1964" } print (thisdict) x = thisdict["model"] print(x) # Acessando o valor de um elemento do dicionário z = thisdict.get("brand") print(z) # Alterando o valor de um elemento do dicionário thisdict["year"] = 2018 print (thisdict) # Varrendo as chaves do dicionário for x in thisdict: print(x) # Varrendo os valores de cada elemento de um dicionário print (" ") for x in thisdict: print (thisdict[x]) print ("ou") for x in thisdict.values(): print (x) # Varrendo as chaves e os respectivos valores print(" ") for x, y in thisdict.items(): print (x, y) # Verificando a existência de um valor no dicionário if "Ford" in thisdict.values(): print ("Ok. Existe") # Verificando a existência de uma key no dicionário if "model" in thisdict: print ("Ok. Model Existe") # Adicionando novo item ao dicionário thisdict["color"] = "red" print (thisdict) # Removendo um item do dicionário thisdict.pop("color") print(thisdict) print("ou") del thisdict["model"] print(thisdict) # Copiando um dicionário print (" ") novodicionario = thisdict.copy() print(novodicionario) # Esvaziando o conteúdo do dicionário thisdict.clear() print(thisdict) # Construindo pelo método dict() thisdict = dict(brand="Ford", model="Mustang", year=2019, color="red") print (thisdict)
false
2e2821bc842d2b6c16a6e9a5f5252b64c4f2d097
ngenter/lnorth
/guessreverse.py
631
4.125
4
# Nate Genter # 1-9-16 # Guess my number reversed # In this program the computer will try and guess your number import random print("\nWelcome to Liberty North.") print("Lets play a game.") print("\nPlease select a number, from 1-100 and I will guess it.") number = int(input("Please enter your number: ")) if number <= 0 or number >= 101: print("That is not a valid number.") tries = 1 guess = () while number != guess: tries == 1 guess = random.randint(1,100) print(guess) if guess != number: tries += 1 print("\nIt took me", tries, "tries.") input("\nPress the enter key to exit.")
true
342d4b53dc20b586b697bc002c78c2539722fb70
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-035.py
486
4.21875
4
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. print('--=--' * 7) print('Analisador de triângulo') print('--=--' * 7) a = float(input('Primeiro segmento:')) b = float(input('Segundo segmento: ')) c = float(input('Terceiro segmento: ')) if a < b + c and b < a + c and c < a + b: print('Os segmentos informados pode FORMAR um triângulo!') else: print('Os segmentos não podem formar um triângulo!')
false
fe297a22342a92f9b3617b827367e60cb7b68f20
jpallavi23/Smart-Interviews
/03_Code_Forces/08_cAPS lOCK.py
1,119
4.125
4
''' wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: either it only contains uppercase letters; or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged. Input The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive. Output Print the result of the given word's processing. Examples Input cAPS Output Caps Input Lock Output Lock ''' word = input() if word[1:].upper() == word[1:]: word = word.swapcase() print(word)
true
4344f818cad8fd3759bab9e914dafb31171782f8
jpallavi23/Smart-Interviews
/06_SI_Basic-Hackerrank/40_Hollow rectangle pattern.py
628
4.21875
4
''' Print hollow rectangle pattern using '*'. See example for more details. Input Format Input contains two integers W and L. W - width of the rectangle, L - length of the rectangle. Constraints 2 <= W <= 50 2 <= L <= 50 Output Format For the given integers W and L, print the hollow rectangle pattern. Sample Input 0 5 4 Sample Output 0 ***** * * * * ***** ''' cols, rows = map(int, input().split()) for itr in range(1, rows+1): for ctr in range(1, cols+1): if itr == 1 or itr == rows or ctr == 1 or ctr == cols: print("*", end="") else: print(" ", end="") print("\r")
true
5510d31f40b640c9a702d7580d1d434715469ba9
smzapp/pyexers
/01-hello.py
882
4.46875
4
one = 1 two = 2 three = one + two # print(three) # print(type(three)) # comp = 3.43j # print(type(comp)) #Complex mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo'] B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3. print(mylist[1]) # This will return the value at index 1, which is 'Grasshopper' print(mylist[0:1]) # This will return the first 3 elements in the list. print(mylist[1:]) # is equivalent to "1 to end" print(len(mylist)) # Example: # [1:5] is equivalent to "from 1 to 5" (5 not included) # [1:] is equivalent to "1 to end" # [len(a):] is equivalent to "from length of a to end" #--------- tups = ('TupName', 'TupsAddress', 'TupsContact') #@TUPLE listo = ['ListName', 'Address', 'Contact'] print(type(tups)) print(type(listo)) print(tups[0], tups[2] ) #tups[3] is out of range print(listo[0]) #---------
true
5da5f3b2063362046288b6370ff541a13552f9c8
adamyajain/PRO-C97
/countingWords.py
279
4.28125
4
introString = input("Enter String") charCount = 0 wordCount = 1 for i in introString: charCount = charCount+1 if(i==' '): wordCount = wordCount+1 print("Number Of Words in a String: ") print(wordCount) print("Number Of Characters in a String: ") print(charCount)
true
80240cb2d0d6c060e516fd44946fd7c57f1a3b06
hungnv132/algorithm
/recursion/draw_english_ruler.py
1,689
4.5
4
""" + Describe: - Place a tick with a numeric label - The length of the tick designating a whole inch as th 'major tick length' - Between the marks of whole inches, the ruler contains a series of 'minor sticks', placed at intervals of 1/2 inch, 1/4 inch, and so on - As the size of the interval decrease by half, the tick length decreases by one + Base cases(recursion): tick_length = 0 + Input: inch, major tick length + Output: --- 0 - -- - --- 1 - -- - --- 2 + Ideas: - method draw_tick(...) is only responsible for printing the line of ticks (eg: ---, -, ---, --) - method interver_v (...) : recursion of draw_tick(...) mehtod until tick_length = 0 - draw_english_ruler(...) is main method - for loop: for displaying 'inch' + References: Data structures and Algorithms in Python by Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael """ def draw_tick(length , tick_label=''): line = '-'*int(length) if tick_label: line += ' ' + tick_label print(line) # interval_version 1 def interval_v1(tick_length): if tick_length > 1: interval_v1(tick_length - 1) draw_tick(tick_length) if tick_length > 1: interval_v1(tick_length - 1) # interval_version 2 def interval_v2(tick_length): if tick_length > 0: interval_v2(tick_length - 1) draw_tick(tick_length) interval_v2(tick_length - 1) def draw_english_ruler(inch, major_tick_length): draw_tick(major_tick_length, '0') for i in range(1,inch): interval_v2(major_tick_length - 1) draw_tick(major_tick_length, str(i)) if __name__ == '__main__': draw_english_ruler(4, 5)
true
7240fb816fb1beba9bf76eaf89579a7d87d46d67
hungnv132/algorithm
/books/python_cookbook_3rd/ch01_data_structures_and_algorithms/07_most_frequently_occurring_items.py
1,516
4.28125
4
from collections import Counter def most_frequently_occurring_items(): """ - Problem: You have a sequence of items and you'd like determine the most frequently occurring items in the sequence. - Solution: Use the collections.Counter """ 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' ] word_counts = Counter(words) print(word_counts) # Counter({'eyes': 8, 'the': 5, 'look': 4, 'my': 3, 'into': 3, 'around': 2, # "don't": 1, 'not': 1, "you're": 1, 'under': 1}) top_three = word_counts.most_common(3) print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)] print(word_counts['look']) # 4 print(word_counts['the']) # 5 print(word_counts['into']) # 3 print(word_counts['eyes']) # 8 # if you want to increment the count manually, simply use addition morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes'] for word in morewords: word_counts[word] += 1 print(word_counts['eyes']) # 9 # or use update() method word_counts.update(morewords) print(word_counts['eyes']) # 10 a = Counter(words) b = Counter(morewords) # Combine counts c = a + b # Subtract counts d = a - b if __name__ == '__main__': most_frequently_occurring_items()
true
d5004f19368c1db3f570771b70d9bd82f94f1a3b
hungnv132/algorithm
/design_patterns/decorator.py
1,029
4.3125
4
def decorator(func): def inner(n): return func(n) + 1 return inner def first(n): return n + 1 first = decorator(first) @decorator def second(n): return n + 1 print(first(1)) # print 3 print(second(1)) # print 3 # =============================================== def wrap_with_prints(func): # This will only happen when a function decorated # with @wrap_with_prints is defined print('wrap_with_prints runs only once') def wrapped(): # This will happen each time just before # the decorated function is called print('About to run: %s' % func.__name__) # Here is where the wrapper calls the decorated function func() # This will happen each time just after # the decorated function is called print('Done running: %s' % func.__name__) return wrapped @wrap_with_prints def func_to_decorate(): print('Running the function that was decorated.') func_to_decorate() print("================") func_to_decorate()
true
10bdaba3ac48babdc769cb838e1f7f4cdef66ae9
nikitaagarwala16/-100DaysofCodingInPython
/MonotonicArray.py
705
4.34375
4
''' Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic. An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non -decreasing. ''' def monoArray(array): arraylen=len(array) increasing=True decreasing=True for i in range(arraylen-1): if(array[i+1]>array[i]): decreasing=False if(array[i+1]<array[i]): increasing=False if not increasing and not decreasing: return False return increasing or decreasing if __name__ == "__main__": array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001] print(monoArray(array))
true
0915b352ed93be7c1fe19f751d021b7b74cafbc2
alexthotse/data_explorer
/Data-Engineering/Part 07_(Elective):Intro_to_Python /Lesson_04.control_flow/control_flow.py
1,798
4.28125
4
# #1. IF Statement # # #2. IF, ELIF, ELSE # #n = str(input("Favourite_number: " )) # n = 25 # if n % 2 == 0: # print("The value of " + str(n) + " is even") # else: # print("The value of " + str(n) + " is odd") # # print(n) # # ######################## # # # season = 'spring' # # season = 'summer' # # season = 'fall' # # season = 'winter' # # season = 'chill dude!' # # # # if season == 'spring': # # print('plant the garden!') # # elif season == 'summer': # # print('water the garden!') # # elif season == 'fall': # # print('harvest the garden!') # # elif season == 'winter': # # print('stay indoors!') # # else: # # print('unrecognized season') # # ######Juno's Code###### # #First Example - try changing the value of phone_balance # phone_balance = 10 # bank_balance = 50 # # if phone_balance < 10: # phone_balance += 10 # bank_balance -= 10 # # print(phone_balance) # print(bank_balance) # # #Second Example - try changing the value of number # # number = 145 # if number % 2 == 0: # print("Number " + str(number) + " is even.") # else: # print("Number " + str(number) + " is odd.") # # #Third Example - try to change the value of age # age = 35 # # # Here are the age limits for bus fares # free_up_to_age = 4 # child_up_to_age = 18 # senior_from_age = 65 # # # These lines determine the bus fare prices # concession_ticket = 1.25 # adult_ticket = 2.50 # # # Here is the logic for bus fare prices # if age <= free_up_to_age: # ticket_price = 0 # elif age <= child_up_to_age: # ticket_price = concession_ticket # elif age >= senior_from_age: # ticket_price = concession_ticket # else: # ticket_price = adult_ticket # # message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price) # print(message)
false
433ad06ffcf65021a07f380078ddf7be5a14bc0d
senorpatricio/python-exercizes
/warmup4-15.py
1,020
4.46875
4
""" Creating two classes, an employee and a job, where the employee class has-a job class. When printing an instance of the employee object the output should look something like this: My name is Morgan Williams, I am 24 years old and I am a Software Developer. """ class Job(object): def __init__(self, title, salary): self.title = title self.salary = salary class Employee(object): def __init__(self, name, age, job_title, job_salary): self.name = name self.age = age self.job = Job(job_title, job_salary) def __str__(self): return "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \ % (self.name, self.age, self.job.title, self.job.salary) # def speak(self): # print "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \ # % (self.name, self.age, self.job.title, self.job.salary) morgan = Employee("Morgan Williams", 24, "Software Developer", 60000) print morgan # morgan.speak()
true
41fdc8a89fb3e7ecdcfaec78e5c668fc0e6e4e80
JoshuaShin/A01056181_1510_assignments
/A1/random_game.py
2,173
4.28125
4
""" random_game.py. Play a game of rock paper scissors with the computer. """ # Joshua Shin # A01056181 # Jan 25 2019 import doctest import random def computer_choice_translator(choice_computer): """ Translate computer choice (int between 0 - 2 inclusive) to "rock", "paper", or "scissors". PARAM choice_computer int between 0 - 2 PRE-CONDITION choice_computer must be int between 0 - 2 POST-CONDITION translate computer choice to "rock", "paper", or "scissors" RETURN return computer choice in "rock", "paper", or "scissors" >>> computer_choice_translator(0) 'rock' >>> computer_choice_translator(1) 'paper' >>> computer_choice_translator(2) 'scissors' """ if choice_computer == 0: return "rock" elif choice_computer == 1: return "paper" else: # choice_computer == 2 return "scissors" def rock_paper_scissors(): """ Play a game of rock paper scissors with the computer. """ choice_computer = computer_choice_translator(random.randint(0, 2)) choice_player = input("Ready? Rock, paper, scissors!: ").strip().lower() if not(choice_player == "rock" or choice_player == "paper" or choice_player == "scissors"): print("Dont you know how to play rock paper scissors, ya loser!") rock_paper_scissors() return print("Computer played:", choice_computer) print("You played:", choice_player) if choice_player == choice_computer: print("TIED") elif choice_player == "rock": if choice_computer == "paper": print("YOU LOSE") elif choice_computer == "scissors": print("YOU WIN") elif choice_player == "paper": if choice_computer == "scissors": print("YOU LOSE") elif choice_computer == "rock": print("YOU WIN") elif choice_player == "scissors": if choice_computer == "rock": print("YOU LOSE") elif choice_computer == "paper": print("YOU WIN") def main(): """ Drive the program. """ doctest.testmod() rock_paper_scissors() if __name__ == "__main__": main()
true
0ca8c1dc04f5e98a3d08b588e2a4c5903e7f61da
amit-kr-debug/CP
/Geeks for geeks/Heap/Sorting Elements of an Array by Frequency.py
2,697
4.125
4
""" Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. Output: For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be seperated by space. Constraints: 1 ≤ T ≤ 70 30 ≤ N ≤ 130 1 ≤ Ai ≤ 60 Example: Input: 2 5 5 5 4 6 4 5 9 9 9 2 5 Output: 4 4 5 5 6 9 9 9 2 5 Explanation: Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6. The output is 4 4 5 5 6. Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 9 9 9 comes first. Now both 2 and 5 have same frequency. So we print smaller element first. The output is 9 9 9 2 5 """ """ tCases = int(input()) for _ in range(tCases): n = int(input()) arr = list(map(int, input().split())) freq = {} for i in arr: if i in freq: freq[i] += 1 else: freq[i] = 1 nDict = {} for key, val in sorted(freq.items(), key = lambda kv:(kv[1], kv[0]), reverse=True): # print(key, val) if val not in nDict: nDict.update({val: [key]}) else: nDict[val].append(key) for key, val in nDict.items(): val.sort() for i in val: for j in range(key): print(i, end=" ") print() """ # solution without heap in O(n*logn), first find freq of each element and make a new dict with value as key # and values of that dict will be arr with that freq then sort each value and print it. tCases = int(input()) for _ in range(tCases): n = int(input()) arr = list(map(int, input().split())) freq = {} for i in arr: if i in freq: freq[i] += 1 else: freq[i] = 1 nDict = {} for key, val in freq.items(): if val not in nDict: nDict.update({val: [key]}) else: nDict[val].append(key) for key, val in sorted(nDict.items(), key=lambda kv: (kv[0], kv[1]), reverse=True): val.sort() for i in val: for j in range(key): print(i, end=" ") print()
true
e2fb43f0392cd69430a3604c6ddcf3b06425b671
amit-kr-debug/CP
/Geeks for geeks/array/sorting 0 1 2.py
1,329
4.1875
4
""" Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. Example 1: Input: N = 5 arr[]= {0 2 1 2 0} Output: 0 0 1 2 2 Explanation: 0s 1s and 2s are segregated into ascending order. Example 2: Input: N = 3 arr[] = {0 1 0} Output: 0 0 1 Explanation: 0s 1s and 2s are segregated into ascending order. Your Task: You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 10^6 0 <= A[i] <= 2 """ # User function Template for python3 class Solution: def sort012(self,arr,n): # code here d = {0: 0,1: 0,2: 0} index = 0 for i in range(n): d[arr[i]] += 1 for key,val in d.items(): for i in range(val): arr[index] = key index += 1 # { # Driver Code Starts # Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) arr = [int(x) for x in input().strip().split()] ob = Solution() ob.sort012(arr,n) for i in arr: print(i,end = ' ') print() # } Driver Code Ends
true
6069283e9388e6d1704f649d14b84e4a288f8d86
amit-kr-debug/CP
/Cryptography and network security/lab - 2/Vigenere Cipher encrypt.py
669
4.21875
4
def encrypt(plain_text, key): cipher_text = "" # Encrypting plain text for i in range(len(plain_text)): cipher_text += chr(((ord(plain_text[i]) + ord(key[i]) - 130) % 26) + 65) return cipher_text if __name__ == "__main__": # Taking key as input key = input("Enter the key:") # Taking plain text as input plain_text = input("Enter the plain text:") count = 0 key_updated = "" # Updating Key for _ in plain_text: if count == len(key): count = 0 key_updated += key[count] count += 1 print("Cipher text:",end = "") print(encrypt(plain_text.upper(),key_updated.upper()))
true
4602c2628ae813e68f997f36b18d270316e42a43
amit-kr-debug/CP
/hackerrank/Merge the Tools!.py
1,835
4.25
4
""" https://www.hackerrank.com/challenges/merge-the-tools/problem Consider the following: A string, , of length where . An integer, , where is a factor of . We can split into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string such that: The characters in are a subsequence of the characters in . Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string . Given and , print lines where each line denotes string . Input Format The first line contains a single string denoting . The second line contains an integer, , denoting the length of each subsegment. Constraints , where is the length of It is guaranteed that is a multiple of . Output Format Print lines where each line contains string . Sample Input AABCAAADA 3 Sample Output AB CA AD Explanation String is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in : We then print each on a new line. """ def merge_the_tools(string, k): import textwrap s=string n=k lis=list(map(str,textwrap.wrap(s,n))) for i in lis: new=list(i[0]) for j in range(1,len(i)): for k in range(len(new)): if new[k] != i[j]: flag = 0 else: flag = 1 break if flag == 0: new.append(i[j]) for i in range(len(new)-1): print(new[i],end="") print(new[len(new)-1]) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k)
true
efa3c5294a1274ba4c2133c34b6aaa32fb3ad590
ayatullah-ayat/py4e_assigns_quizzes
/chapter-10_assignment-10.2.py
921
4.125
4
# 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) email_sender_list = list() for line in handle: word_list = line.split() if len(word_list) < 2: continue if not word_list: continue if not line.startswith('From '): continue email_sender_list.append(word_list[5]) item_dict = dict() for item in email_sender_list: item = item.split(':') it = item[0] item_dict[it] = item_dict.get(it, 0) + 1 for key, value in sorted(item_dict.items()): print(key, value)
true
2836445a3619bd8f3a5554d962f079cc0de9cd9a
sooty1/Javascript
/main.py
1,240
4.1875
4
names = ['Jenny', 'Alexus', 'Sam', 'Grace'] dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph'] names_and_dogs_names = zip(names, dogs_names) print(list(names_and_dogs_names)) # class PlayerCharacter: # #class object attribute not dynamic # membership = True # def __init__(self, name="anonymous", age=0): # if (age > 18): # self.name = name # self.age = age # def run(self): # print('run') # def shout(self): # print(f'my name is {self.name}') # player1 = PlayerCharacter('Tom', 10) # player2 = PlayerCharacter() # player2.attack = 50 # print(player1.shout()) # print(player2.age) #Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age def oldest(*args): return max(args) cat1= Cat("Tom", 3) cat2= Cat('Jerry', 5) cat3= Cat("filbert", 2) def oldest(*args): return max(args)aaaa print(f"The oldest cat is {oldest(cat1.age, cat2.age, cat3.age)} years old.") # 1 Instantiate the Cat object with 3 cats # 2 Create a function that finds the oldest cat # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
true
f7f585f584f0a6b4ccdb708608640d9ba154673c
matherique/trabalhos-edd
/lista_2/test.py
2,095
4.15625
4
#!/usr/bin/env python3 import unittest from Fraction import * class TestFractionClass(unittest.TestCase): def testNumeradorCorreto(self): """ Numerador correto """ n, d = 1, 2 fr = Fraction(n, d) self.assertEqual(fr.num, n) def testDenominadorCorreto(self): """ Denominador correto """ n, d = 1, 2 fr = Fraction(n, d) self.assertEqual(fr.den, d) def testSoma(self): """ Soma de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) res = Fraction(2, 1) self.assertEqual(f1 + f2, res) def testSubtracao(self): """ Subtracao de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) res = Fraction(-1, 1) self.assertEqual(f1 - f2, res) def testMultiplicacao(self): """ Multiplicacao de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) res = Fraction(3, 4) self.assertEqual(f1 * f2, res) def testDivisao(self): """ Divisao de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) res = Fraction(1, 3) self.assertEqual(f1 / f2, res) def testPotenciacao(self): """ Potenciacao de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) n = 1 ** (3/2) d = 2 ** (3/2) res = Fraction(n, d) self.assertEqual(f1 ** f2, res) def testIgualdade(self): """ Potenciacao de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(1, 2) self.assertEqual(f1, f2) def testMaior(self): """Maior de fracoes """ f1 = Fraction(3, 2) f2 = Fraction(1, 2) self.assertGreater(f1, f2) def testMaiorIgual(self): """Maior igual de fracoes """ f1 = Fraction(3, 2) f2 = Fraction(1, 2) self.assertGreaterEqual(f1, f2) def testMenor(self): """Menor igual de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) self.assertLess(f1, f2) def testMenorIgual(self): """Menor igual de fracoes """ f1 = Fraction(1, 2) f2 = Fraction(3, 2) self.assertLessEqual(f1, f2) if __name__ == '__main__': unittest.main(verbosity=2)
false
5b2267600ac663d2493599080b5bf482511015d3
nehaDeshp/Python
/Tests/setImitation.py
623
4.25
4
''' In this exercise, you will create a program that reads words from the user until the user enters a blank line. After the user enters a blank line your program should display each word entered by the user exactly once. The words should be displayed in the same order that they were entered. For example, if the user enters: first second first third second then your program should display: first second third [ use list ] ''' list=[] print("Enter Integers:") while True: num = input("") if(num == " "): break elif(list.__contains__(num)): pass else: list.append(num) print(list)
true
a15d13da749137921a636eb4acf2d56a4681131a
nehaDeshp/Python
/Tests/Assignment1.py
559
4.28125
4
''' Write a program that reads integers from the user and stores them in a list. Your program should continue reading values until the user enters 0. Then it should display all of the values entered by the user (except for the 0) in order from smallest to largest, with one value appearing on each line. Use either the sort method or the sorted function to sort the list ''' list=[] print("Enter Integers:") while True: num = int(input("")) if(num == 0): break else: list.append(num) #sort list.sort() for i in list: print(i)
true
8a61b80b3b96c4559149609d9630323a05f3a134
tanviredu/DATACAMPOOP
/first.py
292
4.34375
4
# Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1,2,3,4,5,6]) # Print out my_avg print(my_avg)
true
caaf2c8cf85b91b74b917523796029eda659131f
samithaj/COPDGene
/utils/compute_missingness.py
976
4.21875
4
def compute_missingness(data): """This function compute the number of missing values for every feature in the given dataset Parameters ---------- data: array, shape(n_instances,n_features) array containing the dataset, which might contain missing values Returns ------- n_missing: list, len(n_features) list containing the number of missing values for every feature """ n_instances,n_features = data.shape n_missing = [0]*n_features for j in range(n_features): for i in range(n_instances): if data[i,j] == '': n_missing[j] += 1 return n_missing def test_compute_missingness(): import numpy as np data = np.empty((4,9),dtype=list) data[0,0] = '' data[0,1] = '' data[1,4] = '' for i in range(6): data[3,i] = '' n_missing = compute_missingness(data) print n_missing if __name__ == "__main__": test_compute_missingness()
true
31116f0e83ba9681303f5540d51b28e8d7d0c1c3
kellyseeme/pythonexample
/220/str.py
228
4.3125
4
#!/usr/bin/env python import string a = raw_input("enter a string:").strip() b = raw_input("enter another string:").strip() a = a.upper() if a.find(b) == -1: print "this is not in the string" else: print "sucecess"
true
d66a2b7006d3bbcede5387ed1a56df930862bccb
kellyseeme/pythonexample
/221/stringsText.py
945
4.21875
4
#!/usr/bin/env python """this is to test the strings and the text %r is used to debugging %s,%d is used to display + is used to contact two strings when used strings,there can used single-quotes,double-quotes if there have a TypeError,there must be some format parameter is not suit """ #this is use %d to set the values x = "there are %d typs of people." % 10 binary = "binary" do_not = "don't" #this is use two variables to strings and use %s y= "those who know %s and those who %s." % (binary,do_not) print x print y #use %r to set x ,%s is the string,and the %r is use the repe() function print "I said: %r." % x #this is use %s to se value y print "I also said:%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" #this is use hilarious to set the string of %r print joke_evaluation % hilarious w = "this is the left side of ..." e = "a string with a right side." #use + to concate the two strings print w + e
true
5a2b8b97398fce8041886ad4920b5f7acd092ef7
kellyseeme/pythonexample
/323/stringL.py
693
4.15625
4
#!/usr/bin/env python #-*coding:utf-8 -*- #this is use the string method to format the strins #1.use the ljust is add more space after the string #2.use the rjust is add more space below the string #3.use the center is add more space below of after the string print "|","kel".ljust(20),"|","kel".rjust(20),"|","kel".center(20),"|" #the string center have more args is the width and the space or other arguments print "|","kel".center(20,"*"),"|" print "|","kel".ljust(20,"*"),"|" print "|","kel".rjust(20,"*"),"|" """ 用来整理字符串的格式,主要使用的方法为ljust,rjust和center,默认情况下使用空格 第二个参数用来表示用什么字符进行填充 """
true
bbb41f0db54a2a443f15cc6855cfa9a2d8a0e3ab
kellyseeme/pythonexample
/323/opString.py
1,007
4.125
4
#!/usr/bin/env python #-*- coding:utf-8 -*- """ this file is to concatenate the strings """ #this is use join to add the list of string pieces = ["kel","is","the best"] print "".join(pieces) #use for to add string other = "" for i in pieces: other = other + i print other #use %s to change the string print "%s %s %s"% (pieces[0],pieces[1],pieces[2]) print "kel" + "is" + "the best" #use function to use the string import operator print reduce(operator.add,pieces,"") """ 在进行拼接字符串的时候,有很多方法,但是都会产生中间变量 最好的方法是使用join方法,在使用join方法的时候,首先构建列表list,然后使用"".join(list)即可,性能最佳 其次的方法是使用%s进行替换,从而在有的是数字的时候,也不需要用str进行字符串的转换 reduce方法用来对sequence的pieces的进行add操作,初始化的值为空,最后返回一个值,对序列中值 进行从左到右的function的operator。add操作 """
false
0db7502613ff0c05461e17509d9b8b6abb1be3d2
kellyseeme/pythonexample
/33/using_list.py
1,053
4.34375
4
#!/usr/bin/env python """ this is for test the list function """ #this is define the shoplist of a list shoplist = ["apple","mango","carrot","banana"] #get the shoplist length,using len(shoplist) print "Ihave",len(shoplist),"items to pruchase." #this is iteration of the list,the list is iterable print "These items are:", for item in shoplist: #there have a comma at the end of the line,it's mean is ride of the newline print item, print "\nIalso have to buy rice." #this is append the function,add a shopinglinst a rice,using append #append is the last the argument shoplist.append("rice") print "My shopping list is now",shoplist print "I will sort my list now" #list is a changeable,so this is sort,and the list is changed shoplist.sort() print "Sorted shoping list is ",shoplist print "The first item I will buy is ",shoplist[0] #this is get the list of value,use the index and then get the value olditem = shoplist[0] #this is delete some of the list del shoplist[0] print "I bouthe the",olditem print "My shopping list is now",shoplist
true
a2861764344d6b0302e21b4d670addd638b13e38
CorinaaaC08/lps_compsci
/class_samples/3-2_logicaloperators/college_acceptance.py
271
4.125
4
print('How many miles do you live from Richmond?') miles = int(raw_input()) print('What is your GPA?') GPA = float(raw_input()) if GPA > 3.0 and miles > 30: print('Congrats, welcome to Columbia!') if GPA <= 3.0 or miles <= 30: print('Sorry, good luck at Harvard.')
true
1d9dba5c3c23f35a906c2527a8fa557e74460d02
hasandawood112/python-practice
/Task-5.py
432
4.15625
4
from datetime import date year1 = int(input("Enter year of date 1 : ")) month1 = int(input("Enter month of date 1 : ")) day1 = int(input("Enter day of date 1 : ")) year2 = int(input("Enter year of date 2 : ")) month2 = int(input("Enter month of date 2 : ")) day2 = int(input("Enter day of date 2 : ")) date1= date(year1,month1,day1) date2 = date(year2,month2,day2) Day = date2 - date1 print(Day.days, "Days have been passed!")
false
06366e956623f3305dbb737d6f91ddcea542daf4
dataneer/dataquestioprojects
/dqiousbirths.py
2,146
4.125
4
# Guided Project in dataquest.io # Explore U.S. Births # Read in the file and split by line f = open("US_births_1994-2003_CDC_NCHS.csv", "r") read = f.read() split_data = read.split("\n") # Refine reading the file by creating a function instead def read_csv(file_input): file = open(file_input, "r") read = file.read() split_data = read.split("\n") no_header = split_data[1:len(split_data)] final_list = list() for i in no_header: string_fields = i.split(",") int_fields = [] for i in string_fields: int_fields.append(int(i)) final_list.append(int_fields) return final_list cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv") # Create a function that takes a list of lists argument def month_births(input_lst): # Store monthly totals in a dictionary births_per_month = {} for i in input_lst: # Label the columns month = i[1] births = i[4] # Check if item already exists in dictonary list if month in births_per_month: # Add the current number of births to the new integer births_per_month[month] = births_per_month[month] + births # If the item does not exist, create it with integer of births else: births_per_month[month] = births return births_per_month cdc_month_births = month_births(cdc_list) # This function uses day of the week instead of month def dow_births(input_lst): births_per_day = {} for i in input_lst: dow = i[3] births = i[4] if dow in births_per_day: births_per_day[dow] = births_per_day[dow] + births else: births_per_day[dow] = births return births_per_day cdc_day_births = dow_births(cdc_list) # This function is more superior because it is a generalized form def calc_counts(data, column): sums_dict = {} for row in data: col_value = row[column] births = row[4] if col_value in sums_dict: sums_dict[col_value] = sums_dict[col_value] + births else: sums_dict[col_value] = births return sums_dict
true
fb9b299eff93179ac097d797c7e5ce59bc20f63a
yugin96/cpy5python
/practical04/q5_count_letter.py
796
4.1875
4
#name: q5_count_letter.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function count_letter(str, ch) that finds the # number of occurences of a specified leter, ch, in a string, str. #main #function def count_letter(str, ch): #terminating case when string is empty if len(str) == 0: return 0 #add 1 to result if ch is equal to first character of str if str[0] == ch: return 1 + count_letter(str[1:], ch) #add 0 to result if ch is not equal to first character of str if str[0] != ch: return 0 + count_letter(str[1:], ch) #prompt user input of string and character string = str(input('Enter a string: ')) character = str(input('Enter a character: ')) print(count_letter(string, character))
true
599df5c53d26902da3f2f16cb892a0ae6501be78
yugin96/cpy5python
/practical04/q6_sum_digits.py
482
4.28125
4
#name: q6_sum_digits.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function sum_digits(n) that computes the sum of # the digits in an integer n. #main #function def sum_digits(n): #terminating case when integer is 0 if len(str(n)) == 0: return 0 else: return int(str(n)[0]) + sum_digits(str(n)[1:]) #prompt user input of integer integer = input('Enter an integer: ') print(sum_digits(integer))
true
78baf00a600d84297b1f2abac7d09470fce0638f
hechtermach/ML
/untitled2.py
218
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 01:27:35 2019 @author: mach0 """ import itertools list_step=['R','L','U','D'] list_all=[] for item in itertools.product(list_step,repeat=3): print (item)
false
fbd7624f47d4e14b47722923fd568c31e082d91d
Monsieurvishal/Peers-learning-python-3
/programs/for loop.py
236
4.59375
5
>>for Loops #The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects. for i in range(5): print("hello!") Output: hello! hello! hello! hello! hello!
true
c56cc5a285093da9ca9cc2265e344bfdbf03f929
Monsieurvishal/Peers-learning-python-3
/programs/for loop_p3.py
282
4.3125
4
>>Write a python script to take input from the user and print till that number. #Ex: if input is 10 print from 1 till 10. n=int(input("enter the number:")) i=0 for i in range(n): print(i) i=i+1 print("finished") #output: enter the number: 0 1 2 3 4 5 6 7 8 9 finished
true
24b146a3e423fd413124b988150d4e1ee01b4204
dell-ai-engineering/BigDL4CDSW
/1_sparkbasics/1_rdd.py
1,467
4.25
4
# In this tutorial, we are going to introduce the resilient distributed datasets (RDDs) # which is Spark's core abstraction when working with data. An RDD is a distributed collection # of elements which can be operated on in parallel. Users can create RDD in two ways: # parallelizing an existing collection in your driver program, or loading a dataset in an external storage system. # RDDs support two types of operations: transformations and actions. Transformations construct a new RDD from a previous one and # actions compute a result based on an RDD,. We introduce the basic operations of RDDs by the following simple word count example: from pyspark import SparkContext from pyspark.sql import SparkSession sc = SparkContext.getOrCreate() spark = SparkSession.builder \ .appName("Spark_Basics") \ .getOrCreate() text_file = sc.parallelize(["hello","hello world"]) counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) for line in counts.collect(): print line # The first line defines a base RDD by parallelizing an existing Python list. # The second line defines counts as the result of a few transformations. # In the third line and fourth line, the program print all elements from counts by calling collect(). # collect() is used to retrieve the entire RDD if the data are expected to fit in memory.
true
c767555ee9c73ae671ed7d37c5951dbe943c3635
hoangqwe159/DoVietHoang-C4T5
/Homework 2/session 2.py
258
4.21875
4
from turtle import * shape("turtle") speed(0) # draw circles circle(50) for i in range(4): for i in range (360): forward(2) left(1) left(90) #draw triangle # = ctrl + / for i in range (3): forward(100) left(120) mainloop()
true
fe892de04ecbf1e806c4669f14b582fd1a801564
qodzero/icsv
/icsv/csv
578
4.15625
4
#!/usr/bin/env python3 import csv class reader(obj): ''' A simple class used to perform read operations on a csv file. ''' def read(self, csv_file): ''' simply read a csv file and return its contents ''' with open(csv_file, 'r') as f: cs = csv.reader(f) cs = [row for row in cs] df = dict() for key in cs[0]: df[key] = [] df_keys = [key for key in df.keys()] for row in cs[1: ]: for i, col in enumerate(row): df[df_keys[i]].append(col) return df
true
8b9059649cbaad48bb6b53fa8a4624eb9b5819a9
aha1464/lpthw
/ex21.py
2,137
4.15625
4
# LPTHW EX21 # defining the function of add with 2 arguments. I add a and b then return them def add(a, b): print(f"ADDING {a} + {b}") return a + b # defining the function of subtract def subtract(a, b): print(f"SUBTRACKTING {a} - {b}") return a - b # defining the function of multiply def multiply(a, b): print(f"MULTIPLING {a} * {b}") return a * b # defining the function of divide def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b # print the text in the string and add a new line print(f"let's do some math with just functions!\n") # defining age, height, weight & iq by addition, subraction, multiplying and # dividing with the (the values, required) age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) # print the text with their {variable} print(f"Age: {age}, Height {height}, Weight {weight}, IQ {iq}\n") # a puzzle for the extra credit, type it in anyway # print the text below in the terminal print(f"Here is the puzzle.") # WTF, I have no idea??? Inside out: (iq, 2)(/ weight)(multiply by height) #(subtract age) add # 50/2 = 25 # 180 * 24 = 4500 # 74 - 4500 # 35 + -4426 = -4391 # what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print("That becomes: ", what, "Can you do it by hand?") print("24 + 34 / 100 - 1023") # Extra Credit: # 1. If you aren't really sure what return does, try writing a few of your own # functions and have them return some values. You can return anything that you # can put to the reight of an = # 2. At the end of hte script is a puzzle. I'm taking th return value of one # function and using it as the argument of an other funtion. I'm doing this in # a chain so that I'm kind of creating a formula using the function. It looks # really weird, but if you run the sript, you can see the results. # 3. Once you have the formula worked out for the puzzle, get in there and see # what happens when you modify the parts of the functions. Try to change it on # purpose to make another value. # 4. Do the inverse. Write a simsple forumula and use the functions in the # same way to calculate it.
true
6345bac40a37f7811ffd2cf6b011e339bdd072f7
aha1464/lpthw
/ex16.py
1,371
4.25
4
# import = the feature argv = argument variables sys = package from sys import argv # script, filename = argv # printed text that is shown to the user when running the program print(f"We're going to erase (filename).") print("If you don't want that, hit CTRL-C (^c).") print("If you do want that, hit RETURN.") # input = user input required ("prompt text goes here") input("?") # prints ("the text") print("Opening the file...") # target = open(user inputed filename in the terminal) 'W' says open this file in 'write mode' target = open(filename, 'w') # prints ("the text here") print("Truncating the file. Goodbye!") # target command truncate: empties the file. target.truncate() # prints("the text" in the terminal) print("Now I'm going to ask you for three lines.") # # line1 is the id and input gives the command that the user needs to input info line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: " # prints ("the text" in the terminal) print("I'm going to write these to the file.") # target.write(the text the user inputs in the terminal when prompted) target.write(line1) # using ("\n") starts a new line target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") # print the ("text") print("And finally, we close it.") # targer.close() closes and saves the file that has been created target.close()
true
3af1f947862099145d100d986ad158586368d47b
thetrashprogrammer/StartingOutWPython-Chapter3
/fat_and_carbs.py
1,491
4.375
4
# Programming Exercise 3.7 Calories from Fat and Carbohydrates # May 3rd, 2010 # CS110 # Amanda L. Moen # 7. Calories from Fat and Carbohydrates # A nutritionist who works for a fitness club helps members by # evaluating their diets. As part of her evaluation, she asks # members for the number of fat grams and carbohydrate grams # that they consumed in a day. Then, she calculates the number # of calories that result from the fat, using the following # formula: # calories from fat = fat grams X 9 # Next, she calculates the number of calories that result from # the carbohydrates, using the following formula: # calories from carbs = carb grams X 4 # The nutritionist asks you to write a program that will make # these calculations. def main(): # Ask for the number of fat grams. fat_grams = input('Enter the number of fat grams consumed: ') fat_calories(fat_grams) # Ask for the number of carb grams. carb_grams = input('Enter the number of carbohydrate grams consumed: ') carb_calories(carb_grams) def fat_calories(fat_grams): # Calculate the calories from fat. # calories_from_fat = fat_grams*9 calories_from_fat = fat_grams * 9 print 'The calories from fat are', calories_from_fat def carb_calories(carb_grams): # Calculate the calories from carbs. # calories_from_carbs = carb_grams * 4 calories_from_carbs = carb_grams * 4 print 'The calories from carbohydrates are', calories_from_carbs # Call the main function. main()
true
7dcc48ffebb1ae534fa973cab9d70c77e7b7a610
wade-sam/variables
/Second program.py
245
4.15625
4
#Sam Wade #09/09/2014 #this is a vaiable that is storing th value entered by the user first_name = input("please enter your first name: ") print(first_name) #this ouputs the name in the format"Hi Sam!" print("Hi {0}!".format(first_name))
true
d490e1f73448f32eb150b3994f359cffb155acc4
pankhurisri21/100-days-of-Python
/variables_and_datatypes.py
548
4.125
4
#variables and datatypes #python variables are case sensitive print("\n\nPython variables are case sensitive") a=20 A=45 print("a =",a) print("A =",A) a=20#integer b=3.33 #float c="hello" #string d=True #bool #type of value print("Type of different values") print("Type of :",str(a)+" =",type(a)) print("Type of :",str(b)+" =",type(b)) print("Type of : "+str(c)+ " =",type(c)) print("Type of : "+str(d)+" =",type(d)) #Type conversion print("New Type of:",a,end=" = ") print(type(str(a))) print("New Type of:",b,end=" = ") print(type(int(b)))
true
d9f185d9097e1341c3769d693c9976e25eea6d23
HeWei-imagineer/Algorithms
/Leetcode/hanoi.py
591
4.15625
4
#关于递归函数问题: def move_one(num,init,des): print('move '+str(num)+' from '+init+' to '+des) print('---------------------------------') def hanoi(num,init,temp,des): if num==1: move_one(num,init,des) else: hanoi(num-1,init,des,temp) move_one(num,init,des) hanoi(num-1,temp,init,des) # 一件很难的事,我可以完成其中一小步,剩下的交给第二个人做。 # 第二个人接到任务时,想我可以完成其中一小步,剩下的交给第三个人做。... # 直到任务最后被分解成简单的一小步。
false
b2eb51f1c07dc6b03bd49499e392191e4578a2ed
rbk2145/DataScience
/9_Manipulating DataFrames with pandas/2_Advanced indexing/1_Index objects and labeled data.py
814
4.4375
4
####Index values and names sales.index = range(len(sales)) ####Changing index of a DataFrame # Create the list of new indexes: new_idx new_idx = [month.upper() for month in sales.index] # Assign new_idx to sales.index sales.index = new_idx # Print the sales DataFrame print(sales) ######Changing index name labels # Assign the string 'MONTHS' to sales.index.name sales.index.name = 'MONTHS' # Print the sales DataFrame print(sales) # Assign the string 'PRODUCTS' to sales.columns.name sales.columns.name = 'PRODUCTS' # Print the sales dataframe again print(sales) ####Building an index, then a DataFrame # Generate the list of months: months months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # Assign months to sales.index sales.index = months # Print the modified sales DataFrame print(sales)
true
c31cfdfc797c4f40d719d1ef28549059c291c76f
SandjayRJ28/Python
/Python Ep 03 Strings.py
1,539
4.21875
4
#Variablen defineren gaat heel makkelijk heeft het een naam en waarde het its done Voor_naam = "Sandjay" print(Voor_naam) #Je kan stringe combineren met + Achter_naam = "Jethoe" print(Voor_naam + Achter_naam) print("Hallo" + Voor_naam + "" + Achter_naam) #Je kan functies gebruiken om je string aan te passen zin = "Ik kan eindelijke een beetje Pyhton" print(zin.upper()) print(zin.lower()) print(zin.capitalize()) print(zin.count("a")) #De functies helpen on om de tekste een opmaak te geven om het op te slaan naar bestanden,Databases of om aan gebruikers te laten zien. print("Hallo" + Voor_naam.capitalize() + " \n" + Achter_naam.capitalize()) #verschillende string oefeningen met tab voor autocomplete print(Voor_naam + Achter_naam) print("Hallo, " + Voor_naam + " " + Achter_naam) #input geven via de console V_naam = input("Vul hier jou naam is ") A_naam = input("Vul hier jou Achternaam in ") print("Hallo, " + V_naam.capitalize() + " " + A_naam.capitalize()) #String formatting output = "Hallo, " + V_naam + " " + A_naam output = "Hallo, {} {} ".format(V_naam, A_naam) output = "Hallo, {0} {1} ".format(V_naam, A_naam) #Deze formatting is alleen in Python 3 beschikbaar output = f'Hallo, {V_naam} {A_naam}' #String formatting Part 2 V2_naam = "Sandjay" A2_naam = "Jethoe" output = "Hallo, " + V2_naam + " " + A2_naam output2 = "Hallo, {} {} ".format(V2_naam, A2_naam) output3 = "Hallo, {0}, {1} ".format(V2_naam, A2_naam) output4 = f'Hallo, {V2_naam} {A2_naam}' print(output) print(output2) print(output3) print(output4)
false
a991555e799064d6a89f9c0c1cc460fcf41ce8ea
TazoFocus/UWF_2014_spring_COP3990C-2507
/notebooks/scripts/cli.py
664
4.21875
4
# this scripts demonstrates the command line input # this works under all os'es # this allows us to interact with the system import sys # the argument list that is passed to the code is stored # in a list called sys.argv # this list is just like any list in python so you should treat it as such cli_list = sys.argv # how many elements is in the list? print 'The length of my cli list is: ', len(cli_list) # what is the list of arguments? print 'Here is my list: ', cli_list # what is the first element? print 'this is the name of my python file: ', cli_list[0] # how about the rest of the elements for cli_element in cli_list[1:]: print cli_element
true
f68f8aaf53e834b5b3297a2852518edba06ebbe0
denrahydnas/SL9_TreePy
/tree_while.py
1,470
4.34375
4
# Problem 1: Warm the oven # Write a while loop that checks to see if the oven # is 350 degrees. If it is, print "The oven is ready!" # If it's not, increase current_oven_temp by 25 and print # out the current temperature. current_oven_temp = 75 # Solution 1 here while current_oven_temp < 350: print("The oven is at {} degrees".format(current_oven_temp)) current_oven_temp += 25 else: print("The oven is ready!") # Problem 2: Total and average # Complete the following function so that it asks for # numbers from the user until they enter 'q' to quit. # When they quit, print out the list of numbers, # the sum and the average of all of the numbers. def total_and_average(): numbers = [] while True: add = input("Please give me a number, or type 'q' to quit: ").lower() if add == 'q': break try: numbers.append(float(add)) except ValueError: continue print("You entered: ", numbers) print("The total is: ", sum(numbers)) print("The average is: ", sum(numbers)/len(numbers)) total_and_average() # Problem 3: Missbuzz # Write a while loop that increments current by 1 # If the new number is divisible by 3, 5, or both, # print out the number. Otherwise, skip it. # Break out of the loop when current is equal to 101. current = 1 # Solution 3 here while current < 101: if not current % 3 or current % 5 == 0: print(current) current += 1
true
78c6cd735ab26eabf91d6888118f9e5ec1320ccf
denrahydnas/SL9_TreePy
/tree_calc.py
746
4.28125
4
# Step 1 # Ask the user for their name and the year they were born. name = input("What is your name? ") ages = [25, 50, 75, 100] from datetime import date current_year = (date.today().year) while True: birth_year = input("What year were you born? ") try: birth_year = int(birth_year) except ValueError: continue else: break current_age = current_year - birth_year # Step 2 # Calculate and print the year they'll turn 25, 50, 75, and 100. for age in ages: if age > current_age: print("Congrats, Sandy! You will be {} in {}.".format(age, (birth_year+age))) # Step 3 # If they're already past any of these ages, skip them. print("You will turn {} this calendar year.".format(current_age))
true
528a622f441ed7ac306bc073548ebdf1e399271e
prabhus489/Python_Bestway
/Length_of_a_String.py
509
4.34375
4
def len_string(): length = 0 flag = 1 while flag: flag = 0 try: string = input("Enter the string: ") if string.isspace()or string.isnumeric(): print("Enter a valid string") flag = 1 except ValueError: print("Enter a Valid input") flag = 1 for x in string: length += 1 return length str_length = len_string() print("The length of the string is: ", str_length)
true
b0a74a6e2ce7d3392643479ebbd4280ec9ce554e
HelloYeew/helloyeew-computer-programming-i
/Fibonacci Loop.py
611
4.125
4
def fib(n): """This function prints a Fibonacci sequence up to the nth Fibonacci """ for loop in range(1,n+1): a = 1 b = 1 print(1,end=" ") if loop % 2 != 0: for i in range(loop // 2): print(a,end=" ") b = b + a print(b,end=" ") a = a + b print() else: for i in range((loop // 2) - 1): print(a,end=" ") b = b + a print(b,end=" ") a = a + b print(a,end=" ") print()
false
3dd5303392fe607aa21e7cefce97426d59b90e49
HelloYeew/helloyeew-computer-programming-i
/OOP_Inclass/Inclass_Code.py
1,881
4.21875
4
class Point2D: """Point class represents and operate on x, y coordinate """ def __init__(self,x=0,y=0): self.x = x self.y = y def disance_from_origin(self): return (self.x*self.x + self.y*self.y)**0.5 def halfway(self, other): halfway_x = (other.x - self.x) / 2 halfway_y = (other.y - self.y) / 2 return Point2D(halfway_x,halfway_y) def __str__(self): return "[{0}, {1}]".format(self.x, self.y) # p = Point2D() # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) # p.x = 3 # p.x = 4 # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) # p = Point2D(10,20) # print("x coor of p is ", p.x) # print("y coor of p is ", p.y) p = Point2D(5, 12) print(p) q = Point2D(3, 4) print(q) distance_from_p_to_origin = p.disance_from_origin() p = Point2D() print(distance_from_p_to_origin) print() class Rectangle: """ Rectangle class represents a rectangle object with its size and location """ def __init__(self,point,width,height): self.corner = point self.width = width self.height = height def area(self): return self.width * self.height def grow(self, delta_width, delta_height): self.width += delta_width self.height += delta_height def move(self,dx,dy): self.corner.x += dx self.corner.y += dy def __str__(self): return "[{0}, {1}, {2}]".format(self.corner,self.width,self.height) box1 = Rectangle(5, 10, 5) print(box1) box2 = Rectangle(Point2D(20,30),100,200) print(box2) print("area of box1 is", box1.area()) print("area of box2 is", box2.area()) box1.grow(30,10) box1.move(2,3) print(box1, box1.area()) class Player: def __init__(self,name,num_wins,num_plays): self.name = name self.num_wins = num_wins self.num_plays = num_plays def
false
6c43b0598523c3590ba54dfc962af52baa71074f
thevindur/Python-Basics
/w1790135 - ICT/Q1A.py
459
4.125
4
n1=int(input("Enter the first number: ")) n2=int(input("Enter the second number: ")) n3=int(input("Enter the third number: ")) #finding the square values s1=n1*n1 s2=n2*n2 s3=n3*n3 #finding the cube values c1=n1*n1*n1 c2=n2*n2*n2 c3=n3*n3*n3 #calculating the required spaces for the given example x=" "*5 x1=" "*4 y=" "*5 y1=" "*4 z=" "*3 print("\n") print("Number"+"\t"+"Square"+"\t"+"Cube") print(n1,x,s1,y,c1) print(n2,x,s2,y1,c2) print(n3,x1,s3,z,c3)
false
604a599edc09ff277520aadd1bb79fb8157272ee
pallu182/practise_python
/fibonacci_sup.py
250
4.125
4
#!/usr/bin/python num = int(raw_input("Enter the number of fibonacci numbers to generate")) if num == 1: print 1 elif num == 2: print 1,"\n", 1 else: print 1 print 1 a = b = 1 for i in range(2,num): c = a + b a = b b = c print c
true
ca5d8a47171f6b1fbc2d53f6648da8f0a6b9e900
km1414/Courses
/Computer-Science-50-Harward-University-edX/pset6/vigenere.py
1,324
4.28125
4
import sys import cs50 def main(): # checking whether number of arguments is correct if len(sys.argv) != 2: print("Wrong number of arguments!") exit(1) # extracts integer from input key = sys.argv[1] if not key.isalpha(): print("Wrong key!") exit(2) # text input from user text = cs50.get_string("plaintext: ") print("ciphertext: ", end = "") # cursor for key cursor = 0 # iterating over all characters in string for letter in text: # if character is alphabetical: if letter.isalpha(): # gets number for encryption from key number = ord(key[cursor % len(key)].upper()) - ord('A') cursor += 1 # if character is uppercase: if letter.isupper(): print(chr((ord(letter) - ord('A') + number) % 26 + ord('A')), end = "") # if character is lowercase: else: print(chr((ord(letter) - ord('a') + number) % 26 + ord('a')), end = "") # if character is non-alphabetical: else: print(letter, end = "") # new line print() # great success exit(0) # executes function if __name__ == "__main__": main()
true
5885ab9f922b74f75ae0ef3af2f1f0d00d2cd087
sheilapaiva/LabProg1
/Unidade8/agenda_ordenada/agenda_ordenada.py
621
4.125
4
#coding: utf-8 #UFCG - Ciência da Computação #Programação I e laboratório de Programação I #Aluna: Sheila Maria Mendes Paiva #Unidade: 8 Questão: Agenda Ordenada def ordenar(lista): ta_ordenado = True while ta_ordenado == True: ta_ordenado = False for i in range(len(lista) -1): if lista[i] > lista[i + 1]: lista[i], lista[i + 1] = lista[i + 1], lista[i] ta_ordenado = True break return lista agenda = [] while True: nome = raw_input() if nome == "####": break agenda.append(nome) ordenar(agenda) for i in agenda: if i == nome: print "* %s" % nome else: print i print "----"
false
b87e9b3fa5910c2f521321d84830411b624e0c39
SDSS-Computing-Studies/005a-tuples-vs-lists-AlexFoxall
/task2.py
569
4.15625
4
#!python3 """ Create a variable that contains an empy list. Ask a user to enter 5 words. Add the words into the list. Print the list inputs: string string string string string outputs: string example: Enter a word: apple Enter a word: worm Enter a word: dollar Enter a word: shingle Enter a word: virus ['apple', 'worm', 'dollar', 'shingle', 'virus'] """ t1 = input("Enter a word").strip() t2 = input("Enter a word").strip() t3 = input("Enter a word").strip() t4 = input("Enter a word").strip() t5 = input("Enter a word").strip() x = [t1, t2, t3, t4, t5] print(x)
true
25e432397ff5acb6a55406866813d141dc3ba2c2
jyu001/New-Leetcode-Solution
/solved/248_strobogrammatic_number_III.py
1,518
4.15625
4
''' 248. Strobogrammatic Number III DescriptionHintsSubmissionsDiscussSolution A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. Example: Input: low = "50", high = "100" Output: 3 Explanation: 69, 88, and 96 are three strobogrammatic numbers. Note: Because the range might be a large number, the low and high numbers are represented as string. ''' class Solution: def findallStro(self, n): if n==0: return [] if n==1: return ['1','0','8'] if n==2: return ['00',"11","69","88","96"] res = [] if n>2: listn = self.findallStro(n-2) for s in listn: res.extend(['1'+s+'1', '0'+s+'0', '6'+s+'9','9'+s+'6','8'+s+'8']) return res def strobogrammaticInRange(self, low, high): """ :type low: str :type high: str :rtype: int """ n = len(high) numl, numh = int(low), int(high) res = [] for i in range(n+1): res.extend(self.findallStro(i)) #newres = [] count = 0 for s in res: if len(s)!= 1 and s[0] == '0': continue num = int(s) #print(s, numl, numh) if num >= numl and num <= numh: #newres.append(s) count += 1 #print (count, newres) return count
true
f73472838e6ab97b564a1a0a179b7b2f0667a007
Namrata-Choudhari/FUNCTION
/Q3.Sum and Average.py
228
4.125
4
def sum_average(a,b,c): d=(a+b+c) e=d/3 print("Sum of Numbers",d) print("Average of Number",e) a=int(input("Enter the Number")) b=int(input("Enter the Number")) c=int(input("Enter the Number")) sum_average(a,b,c)
true
b6c0dc8523111386006a29074b02d1691cf1e054
shivigupta3/Python
/pythonsimpleprogram.py
1,709
4.15625
4
#!/usr/bin/python2 x=input("press 1 for addition, press 2 to print hello world, press 3 to check whether a number is prime or not, press 4 for calculator, press 5 to find factorial of a number ") if x==1: a=input("enter first number: ") b=input("enter second number: ") c=a+b print ("sum is ",c) if x==2: print("Hello World") if x==3: num=int(input("enter a number to check whether its prime or not")) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") else: print(num,"is a prime number") else: print(num,"is not a prime number") if x==4: print("CALCULATOR") def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = int(input("Enter choice(1/2/3/4):")) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print "invalid input" if x==5: num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial)
true
9aa1b81bcb80494ea9b0c0b4a728a3981723fa43
eecs110/winter2019
/course-files/practice_exams/final/dictionaries/01_keys.py
337
4.40625
4
translations = {'uno': 'one', 'dos': 'two', 'tres': 'three'} ''' Problem: Given the dictionary above, write a program to print each Spanish word (the key) to the screen. The output should look like this: uno dos tres ''' # option 1: for key in translations: print(key) # option 2: for key in translations.keys(): print(key)
true
0fa9fae44540b84cb863749c8307b805e3a8d817
eecs110/winter2019
/course-files/lectures/lecture_03/demo00_operators_data_types.py
327
4.25
4
# example 1: result = 2 * '22' print('The result is:', result) # example 2: result = '2' * 22 print('The result is:', result) # example 3: result = 2 * 22 print('The result is:', result) # example 4: result = max(1, 3, 4 + 8, 9, 3 * 33) # example 5: from operator import add, sub, mul result = sub(100, mul(7, add(8, 4)))
true
b485405967c080034bd232685ee94e6b7cc84b4f
eecs110/winter2019
/course-files/practice_exams/final/strings/11_find.py
1,027
4.28125
4
# write a function called sentence that takes a sentence # and a word as positional arguments and returns a boolean # value indicating whether or not the word is in the sentence. # Ensure that your function is case in-sensitive. It does not # have to match on a whole word -- just part of a word. # Below, I show how I would call your function and what it would # output to the screen. def is_word_in_sentence(sentence, char_string): if char_string.lower() in sentence.lower(): return True return False def is_word_in_sentence_1(sentence, char_string): if sentence.lower().find(char_string.lower()) != -1: return True return False print('\nMethod 1...') print(is_word_in_sentence('Here is a fox', 'Fox')) print(is_word_in_sentence('Here is a fox', 'bird')) print(is_word_in_sentence('Here is a fox', 'Ox')) print('\nMethod 2...') print(is_word_in_sentence_1('Here is a fox', 'Fox')) print(is_word_in_sentence_1('Here is a fox', 'bird')) print(is_word_in_sentence_1('Here is a fox', 'Ox'))
true
40c91a64b489ecc92af2ee651c0ec3b48eba031e
amandameganchan/advent-of-code-2020
/day15/day15code.py
1,999
4.1875
4
#!/bin/env python3 """ following the rules of the game, determine the nth number spoken by the players rules: -begin by taking turns reading from a list of starting numbers (puzzle input) -then, each turn consists of considering the most recently spoken number: -if that was the first time the number has been spoken, the current player says 0 -otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. """ import sys import re from collections import defaultdict def solution(filename,final_turn): # read in input data data = [] with open(filename) as f: for x in f: data.append(x.strip().split(',')) return getTurn(data,int(final_turn)) def getTurn(data,final_turn): """ simulate playing the game to determine the number spoken at turn final_turn Args: data (list): first starting numbers final_turn (int): desired turn to stop at Returns: int: number spoken aloud at that turn """ finalTurns = [] # do for each set in data for starterset in data: # get number of nums in starter set nums = len(starterset) # keep track of: # current turn number turn = 0 # last 2 turns any number was spoken on (if any) lastTurn = {} nextTurn = {} lastVal = -1 # iterate until desired turn while turn < final_turn: # part 1: 2020, part 2: 30000000 # first starting numbers if turn < nums: currVal = int(starterset[turn]) # subsequent turns else: currVal = nextTurn[lastVal] if currVal in lastTurn.keys(): nextTurn[currVal] = turn-lastTurn[currVal] else: nextTurn[currVal] = 0 lastTurn[currVal] = turn lastVal = currVal turn += 1 finalTurns.append(lastVal) return finalTurns[0] if __name__ == '__main__': if len(sys.argv) < 3: print("Usage: python3 day15code.py <data-file> <turn-number>") sys.exit(1) number = solution(sys.argv[1],sys.argv[2]) print("{} will be the {}th number spoken".format(number,sys.argv[2]))
true
1321c47e1ea033a5668e940bc87c8916f27055e3
Tejjy624/PythonIntro
/ftoc.py
605
4.375
4
#Homework 1 #Tejvir Sohi #ECS 36A Winter 2019 #The problem in the original code is that 1st: The user input must be changed #into int or float. Float would be the best choice since there are decimals to #work with. The 2nd problem arised due to an extra slash when defining ctemp. #Instead of 5//9, it should be 5/9 to show 5 divided by 9 #User enters temp in fahrenheit ftemp = float(input("Enter degrees in Fahrenheit:")) #Formula calculates the temp in degrees C ctemp = (5/9)*(ftemp - 32) #Summarizes what the temps are print(ftemp, "degrees Fahrenheit is", ctemp, "degrees centigrade")
true
44d18b17cdd57a20036f12ec231ce8d9ec1f7157
Mgomelya/Study
/Алгоритмы/Очередь.py
2,073
4.1875
4
# Очередь основана на концепции FIFO - First in First out class Queue: # Очередь на кольцевом буфере, Сложность: O(1) def __init__(self, n): self.queue = [None] * n self.max_n = n self.head = 0 self.tail = 0 self.size = 0 # В пустой очереди и голова, и хвост указывают на ячейку с индексом 0 def is_empty(self): return self.size == 0 def push(self, x): if self.size != self.max_n: self.queue[self.tail] = x self.tail = (self.tail + 1) % self.max_n self.size += 1 # Хвост всегда указывает на первую свободную для записи ячейку, # а голова — на элемент, добавленный в очередь раньше всех остальных def pop(self): if self.is_empty(): return None x = self.queue[self.head] self.queue[self.head] = None self.head = (self.head + 1) % self.max_n self.size -= 1 return x def peek(self): # Вернуть первый элемент if self.is_empty(): return None return self.queue[self.head] def get_size(self): return self.size q = Queue(8) q.push(1) print(q.queue) # [1, None, None, None, None, None, None, None] print(q.size) # 1 q.push(-1) q.push(0) q.push(11) print(q.queue) # [1, -1, 0, 11, None, None, None, None] print(q.size) # 4 q.pop() print(q.queue) # [None, -1, 0, 11, None, None, None, None] print(q.size) # 3 q.pop() q.pop() q.push(-8) q.push(7) q.push(3) q.push(16) print(q.queue) # [None, None, None, 11, -8, 7, 3, 16] print(q.size) # 5 q.push(12) # Когда пытаемся переполнить очередь, хвост будет указывать на след ячейку по часовой стрелке - 0 print(q.queue) # [12, None, None, 11, -8, 7, 3, 16] print(q.size) # 6
false
169a92be719041be83c4a446467626148d4ca1d2
Mgomelya/Study
/Алгоритмы/Связный_список.py
1,794
4.28125
4
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def print_linked_list(node): while node: print(node.value, end=" -> ") node = node.next print("None") # У каждого элемента есть значение и ссылка на следующий элемент списка n3 = Node('third') n2 = Node('second', n3) n1 = Node('first', n2) print_linked_list(n1) # вершина n1 print_linked_list(n2) # вершина n2 def get_node_by_index(node, index): while index: node = node.next index -= 1 return node # Добавление нового элемента по индексу def insert_node(head, index, value): new_node = Node(value) if index == 0: new_node.next = head return new_node previous_node = get_node_by_index(head, index - 1) new_node.next = previous_node.next previous_node.next = new_node return head node, index, value = n1, 2, 'new_node' head = insert_node(node, index, value) print_linked_list(head) # Удаление элемента по индексу def del_node(head, index): if index == 0: head = get_node_by_index(head, 1) return head previous_node = get_node_by_index(head, index - 1) next_node = get_node_by_index(head, index + 1) previous_node.next = next_node return head node, index = n1, 2 head = del_node(node, index) print_linked_list(head) # Поиск индекса по значению def find_val(node, value): index = 0 while node: if node.value == value: return index node = node.next index += 1 else: return -1 head, value = n1, 'third' print(find_val(head, value))
false
eb0494758c0e4976095ade36025341d9cb3a7131
melnikovay/U2
/u2_z8.py
692
4.15625
4
#Посчитать, сколько раз встречается определенная цифра в #введенной последовательности чисел. Количество вводимых чисел и цифра, #которую необходимо посчитать, задаются вводом с клавиатуры. n = int(input('Введите последовательность натуральных чисел ')) c = int (input ('Введите цифру от 0 до 9 ')) k = 0 while n > 0: x = n % 10 n = n // 10 if c == x: k = k + 1 print ('Цифра' ,c ,'встречается в числе', k ,'раз')
false
a1dd8790cc6d7ed8a519d9cb009616e3897760d7
wlizama/python-training
/decoradores/decorator_sample02.py
651
4.15625
4
""" Decorador con parametros """ def sum_decorator(exec_func_before=True): def fun_decorator(func): def before_func(): print("Ejecutando acciones ANTES de llamar a función") def after_func(): print("Ejecutando acciones DESPUES de llamar a función") def wrapper(*args, **kwargs): if exec_func_before: before_func() func(*args, **kwargs) after_func() return wrapper return fun_decorator @sum_decorator(exec_func_before=False) def suma_simple(num1, num2): print("Suma simple: {}".format(num1 + num2)) suma_simple(35, 80)
false
4b11d8d1ea2586e08828e69e9759da9cd60dda23
petermooney/datamining
/plotExample1.py
1,798
4.3125
4
### This is source code used for an invited lecture on Data Mining using Python for ### the Institute of Technology at Blanchardstown, Dublin, Ireland ### Lecturer and presenter: Dr. Peter Mooney ### email: peter.mooney@nuim.ie ### Date: November 2013 ### ### The purpose of this lecture is to provide students with an easily accessible overview, with working ### examples of how Python can be used as a tool for data mining. ### For those using these notes and sample code: This code is provided as a means of showing some basic ideas around ### data extraction, data manipulation, and data visualisation with Python. ### The code provided could be written in many different ways as is the Python way. However I have tried to keep things simple and practical so that students can get an understanding of the process of data mining rather than this being a programming course in Python. ### ### If you use this code - please give me a little citation with a link back to the GitHub Repo where you found this piece of code: https://github.com/petermooney/datamining import matplotlib.pyplot as plt # this is a simple example of how to draw a pie chart using Python and MatplotLib # You will need matplotlit installed for this to work. def drawSamplePieChartPlot(): # we have 5 lecturers and we have the number of exam papers which # each of the lecturers have had to mark. lecturers = ['Peter','Laura','James','Jennifer','Patrick'] examPapersMarked = [14, 37, 22, 16,80] colors = ['purple', 'blue', 'green', 'yellow','red'] plt.pie(examPapersMarked, labels=lecturers, colors=colors,autopct='%1.1f%%',startangle=90) plt.axis('equal') # We are going to then save the pie chart as a PNG image file (nice for the web) plt.savefig("PieChartExample.png") def main(): drawSamplePieChartPlot() main()
true
6187d788dd3f6fc9b049ded6d08189e6bb8923ed
lflores0214/Sorting
/src/iterative_sorting/iterative_sorting.py
1,583
4.34375
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements print(arr) for i in range(0, len(arr) - 1): # print(f"I: {i}") cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(cur_index, len(arr)): # check if the array at j is less than the current smallest index # print(f"J: {j}") # print(arr) if arr[j] < arr[smallest_index]: # if it is j becomes the smallest index smallest_index = j # TO-DO: swap arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index] # print(arr) return arr my_arr = [1, 5, 8, 4, 2, 9, 6, 0, 7, 3] # print(selection_sort(my_arr)) # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): # loop through array # print(arr) for i in range(len(arr)-1): # check if the element at current index is greater than the element to the right # print(arr) for j in range(len(arr)-1): if arr[j] > arr[j+1]: # if it is than swap the two elements arr[j], arr[j+1] = arr[j+1], arr[j] # run loop again until they are all sorted print(arr) # bubble_sort(arr) return arr print(bubble_sort(my_arr)) # print(f"bubble: {bubble_sort(my_arr)}") # STRETCH: implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
true
168a9554f9d16b23e68dac5a254354c0c9e4be10
vinodhinia/CompetitiveCodingChallengeInPython
/Stacks/MinStackOptimal.py
1,172
4.15625
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min_stack = [] def push(self, x): """ :type x: int :rtype: void """ if len(self.stack) == 0 and len(self.min_stack) == 0: self.min_stack.append(x) elif len(self.min_stack) != 0 and x <= self.min_stack[-1]: self.min_stack.append(x) self.stack.append(x) def pop(self): """ :rtype: void """ if len(self.min_stack) != 0 and len(self.stack) !=0 and self.stack[-1] == self.min_stack[-1]: self.min_stack.pop() self.stack.pop() def top(self): """ :rtype: int """ return self.stack[-1] def getMin(self): """ :rtype: int """ return self.min_stack[-1] if len(self.min_stack) !=0 else None minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) print(minStack.getMin()) #--> Returns -3. minStack.pop() print(minStack.top()) #--> Returns 0. print(minStack.getMin()) #--> Returns -2.
false
34517c82223ec7e295f5139488687615eef77d56
devineni-nani/Nani_python_lerning
/Takung input/input.py
1,162
4.375
4
'''This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python.''' #input() use roll_num= input("enter your roll number:") print (roll_num) ''' How the input function works in Python : When input() function executes program flow will be stopped until the user has given an input. The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional. Whatever you enter as input, input function convert it into a string. if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting. for example: ''' num=input("enter an number:") print (num) name = input ("enter your name:") print (name) #Printing type of input value print ("type of num", type(num)) print ("type of name:", type(name)) num1=type(num) print ("after typecasting num type:", type(num1))
true
75b4292c4e85d8edd136e7bf469c60e9222e383f
Dragonriser/DSA_Practice
/Binary Search/OrderAgnostic.py
847
4.125
4
""" Given a sorted array of numbers, find if a given number ‘key’ is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates. Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1. Example 1: Input: [4, 6, 10], key = 10 Output: 2 """ #CODE: def orderAgnostic(arr, target): length = len(arr) ascending = False if arr[0] < arr[length - 1]: ascending = True lo, hi = 0, length - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if arr[mid] == target: return mid else: if ascending: if arr[mid] < target: lo = mid + 1 else: hi = mid - 1 else: if arr[mid] < target: hi = mid - 1 else: lo = mid + 1 return -1
true
d6b9c248126e6027e39f3f61d17d8a1a73f687b0
Dragonriser/DSA_Practice
/LinkedLists/MergeSortedLists.py
877
4.1875
4
#QUESTION: #Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. #APPROACH: #Naive: Merge the linked Lists and sort them. #Optimised: Traverse through lists and add elements to new list according to value, since both lists are in increasing order. Time & Space complexity: O(n + m) #CODE: class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 and not l2: return None merged = cur = ListNode() while l1 and l2: if l1.val <= l2.val: cur.next = l1 l1 = l1.next elif l2.val <= l2.val: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return merged.next
true
f0438d1379df6974702dc34ef108073385a3877e
Nightzxfx/Pyton
/function.py
1,069
4.1875
4
def square(n): """Returns the square of a number.""" squared = n ** 2 print "%d squared is %d." % (n, squared) <--%d because is comming from def (function) return squared # Call the square function on line 10! Make sure to # include the number 10 between the parentheses. square(10) -------------------------- def power(base, exponent): # Add your parameters here! result = base ** exponent print "%d to the power of %d is %d." % (base, exponent, result) power(37, 4) # Add your arguments here! ------------------------------- def one_good_turn(n): return n + 1 def deserves_another(m): return one_good_turn(m) + 2 <0 use the result of the frist funciton to apply in the second --------------------------- def cube(number): return number * number * number def by_three(number): if number % 3 == 0: <-- if the number is devided by 3 return cube(number) else: return False ----------------- def distance_from_zero(p): if type(p) == int or type(p) == float: return abs(p) else: return "Nope"
true
12188e81219abc09fc9e995f00ec54a52b605166
Wasylus/lessons
/lesson12.py
1,117
4.4375
4
# print(int(bmi)) # # 1. What if bmi is 13 # # 2. What if bmi is 33 # if bmi <= 18: # print("Your BMI is 18, you are underweight.") # elif bmi >= 22: # print("Your BMI is 22, you have a normal weight.") # elif bmi >= 28: # print("Your BMI is 28, you are slightly overweight.") # elif bmi >= 33: # print("Your BMI is 33, you are obese.") # print("Your BMI is 40, you are clinically obese.") # result = int(bmi) # print(result) def calculate_bmi(weight: float, height: float) -> float: return weight / height ** 2 def bmi_to_str(bmi: int) -> str: if bmi < 18: return "underweight" elif bmi < 25: return "normal weight" elif bmi < 30: return "overweight" elif bmi < 35: return "obese" else: return "clinically obese" # Homework: check math.ceil, math.floor, math.round height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi = calculate_bmi(weight, height) bmi_repr = bmi_to_str(bmi) msg = f"Your bmi is {int(bmi)}, you are {bmi_repr}" print(msg)
false
553e1903b680207d1c0e956b7b881692609834a3
OJ13/Python
/Udemy/Iniciantes/condicionais.py
400
4.1875
4
numero = 1 if(numero == 1): print("Numero é igual a um") if(numero == 2) : print("Número é igual a Dois") numero = 3 if(numero == 1): print("Numero é igual a um") else: print("Número não é igual a um") nome = "Junior" if("z" in nome) : print("Contém 'Z' no nome") elif("o" in nome) : print("Contém 'o' no nome") else: print("Não contém nem Z nem O")
false
c7eed0a9bee1a87a3164f81700d282d1370cebdb
philuu12/PYTHON_4_NTWK_ENGRS
/wk1_hw/Solution_wk1/ex7_yaml_json_read.py
835
4.3125
4
#!/usr/bin/env python ''' Write a Python program that reads both the YAML file and the JSON file created in exercise6 and pretty prints the data structure that is returned. ''' import yaml import json from pprint import pprint def output_format(my_list, my_str): ''' Make the output format easier to read ''' print '\n\n' print '#' * 3 print '#' * 3 + my_str print '#' * 3 pprint(my_list) def main(): ''' Read YAML and JSON files. Pretty print to standard out ''' yaml_file = 'my_test.yml' json_file = 'my_test.json' with open(yaml_file) as f: yaml_list = yaml.load(f) with open(json_file) as f: json_list = json.load(f) output_format(yaml_list, ' YAML') output_format(json_list, ' JSON') print '\n' if __name__ == "__main__": main()
true
96d7d761a9593d39c6d389de8c1dc506d61ef9b4
AASHMAN111/Addition-using-python
/Development/to_run_module.py
1,800
4.125
4
#This module takes two input from the user. The input can be numbers between 0 and 255. #This module keeps on executing until the user wishes. #This module can also be called as a main module. #addition_module.py is imported in this module for the addition #conversion_module.py is imported in this module for the conversion #user_input_moduoe.py is imported in this module for taking the inputs from them and to handle exceptions. #Aashman Uprety, 26th May, 2020 import addition_module import conversion_module import user_input_module def list_to_string(lst): """Function to convert the list 'lst' to string.""" string = "" for i in lst: i = str(i) string = string + i return string check = "yes" while check != "no": if check == "yes": lst = user_input_module.user_input_module() fbinary = conversion_module.decimal_to_binary(lst[0]) sbinary = conversion_module.decimal_to_binary(lst[1]) bit_addition = addition_module.bit_addition(fbinary, sbinary) bitwise_add = addition_module.bitwise_addition(lst[0],lst[1]) print("First inputted number in binary is: ", list_to_string(fbinary)) print("Second inputted number in binary is: ", list_to_string(sbinary)) print("Sum of the two inputted numbers in binary is: ", list_to_string(bit_addition)) print("Sum of the two inputted numbers in decimal is: ",bitwise_add) else: print("please only enter yes or no.") check = input("Are you willing for another addition? If yes just type yes than you can else just type no, the program will terminate : ") check = check.lower() if check == "no": print("The program is terminating. BYYEEEEEEEE.")
true
868ad4369cd64f877f4ea35f1a85c941aa9c7409
SaketJNU/software_engineering
/rcdu_2750_practicals/rcdu_2750_strings.py
2,923
4.40625
4
""" Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. """ import string name = "shubham" print("Data in upper case : ",name.upper()) # upper() for UPPER case strings conversion lower = "PRAJAPATI" print("Data in lower case : ",lower.lower()) # lower() for lower case strings conversion takeData = input("Please enter any data : ") print("Here is the user input data : ",takeData) # input() for taking data from user # NOTE -> input() takes data in string if you want to do some functionality with numeric please # convert that data in your dataType like : int float etc. # Let's take a look of some in-built string functions print(string.ascii_uppercase) # ascii_uppercase gives A-Z print(string.digits) # it gives 0-9 # string formatter """ % c -> character % s -> string % i ,d-> signed integer deciaml integer % u -> unsigned decimal integer % x -> hex decimal integer (lowercase) % X -> hex decimal integer (UPPERCASE) % o -> octal decimal integers % e -> exponantial notation (lowercase, e^3) % E -> exponantial notation (10^3) % f -> floating point numbers """ print("hexa decimal : ",string.hexdigits) # string.hexdigits gives hexadecimal number print("only printable no : ",string.printable ) # printable characters only print("Octa decimal no : ",string.octdigits) # Octa decimal no's print(type(name.isalnum()),name.isalnum()) # checks alphanumeric print(type(name.isnumeric()),name.isnumeric()) # checks numeric print(type(name.isdigit()),name.isdigit()) # checks digit print("Split func : ",name.split()) # Splits stings print("Starts With ",name.startswith('s')) # Checks starting char of string return boolean number = " my number is 97748826478" print(number.split()) # Basically returns list print(number.strip()) # removes unprintable charaters from both side left and right print(number.rstrip()) # removes unprintable charaters right side only splitn= number.split() for onew in splitn: if (onew.strip()).isdigit(): if len(onew.strip())== 11: print("No", onew.strip()) str1 = "abcdxyzabc" print(str1.replace('a','k')) # occurance of 'a' by 'k' str2 = str1.replace('a','k') print(str2.replace('acd','shu')) print(str1.capitalize()) # Capitalize capital only first char of an string # Method 1st newName = "shubham kumar prajapati" splitName = newName.split() print(splitName) print(splitName[0][0].upper() + ". "+ splitName[1][0].upper() + ". "+ splitName[2].capitalize()) wordlen = len(splitName) print("Length of list : ",wordlen) # Method 2nd count = 0 newname = "" for aw in splitName: count +=1 if count < wordlen: newname += aw[0].upper()+ ". " else : newname += aw[0].upper()+aw[1:] print("By method 2nd : ",newname)
true
7bbe18daf81dabb7aa2ddb7f20bca261734a17d8
dodooh/python
/Sine_Cosine_Plot.py
858
4.3125
4
# Generating a sine vs cosine curve # For this project, you will have a generate a sine vs cosine curve. # You will need to use the numpy library to access the sine and cosine functions. # You will also need to use the matplotlib library to draw the curve. # To make this more difficult, make the graph go from -360° to 360°, # with there being a 180° difference between each point on the x-axis import numpy as np import matplotlib.pylab as plt plt.show() # values from -4pi to 4pi x=np.arange(-4*np.pi,4*np.pi,0.05) y_sin=np.sin(x) y_cos=np.cos(x) #Drawing sin and cos functions plt.plot(x,y_sin,color='red',linewidth=1.5, label="Sin(x)") plt.plot(x,y_cos,color='blue', label="Cos(x)") plt.title("Sin vs Cos graph") plt.xlabel('Angles in radian') plt.ylabel('sin(x) and cos(x)') plt.legend(['sin(x)','cos(x)']) plt.show()
true
68d606253d377862c11b0eaf52f942f6b6155f56
DimaSapsay/py_shift
/shift.py
349
4.15625
4
"""" function to perform a circular shift of a list to the left by a given number of elements """ from typing import List def shift(final_list: List[int], num: int) -> List[int]: """perform a circular shift""" if len(final_list) < num: raise ValueError final_list = final_list[num:] + final_list[:num] return final_list
true
630d6de3258bef33cfb9b4a79a276d002d56c39c
VictoryWekwa/program-gig
/Victory/PythonTask1.py
205
4.53125
5
# A PROGRAM TO COMPUTE THE AREA OF A CIRCLE ## # import math radius=float(input("Enter the Radius of the Circle= ")) area_of_circle=math.pi*(radius**2) print("The Area of the circle is", area_of_circle)
true
5503ffdae3e28c9bc81f7b536fc986bf46913d34
jocogum10/learning_data_structures_and_algorithms
/doubly_linkedlist.py
1,940
4.21875
4
class Node: def __init__(self, data): self.data = data self.next_node = None self.previous_node = None class DoublyLinkedList: def __init__(self, first_node=None, last_node=None): self.first_node = first_node self.last_node = last_node def insert_at_end(self, value): new_node = Node(value) if not self.first_node: # if there are no elements yet in the linked list self.first_node = new_node self.last_node = new_node else: new_node.previous_node = self.last_node # else, set the new node's previous node as the last node self.last_node.next_node = new_node # set the last node's next node to the new node self.last_node = new_node # set the last node as the new node def remove_from_front(self): removed_node = self.first_node # set the node to be removed self.first_node = self.first_node.next_node # set the first node to be the next node return removed_node # return the removed node class Queue: def __init__(self): self.queue = DoublyLinkedList() def enque(self, value): self.queue.insert_at_end(value) def deque(self): removed_node = self.queue.remove_from_front return removed_node def tail(self): return self.queue.last_node.data if __name__ == '__main__': node_1 = Node("once") node_2 = Node("upon") node_1.next_node = node_2 node_3 = Node("a") node_2.next_node = node_3 node_4 = Node("time") node_3.next_node = node_4 dlist = DoublyLinkedList(node_1) print(dlist.remove_from_front().data) q = Queue() q.enque(dlist) b = q.tail() print(b.first_node.data)
true
f9b9480cc340d3b79f06e49aa31a53dbea5379f5
abilash2574/FindingPhoneNumber
/regexes.py
377
4.1875
4
#! python3 # Creating the same program using re package import re indian_pattern = re.compile(r'\d\d\d\d\d \d\d\d\d\d') text = "This is my number 76833 12142." search = indian_pattern.search(text) val = lambda x: None if(search==None) else search.group() if val(search) != None: print ("The phone number is "+val(search)) else: print("The phone number is not found")
true
ddf2124551bc9a6c08f4e1d4b4347c6cd1a3cb91
gogoamy/repository1
/type.py
2,561
4.125
4
# -*- coding: utf-8 -*- # Number类型(int, float, boolean, complex) print('Number类型(int, float, boolean, complex)') a = 10 print('整形(int) a = ',a) b = 20.00 print('浮点型(float) b = ',b) c = 1.5e11 print('浮点型,科学计数法(float) c = ',c) d = True print('布尔型(boolean) d = ',d) e = False print('布尔型(boolean) e = ',e) f = 3.14j print('复数(complex) f = ',f) g = complex(1.2,2.3) print('复数(complex) g = ',g) print() print() print() # String类型 print('String类型') s1 = 'hello' print('String类型 s1 = ',s1) s2 = "let's go" print('String类型 s2 = ',s2) # 转义符号\,\n,\t s3 = 'let\'s go' print('String类型 s3 = ',s3) s4 = 'abc\ncba' print('String类型 s4 = ',s4) s5 = '\\\t\\' print('String类型 s5 = ',s5) #跨越多行 s6 = '''abc 123 erf 333 tyu ''' print('String类型 s6 = ',s6) # 星号 (*) 表示复制当前字符串,紧跟的数字为复制的次数 s7 = 'hello world '*5 print('String类型 s7 = ',s7) print() print() print() # String中字符串检索 print('String中字符串检索') test = 'hello' print('test[0]: ',test[0]) print('test[1]: ',test[1]) print('test[2]: ',test[2]) print('test[3]: ',test[3]) print('test[4]: ',test[4]) # String中的切片 # str[x:y]: 输出从x位置开始的字符一直到y位置(不包括y) print('test[0:2]: ',test[0:2]) print('test[2:4]: ',test[2:3]) print('test[2:5]: ',test[2:5]) # 索引切片可以有默认值,切片时,忽略第一个索引的话,默认为0 # 忽略第二个索引,默认为字符串的长度 print('test[:2]: ',test[:2]) print('test[2:]: ',test[2:]) # 索引也可以是负数,这将导致从右边开始计算 print('test[-1]: ',test[-1]) print('test[-2]: ',test[-2]) print('test[-3]: ',test[-3]) print('test[-4]: ',test[-4]) print('test[-5]: ',test[-5]) print('test[-2:]: ',test[-2:]) print('test[:-2]: ',test[:-2]) # 内置函数 len() 返回字符串长度 s = 'abcdefghijk' print('字符串s的长度是: ',len(s)) print() print() print() # 格式化字符串 # 在字符串内部,%s表示用字符串替换,%d表示用整数替换 # 有几个%占位符,后面就跟几个变量或者值,顺序要对应好 print('格式化字符串') print('hello,%s' % 'world') print('your name is %s, your score is %d' % ('testing',98)) print('浮点数:%f' % 3.14) print('浮点数:%.2f' % 3.14)
false
d8e66b7676addfb742698f8057a2dbe59d9991c5
DamirKozhagulov/python_basics_homework
/home_tasks_1/practical_work_1_4.py
571
4.15625
4
# 4) # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. number = input('Введите целое положительное число: ') print(len(number)) result = [] i = 0 while i < len(number): num = number[i] result.append(num) i += 1 number = sorted(result) print(number) print('Самая большая цифра ' + number[-1])
false
be8b2ea14326e64425af9ee13478ec8c97890804
beajmnz/IEDSbootcamp
/pre-work/pre-work-python.py
1,135
4.3125
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 23 17:39:23 2021 @author: Bea Jimenez <bea.jimenez@alumni.ie.edu> """ #Complete the following exercises using Spyder or Google Collab (your choice): #1. Print your name print('Bea Jimenez') #2. Print your name, your nationality and your job in 3 different lines with one single #print command print('Bea Jimenez\nSpanish\nCurrently unemployed, but I\'m a COO wannabe :)') #3. Create an integer variable taking the value 4 intFour = 4 #4. Create other integer variable taking the value 1 intOne = 1 #5. Transform both variables into boolean variables. What happens? intFour = bool(intFour) intOne = bool(intOne) # -> both variables are transformed into booleans and get True value #6. Transform this variable "23" into numerical variable. str23 = '23' int23 = int(str23) #7. Ask the user their age in the format 1st Jan, 2019 (check the command input for #this). Using this info, show on the screen their year of birth birthdate = input(prompt='Please state your birthdate in the format 1st Jan, 2019') print('From what you just told me, you were born in the year '+birthdate[-4:])
true
28e93fcc30fca3c0adec041efd4fbeb6a467724e
beajmnz/IEDSbootcamp
/theory/03-Data Structures/DS6.py
452
4.34375
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Wed May 5 18:24:27 2021 @author: Bea Jimenez <bea.jimenez@alumni.ie.edu> """ """ Write a Python program to count the elements in a list until an element is a tuple. Input: [10,20,30,(10,20),40] Output: 3 """ Input = [10,20,30,(10,20),40] counter = 0 for i in Input: if type(i) != tuple: counter+=1 else: break print("There were",counter,"elements before the first tuple")
true
e29dcf2e71f5f207a18e22067c0b26b530399225
beajmnz/IEDSbootcamp
/theory/02b-Flow Control Elements/FLOW3.py
468
4.125
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Wed May 5 13:03:37 2021 @author: Bea Jimenez <bea.jimenez@alumni.ie.edu> """ """ Write a Python program that asks for a name to the user. If that name is your name, give congratulations. If not, let him know that is not your name Mark: be careful because the given text can have uppercase or lowercase letters """ name = input('Guess my name').strip().lower() if name == 'bea': print('congrats!') else: print('too bad')
true
37b2d8a716c5e5a130cf1761e92a65ea3a517ab7
JovieMs/dp
/behavioral/strategy.py
1,003
4.28125
4
#!/usr/bin/env python # http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern # -written-in-python-the-sample-in-wikipedia """ In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern), however Python supports higher-order functions and allows us to have only one class and inject functions into it's instances, as shown in this example. """ import types class SortedList: def set_strategy(self, func=None): if func is not None: self.sort = types.MethodType(func, self) def sort(self): print(self.name) def bubble_sort(self): print('bubble sorting') def merge_sort(self): print('merge sorting') if __name__ == '__main__': strat = SortedList() strat.set_strategy(bubble_sort) strat.sort() strat.set_strategy(merge_sort) strat.sort()
true
ac896f90c9213c8bee169ffd3fbc74a6b4dc15e3
ICS3U-Programming-JonathanK/Unit4-01-Python
/sum_of_numbers.py
1,257
4.40625
4
#!/usr/bin/env python3 # Created by: Mr. Coxall # Created on: Sept 2019 # Modified by: Jonathan # Modified on: May 20, 2021 # This program asks the user to enter a positive number # and then uses a loop to calculate and display the sum # of all numbers from 0 until that number. def main(): # initialize the loop counter and sum loop_counter = 0 sum = 0 # get the user number as a string user_number_string = input("Enter a positive number: ") print("") try: user_number_int = int(user_number_string) print("") except ValueError: print("Please enter a valid number") else: # calculate the sum of all numbers from 0 to user number while (loop_counter <= user_number_int): sum = sum + loop_counter print("Tracking {0} times through loop.".format(loop_counter)) loop_counter = loop_counter + 1 print("The sum of the numbers from" "0 to {} is: {}.".format(user_number_int, sum)) print("") if (user_number_int < 0): print("{0} is not a valid number".format(user_number_int)) finally: print("") print("Thank you for your input") if __name__ == "__main__": main()
true
e811211d279510195df3bbdf28645579c8b9f6de
megler/Day8-Caesar-Cipher
/main.py
1,497
4.1875
4
# caesarCipher.py # # Python Bootcamp Day 8 - Caesar Cipher # Usage: # Encrypt and decrypt code with caesar cipher. Day 8 Python Bootcamp # # Marceia Egler Sept 30, 2021 from art import logo from replit import clear 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', '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'] game = True def caesar(cipher:str, shift_amt:int, direction:str) -> str: code = '' if direction == 'decode': shift_amt *= -1 for i,value in enumerate(cipher): if value in alphabet: #find the index of the input in the alphabet answer = alphabet.index(value) answer += shift_amt #if shift_amt pushes past end of alphabet, restart #eg z(26) + shift(5) == 30 = (26 * 1) + 4 alpha_loop = alphabet[answer%len(alphabet)] code += alpha_loop else: code += value print(f"The {direction}d text is {code}") print(logo) #Allow game to continue until user says no while game: 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(cipher=text, shift_amt=shift, direction=direction) play = input("Do you want to play again?\n").lower() if play == 'no': print(f"Thanks for playing") game = False
true
03839c78723e70f763d8009fea4217f18c3eff42
agustinaguero97/curso_python_udemy_omar
/ex4.py
1,624
4.15625
4
""""Your teacher asked from you to write a program that allows her to enter student 4 exam result and then the program calculates the average and displays whether student passed the semester or no.in order to pass the semester, the average score must be 50 or more""" def amount_of_results(): while True: try: count = int(input("type the amount of result to calculate the average: ")) if count <= 0: raise Exception return count except: print("input error, must be a number greater that 0 and a integer") def result_input(count): result_list = [] while True: try: note = int(input(f"type the {count}° note (o to 100): ")) if 0<= note and note <= 100: result_list.append(note) count -= 1 if count == 0: break else: raise Exception except: print("invalid number, must go from 0 to 100") return result_list def prom(result): sum = 0 for notes in result: sum = sum + notes promedio = int(sum/(len(result))) print(f"the average of the results is: {promedio}") return promedio def pass_failed(average,score): if average < score: print("the student does not pass ") if average >= score: print("the student does pass") if __name__ == '__main__': count = amount_of_results() result = result_input(count) average = prom(result) pass_failed(average,score=50) #here can modify the minimun average score of approval
true
7be5665d75207fd063846d31adfc0012aaeee891
vlad-bezden/data_structures_and_algorithms
/data_structures_and_algorithms/quick_sort.py
512
4.21875
4
"""Example of quick sort using recursion""" import random from typing import List def quick_sort(data: List[int]) -> List[int]: if len(data) < 2: return data pivot, left, right = data.pop(), [], [] for item in data: if item < pivot: left.append(item) else: right.append(item) return quick_sort(left) + [pivot] + quick_sort(right) if __name__ == "__main__": data = random.sample(range(1000), 15) print(data) print(quick_sort(data))
true
4059405985761b3ae72fff1d6d06169cc35b1823
lakshay-saini-au8/PY_playground
/random/day03.py
678
4.46875
4
#question ''' 1.Create a variable “string” which contains any string value of length > 15 2. Print the length of the string variable. 3. Print the type of variable “string” 4. Convert the variable “string” to lowercase and print it. 5. Convert the variable “string” to uppercase and print it. 6. Use colon(:) operator to print the index of string from -10 to the end(slicing). 7. Print the whole string using a colon(:) operator(slicing). ''' string = "Hye, My Name is lakshay saini. we can connect https://www.linkedin.com/in/lakshay-saini-dev/" print(len(string)) print(type(string)) print(string.lower()) print(string.upper()) print(string[-10:]) print(string[:])
true