blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7c59f7673112831e51cb8d071c45d47d61c21dee
alonsovidales/cracking_code_interview_1_6_python
/9_5.py
1,020
4.21875
4
# Given a sorted array of strings which is interspersed with empty strings, # write a meth- od to nd the location of a given string # Example: nd "ball" in ["at", "", "", "", "ball", "", "", "car", "", "", # "dad", "", ""] will return 4 Example: nd "ballcar" in ["at", "", "", "", "", # "ball", "car", "", "", "dad", "", ""] will return -1 def search_str(strings, string): lo = 0 hi = len(strings)-1 while lo < hi: m = (hi-lo)/2 + lo while strings[m] == "" and m < hi: m += 1 if m == hi: m = (hi-lo)/2 + lo while strings[m] == "" and m > lo: m -= 1 if m == lo: return -1 if strings[m] == string: return m if strings[m] > string: hi = m else: lo = m print search_str(["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""], 'ball') print search_str(["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""], 'ballcar')
false
4505f8a1fe1c9cc5b04a326896c1648ec5415fee
jmockbee/While-Blocks
/blocks.py
390
4.1875
4
blocks = int(input("Enter the number of blocks: ")) height = 0 rows = 1 while rows <= blocks: height += 1 # is the height +1 blocks -= rows #blocks - rows if blocks <= rows: break # while the rows are less than the blocks keep going. # if the rows become greater than the blocks stop rows += 1 print("The height of the pyramid:", height)
true
e9bb62ab1fceeb98599946ef6a0c00650baa5d29
ioannispol/Py_projects
/maths/main.py
2,337
4.34375
4
""" Ioannis Polymenis Main script to calculate the Area of shapes There are six different shapes: - square - rectangle - triangle - circle - rhombus - trapezoid """ import os import class_area as ca def main(): while True: os.system('cls') print("*" * 30) print("Welcome to Area Calculator ") print("Options:") print("s = Square") print("r = Rectangle") print("tri = Triangle") print("c = Circle") print("rh = Rhombus") print("trap = Trapezoid") print("q = Quit") print("*" * 30) userInput = input("Enter the shape command: ") if userInput == 's': width = int(input("Enter the width of square: ")) height = int(input("Enter the height of the square: ")) square = ca.Area(width, height) print("Square area: %d" % (square.square_area())) elif userInput == 'r': width = int(input("Enter the width of square: ")) height = int(input("Enter the height of the square: ")) rectangle = ca.Area(width, height) print("Rectangle area: %d" % (square.rectangle_area())) elif userInput == 'tri': base = int(input("Enter base of the triangle: ")) tri_height = int(input("Enter height of the triangle: ")) tri = ca.Triangle(base, tri_height) print("Triangle Area: %d" % (tri.area())) elif userInput == 'c': radius = int(input("Enter circle radius: ")) cir = ca.Circle(radius) print("Circle area: %d" % cir.area()) elif userInput == 'rh': width = int(input("Enter the width of rhombus: ")) height = int(input("Enter the height of the rhombus: ")) rh = ca.Rhombus(width, height) print("Rhombus area: %d" % (rh.area())) elif userInput == 'trap': base = int(input("Enter the base of the trapezoid: ")) base2 = int(input("Enter the 2nd base of the trapezoid: ")) height = int(input("Enter the height of the trapezoid: ")) trap = ca.Trapezoid(base, base2, height) print("Trapezoid area: %d" % (trap.area())) elif userInput == 'q': break if __name__ == '__main__': main()
true
e467818f8fe5e8099aaa6fb3a9c10853ff92b00b
wiznikvibe/python_mk0
/tip_calci.py
610
4.25
4
print("Welcome to Tip Calculator") total_bill = input("What is the total bill?\nRs. ") tip_percent = input("What percent tip would you like to give? 10, 12, 15?\n ") per_head = input("How many people to split the bill?\n") total_bill1 = float(total_bill) (total_bill) tip_percent1 = int(tip_percent) per_head1 = int(per_head) total_tip = total_bill1 * (tip_percent1/100) total_amount = total_bill1 + total_tip tip_pperson = total_tip / per_head1 each_person = total_amount / per_head1 each_person1 = round(each_person,3) message = f"Each person has to pay: Rs.{each_person1} " print(message)
true
0e4cf1b1837a858cfb92830fa38c93879980b80c
sifisom12/level-0-coding-challenges
/level_0_coding_task05.py
447
4.34375
4
import math def area_of_a_triangle (side1, side2, side3): """ Calculating the area of a triangle using the semiperimeter method """ semiperimeter = 1/2 * (side1 + side2 + side3) area = math.sqrt(semiperimeter* ((semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - side3))) return area area = area_of_a_triangle (7, 9, 11) print("Area is equal to " + "{:.2f}".format(area) + " square units")
true
4c9f4a62a94d2be21d09265e188ae113c4a3bae8
crisog/algorithms-class
/queues/first_problem.py
869
4.125
4
import time # Esta es la clase que define la cola # En este caso, la cola solo cuenta con una lista de elementos y dos funciones. class Queue: def __init__(self): self.items = [] # Esta función es para encolar elementos. def enqueue(self, item): self.items.insert(0, item) # Esta función es para desencolar elementos. def dequeue(self): return self.items.pop() # Esta función devuelve el tamaño de la cola. def size(self): return len(self.items) q1 = Queue() # Esta variable indica la cantidad de elementos que serán añadidos a cola. element_count = 100001 print('Encolando...') for x in range(1, int(element_count)): q1.enqueue(x) print('Elemento ', x, ' encolado.') print('Desencolando...') for x in range(1, q1.size()+1): q1.dequeue() print('Elemento ', x, ' desencolado.')
false
110ca5d0377417a8046664b114cfd28140827ed4
christinalycoris/Python
/arithmetic_loop.py
1,741
4.34375
4
import math print ("This program will compute addition, subtraction,\n" "multiplication, or division. The user will\n" "provide two inputs. The inputs could be any real\n" "numbers. This program will not compute complex\n" "numbers. The program will run until the user\n" "chooses to terminate the program. The user can\n" "do this by selecting the appropriate option when\n" "prompted to do so.\n\n") ans = input("Do you want to continue? Y/N ") while ans == 'Y' or ans == 'y' or ans == 'Yes' or ans == 'yes' or ans == 'YES': print ("\nSelect one operation: ") print ("\t1. Addition ") print ("\t2. Subtraction (A from B) ") print ("\t3. Subtraction (B from A) ") print ("\t4. Multiplication ") print ("\t5. Division (A into B) ") print ("\t6. Division (B into A) ") print ("\t7. EXIT ") sel = int(input("Your selection is: ")) while sel < 1 or sel > 6: if sel == 7: print ("Okay. Goodbye. \n") exit() else: print ("Invalid.\n") sel = int(input("Your selection is: ")) print ("\n") x = float(input("Input a (all real numbers): ")) y = float(input("Input b (all real numbers): ")) print ("\n") if sel == 1: print ("1. Addition \n\t",x,"+",y,"=",x+y) elif sel == 2: print ("2. Subtraction (A from B) \n\t",y,"-",x,"=",y-x) elif sel == 3: print ("3. Subtraction (B from A) \n\t",x,"-",y,"=",x-y) elif sel == 4: print ("4. Multiplication \n\t",x,"×",y,"=",x*y) elif sel == 5: print ("5. Division (A into B) \n\t",y,"÷",x,"=",y/x) elif sel == 6: print ("6. Division (B into A) \n\t",x,"÷",y,"=",x/y) else: print ("Hmm. I don't seem to know that one.\n") if ans == 'N' or ans == 'n' or ans == 'No' or ans == 'no' or ans == 'NO': print ("\nOkay. Goodbye. \n") exit()
true
224d9fa0622c1b7509f205fa3579a4b42a8a73a6
MurasatoNaoya/Python-Fundamentals-
/Python Object and Data Structure Basics/Print Formatting.py
1,397
4.59375
5
# Print Formatting ( String Interpolation ) - # .format method - print('This is a string {}'.format('okay.')) # The curly braces are placeholders for the variables that you want to input. # Unless specified otherwise, the string will be formatted in the order you put them in your .format function. print('This is a {}, not a {}; or a {}'.format('string', 'dictionary', 'tuple')) #A solution to this, is using indexing. print(" The world is {2}, {0} and {1}".format("lean", "mean.", "cruel")) # The variable(s) that you input, can also be in a list too. #The assigning of objects to letters is also possible. print('The {f} {b} {q}'.format(f='fox', b='brown', q='quick')) # Using letters is easier than index position, just do to it being hard to count the spaces. # Float Formatting - result = 100/777 print('The result was {r}'.format(r = result)) # Value:Width:Precision. (Mainly dealing with 'Precision'), as the width value only adds white space. print('The result was {r:1.3}'.format(r = result)) # Variable inserted to three decimal places, with a width of one. #fstrings method, alternative to the .format method. name = 'Andrew' age = 18 weight = 100.5 print(f'Hello my name is {name}') # This works with multiple variables (strings, integers, floats.) print(f'{name} is {age} years old; and can deadlift {weight} kilograms')
true
f62dd5c65eb6c397c7aa0d0557192b8a53768591
lxmambo/caleb-curry-python
/60-sets.py
557
4.15625
4
items = {"sword","rubber duck", "slice of pizza"} #a set cannot have duplicates items.add("sword") print(items) #what we want to put in the set must be hashable, lists are not conjunctions = {"for","and","nor","but","or","yet","so"} seen = set() copletely_original_poem = """yet more two more times i feel nor but or but or, so get me for and 2 or and times yet to know but i know you nor i get more for but """ data = copletely_original_poem.split() for word in data: if str.lower(word) in conjunctions: seen.add(str.lower(word)) print(seen)
true
390e46a938f9b7f819a9e59f517a9de9848b387e
lxmambo/caleb-curry-python
/25-reverse-list-w-slice.py
308
4.15625
4
data = ["a","b","c","d","e","f","g","h"] #prints every 2 items print(data[::2]) #prints reversed print(data[::-1]) data_reversed = data data[:] = data[::-1] print(data) print(id(data)) print(id(data_reversed)) #doint the slice like this changes only the content of the list #but doesn't change de list...
true
02d504e4b5a9658e643c3d10a5dc13b7a2e427f5
yennanliu/CS_basics
/leetcode_python/Hash_table/group-shifted-strings.py
2,917
4.21875
4
""" Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Return: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] Note: For the return value, each inner list's elements must follow the lexicographic order. """ # V0 # V1 # https://www.jiuzhang.com/solution/group-shifted-strings/#tag-highlight-lang-python class Solution: """ @param strings: a string array @return: return a list of string array """ def groupStrings(self, strings): # write your code here ans, mp = [], {} for str in strings: x = ord(str[0]) - ord('a') tmp = "" for c in str: c = chr(ord(c) - x) if(c < 'a'): c = chr(ord(c) + 26) tmp += c if(mp.get(tmp) == None): mp[tmp] = [] mp[tmp].append(str) for x in mp: ans.append(mp[x]) return ans # V1' # http://www.voidcn.com/article/p-znzuctot-qp.html class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ dic = {} for s in strings: hash = self.shiftHash(s) if hash not in dic: dic[hash] = [s] else: self.insertStr(dic[hash], s) return dic.values() def shiftHash(self, astring): hashlist = [(ord(i) - ord(astring[0])) % 26 for i in astring] return tuple(hashlist) def insertStr(self, alist, astring): i = 0 while i < len(alist) and ord(astring[0]) > ord(alist[i][0]): i += 1 if i == len(alist): alist.append(astring) else: alist[:] = alist[0:i] + [astring] + alist[i:] # V2 # Time: O(nlogn) # Space: O(n) import collections class Solution(object): # @param {string[]} strings # @return {string[][]} def groupStrings(self, strings): groups = collections.defaultdict(list) for s in strings: # Grouping. groups[self.hashStr(s)].append(s) result = [] for key, val in groups.iteritems(): result.append(sorted(val)) return result def hashStr(self, s): base = ord(s[0]) hashcode = "" for i in range(len(s)): if ord(s[i]) - base >= 0: hashcode += unichr(ord('a') + ord(s[i]) - base) else: hashcode += unichr(ord('a') + ord(s[i]) - base + 26) return hashcode
true
4e2a77b9611c8885a882a290dc99070f53655c49
yennanliu/CS_basics
/leetcode_python/Dynamic_Programming/best-time-to-buy-and-sell-stock-iii.py
2,900
4.15625
4
""" 123. Best Time to Buy and Sell Stock III Hard You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Input: prices = [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 105 """ # V0 # V1 # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/ # IDEA : Bidirectional Dynamic Programming class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 left_min = prices[0] right_max = prices[-1] length = len(prices) left_profits = [0] * length # pad the right DP array with an additional zero for convenience. right_profits = [0] * (length + 1) # construct the bidirectional DP array for l in range(1, length): left_profits[l] = max(left_profits[l-1], prices[l] - left_min) left_min = min(left_min, prices[l]) r = length - 1 - l right_profits[r] = max(right_profits[r+1], right_max - prices[r]) right_max = max(right_max, prices[r]) max_profit = 0 for i in range(0, length): max_profit = max(max_profit, left_profits[i] + right_profits[i+1]) return max_profit # V1' # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/ # IDEA : One-pass Simulation class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ t1_cost, t2_cost = float('inf'), float('inf') t1_profit, t2_profit = 0, 0 for price in prices: # the maximum profit if only one transaction is allowed t1_cost = min(t1_cost, price) t1_profit = max(t1_profit, price - t1_cost) # reinvest the gained profit in the second transaction t2_cost = min(t2_cost, price - t1_profit) t2_profit = max(t2_profit, price - t2_cost) return t2_profit # V2
true
e21178720f6c4a17fd9efa5a90062082a6c94655
Guimez/SecsConverter
/SecondsConverter.py
1,067
4.46875
4
print() print("===============================================================================") print("This program converts a value in seconds to days, hours, minutes and seconds.") print("===============================================================================") print() Input = int(input("Please, enter a value that you want to convert, in seconds: ")) ### Explains what the program do, then, asks and stores the value given by the user. Days = Input // 86400 # How many integer days there is. Hours = (Input % 86400) // 3600 # The rest of the above division divided by 3600 (correspondent value of 1 hour in seconds). Minutes = ((Input % 86400) % 3600) // 60 # The rest of the above division divided by 60 (correspondent value of 1 minute in seconds). Seconds = (((Input % 86400) % 3600) % 60) # The rest of the above division. ### Calculates the values. print("*****************************************************************************") print(Days, "days,", Hours, "hours,", Minutes, "minutes and", Seconds, "seconds.") ## Shows the results.
true
b18737a279e3b4511d708ae94bd53bc59a2be024
datastarteu/python-edh
/Lecture 1/Lecture.py
2,367
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 10 18:00:20 2017 @author: Pablo Maldonado """ # The "compulsory" Hello world program print("Hello World") ########################### ### Data types ########################### ## What kind of stuff can we work with? # First tipe: Boolean x = True y = 100 < 10 y x*y x+y # Numeric data (integers and floats) a = 1 b = 2 a+b a*b a/b c, d = 2.5, 10.0 c d # Complex numbers z = complex(1,2) z # Strings x = "I am a string" y = "... and I am a string too" # Tells us the type of the object type(x) x+y x*2 'test '*2 "test "*2 ########################### ### Containers ########################### # These are objects that contain other objects. # List x = [1,'a',2.0] x x[0] x[2] x[-1] x[-2] x[0] = 'pablo' x # The new list is now modified # Tuple y = (1,'a',2.0) y type(y) y[0] y[0] = 'something' # Error! You can not overwrite tuples # Unpacking: Storing the information of an object in different parts names = ('Juan', 'Pablo','Maldonado') first_name, second_name, last_name = names first_name # Parse a string into a list single_line = 'pablo,maldonado,zizkov' my_data = single_line.split(',') my_data # put it again together new_single_line = ','.join(my_data) new_single_line # Dictionaries d = {'name':'Pablo', 'last_name':'M'} type(d) d['name'] d['last_name'] d['address'] ########################### ### Loops and list comprehension ########################### x_vals = [1,2,3,4,5] for x in x_vals: print(x*x) # Sum of squares x_vals total = 0 for x in x_vals: total = total + x*x total # The Python way: Using list comprehension! sum([x*x for x in x_vals]) # List comprehension is a very useful way of doing loops "faster" [x*x for x in x_vals] # Ranges of numbers: my_vals = range(1,20) # Run the following. What does it print? for i in my_vals: print(i) my_vals # Calculating squares in two different ways sum([x*x for x in my_vals]) sum([x**2 for x in my_vals]) # Example: Calculate the distance between two vectors #### from math import sqrt x = [3,0] y = [0,4] dist = 0 for i in range(len(x)): dist += (x[i]-y[i])**2 dist = sqrt(dist) dist # How can we re-write this? def my_dist(x,y): dist2 = sum([(x[i]-y[i])**2 for i in range(len(x))]) dist = sqrt(dist2) return dist
true
5a5f041391049d4e7fa05338ae258462dcbf3e12
iulidev/dictionary_search
/search_dictionary.py
2,798
4.21875
4
""" Implementarea unui dictionar roman englez si a functionalitatii de cautare in acesta, pe baza unui cuvant In cazul in care nu este gasit cuvantul in dictionar se va ridica o eroare definita de utilizator WordNotFoundError """ class Error(Exception): """Clasa de baza pentru exceptii definite de utilizator""" pass class WordNotFoundError(Error): """Clasa pentru exceptii la cautare fara succes in dictionar""" class Dict: """Clasa pentru instante de tip dictionar, perechi cuvant: traducere Atribute: name (str): numele dictionarului words (dict): dictionarul de cuvinte, perechi de stringuri word: translation total (int): numarul total de definitii (cuvinte) Metode: __init__(self, name='Dictionar En-Ro', initial_words=None) - constructor pe baza nume (string) si dictionar de start (dict) add(self, word, translation) - adauga un cuvant word cu traducerea translation la dictionar display(self) - afiseaza perechile cuvant: traducere (valorile din dictionar) search(self, word) - cauta cuvantul word in dictionar - afiseaza traducerea daca este gasit - altfel, ridica exceptia WordNotFoundError count(): - afiseaza numarul de cuvinte din dictionar (total) """ total = 0 def __init__(self, name='Dictionar Ro-En', initial_words=None): self.name = name if initial_words is None: self.words = {} else: self.words = initial_words.copy() Dict.total += len(initial_words) def add(self, word, translation): self.words[word] = translation Dict.total += 1 def display(self): for word, translation in self.words.items(): print(f'{word} = {translation}') def search(self, word): try: translation = self.words.get(word) if translation is None: raise WordNotFoundError( f'Cuvantul {word} nu este in dictionar') except WordNotFoundError as e: return f'>>> {e.__class__.__name__}: {e}' else: return f'Rezultat cautare: {word} = {translation}' @staticmethod def count(): return f'Dictionarul are {Dict.total} cuvinte' def main(): d = Dict('Dictionar Roman Englez', {'mare': 'sea', 'calculator': 'computer'}) d.add('zi', 'day') d.add('ora', 'hour') d.add('soare', 'sun') d.add('apa', 'water') d.display() print(d.search('zi')) print(d.search('eveniment')) # ridica o exceptie WordNotFoundError print(d.search('soare')) print(Dict.count()) if __name__ == '__main__': main()
false
8be94bc4445de4bbc0c2ad37d191353f8c1bab96
naduhz/tutorials
/automate-the-boring-stuff/Collatz Sequence.py
343
4.21875
4
#Collatz Sequence def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 == 1: print(3 * number + 1) return 3 * number + 1 print('Enter any number: ') anyNumber = int(input()) while anyNumber != 1: anyNumber = collatz(anyNumber)
false
e2bb2d975de5ede39c8393da03e9ad7f48a19b7f
TenzinJam/pythonPractice
/freeCodeCamp1/try_except.py
1,080
4.5
4
#try-except block # it's pretty similar to try catch in javascript # this can also help with some mathematical operations that's not valid. such as 10/3. It will go through the except code and print invalid input. The input was valid because it was a number, but mathematically it was not possible to compute that number. Except will catch that as well. # we can except specific kind of error in this try except block. In the example below we are using built in keywords such as ZeroDivisionError and ValueError. Depending on what kind of error it is, it will display the message accordingly. # you can also name the error and print that error, like we did in the case of ZeroDivisionError, where we named it as "err" and then print it out. This err message returned in "integer division or modulo by zero" as specified by python, and not by the developer. # therefore, it is not a good practice to do an umbrella except. try: number = int(input("Enter a number:" )) print(number) except ZeroDivisionError as err: print(err) except ValueError: print("Invalid input")
true
c1c368937073a6f68e60d72a72d5c5f36f0243c1
kristinnk18/NEW
/Project_1/Project_1_uppkast_1.py
1,481
4.25
4
balance = input("Input the cost of the item in $: ") balance = float(balance) x = 2500 monthly_payment_rate = input("Input the monthly payment in $: ") monthly_payment_rate = float(monthly_payment_rate) monthly_payment = monthly_payment_rate while balance < x: if balance <= 1000: for month in range(1, 13): monthly_interest_rate = 0.015 monthly_payment = monthly_payment_rate interest_paid = balance * monthly_interest_rate balance = (balance - monthly_payment) + (balance * monthly_interest_rate) if balance <= 50: monthly_interest_rate = 0.015 monthly_payment = balance interest_paid = balance * monthly_interest_rate balance = (balance - monthly_payment) print("Month: ", month, "Payment: ", round(monthly_payment, 2), "Interest paid: ", round(interest_paid,2), "Remaining debt: ", round(balance,2)) break else: for month in range(1, 13): monthly_interest_rate = 0.02 monthly_payment = monthly_payment_rate interest_paid = balance * monthly_interest_rate balance = (balance - monthly_payment) + (balance * monthly_interest_rate) print("Month: ", month, "payment: ", round(monthly_payment, 2), "Interest paid: ", round(interest_paid,2), "Remaining balance: ", round(balance,2)) break
true
be515f0adc638fd089a400065d74d2292bbaaecd
kristinnk18/NEW
/Skipanir/Lists/dotProduct.py
780
4.25
4
# Input vector size: 3 # Element no 1: 1 # Element no 2: 3.0 # Element no 3: -5 # Element no 1: 4 # Element no 2: -2.0 # Element no 3: -1 # Dot product is: 3.0 def input_vector(size): input_vector = [] element = 1 for i in range(size): vector = float(input("Element no {}: ".format(element))) element += 1 input_vector.append(vector) return input_vector def dot_product(vector1, vector2): dot_product = 0 for i in range(size): vector = vector1[i] * vector2[i] dot_product += vector return dot_product # Main program starts here, DO NOT change size = int(input("Input vector size: ")) vector1 = input_vector(size) vector2 = input_vector(size) print("Dot product is:", dot_product(vector1, vector2))
false
06119d936bbe22687f7b163aee7cda895eae7957
kristinnk18/NEW
/Skipanir/whileLoops/Timi_3_2.py
327
4.1875
4
#Write a program using a while statement, that given the number n as input, prints the first n odd numbers starting from 1. #For example if the input is #4 #The output will be: #1 #3 #5 #7 num = int(input("Input an int: ")) count = 0 odd_number = 1 while count < num: print(odd_number) odd_number += 2 count += 1
true
5bb9558126505e69beda2cfb5e076e33a7cffa48
kristinnk18/NEW
/Skipanir/whileLoops/Timi_3_6.py
426
4.125
4
#Write a program using a while statement, that prints out the two-digit number such that when you square it, # the resulting three-digit number has its rightmost two digits the same as the original two-digit number. # That is, for a number in the form AB: # AB * AB = CAB, for some C. count = 10 while count <= 100: total = count * count if total % 100 == count: print(count) break count +=1
true
ab3da913e858ba47242ef8a7cb929c1db24754c8
kristinnk18/NEW
/Skipanir/algorithms/max_number.py
281
4.21875
4
number = int(input("input a number: ")) max_number = number while number > 0: if number > max_number: max_number = number number = int(input("input a number: ")) print(max_number) # prentar ut stærstu töluna sem er innsleginn þangað til talan verður < 0.
false
8d51a0547e26c0a4944ff04866cc37fd83c2ad35
kristinnk18/NEW
/Skipanir/Lists/pascalsTriangle.py
444
4.1875
4
def make_new_row(x): new_list = [] if x == []: return [1] elif x == [1]: return [1,1] new_list.append(1) for i in range(len(x)-1): new_list.append(x[i]+x[i+1]) new_list.append(1) return new_list # Main program starts here - DO NOT CHANGE height = int(input("Height of Pascal's triangle (n>=1): ")) new_row = [] for i in range(height): new_row = make_new_row(new_row) print(new_row)
true
26f7474ef39d8d92a78e605b92bdb46e73b77e45
Bioluwatifemi/Assignment
/assignment.py
345
4.15625
4
my_dict = {} length = int(input('Enter a number: ')) for num in range(1, length+1): my_dict.update({num:num*num}) print(my_dict) numbers = {2:4, 3:9, 4:16} numbers2 = {} your_num = int(input('Enter a number: ')) for key,value in numbers.items(): numbers2.update({key*your_num:value*your_num}) print (numbers2)
true
7028471a2d611b32767fb9d62a2acaab98edb281
free4hny/network_security
/encryption.py
2,243
4.5625
5
#Key Generation print("Please enter the Caesar Cipher key that you would like to use. Please enter a number between 1 and 25 (both inclusive).") key = int(input()) while key < 1 or key > 25: print(" Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.") key = int(input()) print(" Thanks for selecting the Caesar Cipher key. The Key selected by you is " + str(key)) #The plain text message #Allow the user to enter the plaintext message through the console plain_text = str(input("Please enter the plain text message that you would like the Caesar Cipher Encryption Algorithm to encrypt for you.")) cipher_text = "" print(" Thanks for entering the plain text message. You have entered the following plain text message.") print(" " + plain_text) #The Caesar Cipher Encryption algorithm for letter in plain_text: if letter.isalpha(): val = ord(letter) val = val + key if letter.isupper(): if val > ord('Z'): val -= 26 elif val < ord('A'): val += 26 elif letter.islower(): if val > ord('z'): val -= 26 elif val < ord('a'): val += 26 new_letter = chr(val) cipher_text += new_letter else: cipher_text += letter print(" Cipher Text -----> " + cipher_text) ###################################################### # #The Caesar Cipher Decryption algorithm # key1 = key # key1 = -key1 # plain_text = "" # print(" Cipher Text -----> " + cipher_text) # for letter in cipher_text: # if letter.isalpha(): # val = ord(letter) # val = val + key1 # if letter.isupper(): # if val > ord('Z'): # val -= 26 # elif val < ord('A'): # val += 26 # elif letter.islower(): # if val > ord('z'): # val -= 26 # elif val < ord('a'): # val += 26 # new_letter = chr(val) # plain_text += new_letter # else: # plain_text += letter # print(" Plain Text -----> " + plain_text)
true
aacace9f445f6f26d1f1e12c1e38802cb4d58c69
Kiara-Marie/ProjectEuler
/4 (palindrome 3digit product).py
706
4.34375
4
def isPalindrome(x): "Produces true if the given number is a palindrome" sx = str(x) # a string version of the given number lx = len(sx) # the number of digits in the given number n = lx - 1 m = 0 while 5 == 5: if sx[m] != sx[n] : return (False) break elif m >= n: return (True) break else: n -= 1 m += 1 #Program to find biggest palindrome made by multiplying 2 3-digit numbers n = 100 m = 100 rsf = -1 x = -1 for n in range(999): for m in range(999): if (m * n) > x and isPalindrome(m * n): rsf += 1 x = m * n print(rsf,x)
true
80ade572ba368b6ff7587525d07db2cc1e2424d4
bbrecht02/python-exercises
/cursoemvideo-python/ex008.py
418
4.21875
4
metro= float(input("Escreva uma distancia em metros:")) print ("A medida de {} m corresponde a:".format(metro)) # km= metro*10**-3 print ("{} km".format(km)) # hm= metro*10**-2 print ("{} hm".format(hm)) # dam= metro*10**-1 print ("{} dam".format(dam)) # dm= metro*10**1 print ("{} dm".format(dm)) # cm= metro*10**2 print ("{} cm".format(cm)) # mm= metro*10**3 print ("{} mm".format(mm))
false
a09f7b9417baef1b2635f3ba4245b503f493f14d
AaqibAhamed/Python-from-Begining
/ifpyth.py
419
4.25
4
responds= input('Do You Like Python ?(yes/no):') if responds == "yes" or responds == "YES" or responds == "Yes" or responds== "Y" or responds== "y" : print("you are on the right course") elif responds == "no" or responds == "NO" or responds == "No" or responds == "N" or responds == "n" : print(" you might change your mind ") else : print(" I did not understand ")
true
d0926732039cde4d463a57f833effe85fb656eea
zhangshuyun123/Python_Demo
/function_return.py
1,129
4.125
4
# -*- coding:utf8 - # 函数返回“东西” # 函数中调用函数 # 20190510 #加法 def add(a, b): print("两个值相加 %r + %r = " %(a, b)) return a + b #减法 def subtract(a,b): print("两个值相减 %r - %r = " %(a, b)) return a - b #乘法 def multiplication(a, b): print("两个值相乘 %r * %r = " %(a, b)) return a * b #除法 def division(a, b): print("两个数相除 %r / %r " %(a, b)) return a / b print("Let's do some match with just functions !!") he = add(10, 20) sheng = subtract(200, 100) cheng = multiplication(6, 6) chu = division(9, 3) print("和为:%r , 减为:%r , 乘积为:%r , 除为:%r ." %(he, sheng, cheng, chu)) print("**************************************************************") what = add(he, subtract(sheng, multiplication(cheng, division(chu, 2)))) print("这个值变成了:", what, "你算对了吗??") ######################################################### # 用input()输入多个值 q, w, e, r = input("请输入值中间用空格隔开:").split() print(q, w, e, r)
false
8dd72e83e364d450cafab02d2d099a4c3190d5ae
Maker-Mark/python_demo
/example.py
831
4.15625
4
grocery_list = ["Juice", "Apples", "Potatoes"] f = 1 for i in grocery_list: print( "Dont forget to buy " + i + '!') ##Demo on how to look though characters in a string for x in "diapers": print(x) #Conditional loop with a if statment desktop_app_list = ["OBS", "VMware", "Atom", "QR Generator", "Potatoe AI"] for x in desktop_app_list: print(x) if x == "Atom": print("Ladies and Gents, we got it! \nThe rest of your desktop apps are:") ## function demo def my_function(): print("This text is coming from a function") #To call the fucntion just call the funchion with the parameters my_function() # fucntion with parameters Demo def function_with_params(name): print("Hello, my name is " + name + " and I am a fucntion") #Calling paramatized function function_with_params("Bob")
true
f42a483538f0c1404ea3f2d594face9535e57e19
iramosg/curso_python
/aula04.py
426
4.125
4
import math num1 = 2 num2 = 5.5 print(type(num1)) print(type(num2)) num3 = num1 + num2 print(type(num3)) divisao = 5 + 2 / 2 print(divisao) divisao2 = (5+2) / 2 print(divisao2) verdadeiro = 5 > 2 print(verdadeiro) falso = 5 < 2 print(falso) idade = 18 if idade >= 18: print("Acesso liberado") else: print("Acesso negado!") math.sqrt(num1) print(math.sqrt(num1)) math.factorial(5) print(math.factorial(5))
false
9b0690bfa3aa792c46e4107b00fc06f45689b99a
xing3987/python3
/base/基础/_07_tuple.py
562
4.1875
4
single_turple = (3) print(type(single_turple)) single_turple = (3,) print(type(single_turple)) # list tuple相互转换 num_list = [1, 2, 4, 5] num_tuple = tuple(num_list) print(num_tuple) num_list = list(num_tuple) print(num_list) info_tuple = ("小明", 16, 1.85) print("%s 年龄是 %d,身高为 %.02f." % info_tuple) #循环变量 for info in info_tuple: print(info) #取值和去索引 print(info_tuple[0]) print(info_tuple.index("小明")) from base.helper import _helper _helper.print_line("*") #切片(同string规则) print(info_tuple[1:3])
false
ffc172de327a528fe0b4b6266080d16d0012f23c
sentientbyproxy/Python
/JSON_Data.py
638
4.21875
4
# A program to parse JSON data, written in Python 2.7.12. import urllib import json # Prompt for a URL. # The URL to be used is: http://python-data.dr-chuck.net/comments_312354.json url = raw_input("Please enter the url: ") print "Retrieving", url # Read the JSON data from the URL using urllib. uh = urllib.urlopen(url) data = uh.read() # Parse and extract the comment counts from the JSON data. js = json.loads(str(data)) # Set starting point of sum. sum = 0 comments = js["comments"] # Compute the sum of the numbers in the file. for item in js["comments"]: sum += item["count"] # Enter the sum below: print "Sum: ", sum
true
cc12ace41f10bfc03fd6fda0bfa7d3d95694768c
Ontefetse-Ditsele/Intro_python
/week_3/cupcake.py
1,744
4.125
4
#Ontefetse Ditsele # #19 May 2020 print("Welcome to the 30 second expect rule game--------------------") print("Answer the following questions by selection from among the options") ans = input("Did anyone see you(yes/no)\n") if ans == "yes": ans = input("Was it a boss/lover/parent?(yes/no)\n") if ans == "no": print("Eat It") else: ans = input("Was it expensive(yes/no)\n") if ans == "yes": ans = input("Can you cut of the part that touched the floor?(yes/no): \n") if ans == "yes": print("Eat it") else: print("Your call") else: ans = input("is it chocolate?(yes/no)\n") if ans == "yes": print("Eat it") else: print("Don't eat it") else: ans = input("Was it sticky?(yes/no)\n") if ans == "yes": ans = input("Is it a raw steak?(yes/no)\n") if ans == "yes": ans = input("Are you a puma?(yes/no)\n") if ans == "yes": print("Eat it") else: print("Don't eat it") else: ans = input("Did the cat lick it?(yes/no)\n") if ans == "no": print("Eat it") else: ans = input("Is it a healthy cat?(yes/no)\n") if ans == "yes": print("Eat it") else: print("Your call") else: ans = input("Is it an emausaurus(yes/no)\n") if ans == "yes": ans = input("Are you a megalosaurus(yes/no)\n") if ans == "yes": print("Eat it") else: print("Don't eat it") else: ans = input("Did the cat lick it?(yes/no)\n") if ans == "no": print("Eat it") else: ans = input("Is your cat healthy?(yes/no)\n") if ans == "yes": print("Eat it") else: print("Your call")
true
d09b3c2711d9df4ea00c917aabfe2c0f191055ee
Ontefetse-Ditsele/Intro_python
/week_3/pi.py
356
4.28125
4
#Ontefetse Ditsele # #21 May 2020 from math import sqrt denominator = sqrt(2) next_term = 2/denominator pi = 2 * 2/denominator while next_term > 1: denominator = sqrt(2 + denominator) next_term = 2/denominator pi *= next_term print("Approximation of PI is",round(pi,3)) radius = float(input("Enter the radius:\n")) print("Area:",round(pi * (radius**2),3))
true
a61ad782abbf9a3c0f2b76a561c1c190474264e0
rohini-nubolab/Python-Learning
/dictionary.py
551
4.28125
4
# Create a new dictionary d = dict() # or d = {} # Add a key - value pairs to dictionary d['xyz'] = 123 d['abc'] = 345 # print the whole dictionary print d # print only the keys print d.keys() # print only values print d.values() # iterate over dictionary for i in d : print "%s %d" %(i, d[i]) # another method of iteration for index, key in enumerate(d): print index, key, d[key] # check if key exist print 'xyz' in d # delete the key-value pair del d['xyz'] # check again print "xyz" in d
true
f5bef46daa56f9dbf9a18ddedb786bb7b982fd22
rohini-nubolab/Python-Learning
/swaplist.py
280
4.1875
4
# Python3 program to swap first and last element of a list def swaplist(newlist): size = len(newlist) temp = newlist[0] newlist[0] = newlist[size-1] newlist[size-1] = temp return newlist newlist = [12, 15, 30, 56, 100] print(swaplist(newlist))
true
a997569eb3036d6acca7e9e4152511878bd4ed1c
rohini-nubolab/Python-Learning
/length_k.py
294
4.28125
4
# Python program to find all string which are greater than given length k def length_k(k, str): string = [] text = str.split(" ") for i in text: if len(i) > k: string.append(i) return string k = 4 str = "Python is a programming" print(length_k(k, str))
true
4b0c89c828134415e4ad1da02a50c6dbf49c664e
rohini-nubolab/Python-Learning
/str_palindrome.py
254
4.4375
4
#Python program to check given string is Palindrome or not def isPalindrome(s): return s == s[::-1] s = "MADAM" result = isPalindrome(s) if result: print("Yes. Given string is Palindrome") else: print("No. Given string is not Palindrome")
true
3946d61a5c4b0fbc5ae9e26104e37b3acac9d4b4
99004396/pythonlabs
/fibonacci.py
240
4.125
4
def fibonacci(n): if(n==0): print("Incorrect input") if(n==1): print("0") n1=0 n2=1 c=0 while c<n: print(n1) f=n1+n2 n1=n2 n2=f c+=1 n=int(input()) fibonacci(n)
false
5eeb7cec2d6ca5a9f2478fe7286f23de9a185114
jedzej/tietopythontraining-basic
/students/Glogowska_Joanna/lesson_02_flow_control/adding_factorials.py
269
4.28125
4
print('For a given integer, \ print the sum of factorials') number = int(input('Enter a number: ')) sumoffact = 0 factorial = 1 for i in range(1, number + 1): factorial = factorial * i sumoffact += factorial print('The sum of factorials is: ' + str(sumoffact))
true
ecbcf8889252eb36d47c2b968d821f38f1d2fceb
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_07_strings/date_calculator.py
727
4.28125
4
#! python # date_calculator.py import datetime as dt def time_from_now(years=0, days=0, hours=0, minutes=0): """ Examples -------- time_from_now() time_from_now(2, 33, 12, 3) """ date0 = dt.datetime.now() date1 = date0.replace(date0.year + years) + \ dt.timedelta(days=days, hours=hours, minutes=minutes) return date1 if __name__ == "__main__": print("Give years, days, hours, minutes from now:") dateout = time_from_now(years=int(input("years: ")), days=int(input("days: ")), hours=int(input("hours: ")), minutes=int(input("minutes: "))) print("{:%Y-%m-%d %H:%M}".format(dateout))
false
973669615a36fdb152cd81f14b51f6908c7f121b
jedzej/tietopythontraining-basic
/students/biegon_piotr/lesson_02_flow_control/the_number_of_zeros.py
260
4.1875
4
print("The number of zeros\n") N = int(input("Enter the number of numbers: ")) result = 0 for i in range(1, N + 1): a = int(input("Enter a number: ")) if a == 0: result += 1 print("\nYou have entered {:d} numbers equal to 0".format(result))
true
65ffa0dbf7bc4a6e052fa5cf4f235ad36c55caec
jedzej/tietopythontraining-basic
/students/Glogowska_Joanna/lesson_01_basics/lesson_01.py
2,688
4.125
4
import math # Lesson 1.Input, print and numbers # Sum of three numbers print('Input three numbers in different rows') first = int(input()) second = int(input()) third = int(input()) sum = first + second + third print(sum) # Area of right-angled triangle print('Input the length of the triangle') base = int(input()) print('Input the height of the triangle') height = int(input()) area = (base * height) / 2 print(area) # Hello, Harry! print('What is your name?') print('Hello, ' + str(input()) + '!') # Apple sharing print('Input number of students') students = int(input()) print('Input number of apples') apples = int(input()) print('Each student will get ' + str(apples // students) + ' apples') print(str(apples % students) + ' apples will remain in the basket') # Previous and next number = int(input()) print('The next number for the number ' + str(number) + ' is ' + str(number + 1) + '.') print('The previous number for the number ' + str(number) + ' is ' + str(number - 1) + '.') # School desks print('There are 3 classes - how many students is in each of them?\n"' 'Input your answers in separate rows') class1 = int(input()) class2 = int(input()) class3 = int(input()) desks = ( class1 // 2 + class2 // 2 + class3 // 2 + class1 % 2 + class2 % 2 + class3 % 2 ) print(str(desks) + ' needs to be purchased') # Lesson 2.Integer and float numbers # Last digit of integer intnum = int(input()) print(intnum % 10) # Tens digit tensdig = int(input()) print((tensdig % 100) // 10) # Sum of digits sum3dig = int(input()) print(((sum3dig % 1000) // 100) + ((sum3dig % 100) // 10) + (sum3dig % 10)) # Fractional part fract = float(input()) print(fract - int(fract)) # First digit after decimal point rand = float(input()) firstdig = ((rand * 10) // 1) % 10 print(int(firstdig)) # Car route print('What distance in km the car covers per day?') kmperday = int(input()) print('What is the length of the route?') routelength = int(input()) print(math.ceil(routelength / kmperday)) # Digital clock print('Number of minutes that passed since midnight') minsmidn = int(input()) print(str(minsmidn // 60) + ':' + str(minsmidn % 60)) # Total cost dollars = int(input()) cents = int(input()) numcup = int(input()) print(dollars * numcup + (cents * numcup) // 100, (cents * numcup) % 100) # Clock face - 1 print('How many hours have passed since minight?') hours = int(input()) print('How many minutes have passed since minight?') mins = int(input()) print('How many seconds have passed since minight?') secs = int(input()) anghr = 360 / 12 angmin = anghr * 1 / 60 angsec = angmin / 60 angle = (anghr * hours) + (angmin * mins) + (angsec * secs) print(angle)
true
4355f566a32a6c866219f64a5725f1be10bc2b43
jedzej/tietopythontraining-basic
/students/kosarzewski_maciej/lesson_04_unit_testing/collatz/collatz_sequence.py
434
4.3125
4
def collatz(number): if number <= 0: raise ValueError elif number % 2 == 0: half_even = number / 2 print(half_even) return half_even elif number % 2 == 1: some_odd = (3 * number) + 1 print(some_odd) return some_odd if __name__ == "__main__": value = int(input("Please enter a number, positive, integer: ")) while value != 1: value = collatz(value)
true
f4833bbfde29d3ebcd266957c9c4adc1855ea9a4
jedzej/tietopythontraining-basic
/students/hyska_monika/lesson_06_dicts_tuples_sets_args_kwargs/Uppercase.py
459
4.375
4
# Function capitalize(lower_case_word) that takes the lower case word # and returns the word with the first letter capitalized def capitalize(lower_case_word): lst = [word[0].upper() + word[1:] for word in lower_case_word.split()] capital_case_word = " ".join(lst) print(capital_case_word) return capital_case_word text = str((input("Put string - use small letter: "))) capitalize(text) print("") s = "ala's ma kota UK. kk" capitalize(s)
true
6207e6d6d2dab838bbeaf60a37d815fee1d29cee
jedzej/tietopythontraining-basic
/students/jakielczyk_miroslaw/lesson_08_regular_expressions/email_validator.py
506
4.21875
4
import re email_address = input("Enter email address: ") email_regex = re.compile(r'''( [a-zA-Z0-9._%+-]+ # username @ # @ symbol [a-zA-Z0-9.-]+ # domain name (\.[a-zA-Z]{2,3}) # dot-something )''', re.VERBOSE) email_match = email_regex.search(email_address) if email_match is not None: print("given email address is correct") else: print("Given email address is incorrect")
false
1378aaf0c29ff0a9aa1062890506ceb7885e002a
jedzej/tietopythontraining-basic
/students/urtnowski_daniel/lesson_10_organizing_files/selective_copy.py
2,443
4.21875
4
#!/usr/bin/env python3 """ selective_copy.py: a practice project "Selective Copy" from: https://automatetheboringstuff.com/chapter9/ The program walks through a folder tree and searches for files with a given file extension. Then it copies these files from the source location to a destination folder. Usage: ./selective_copy.py <extension> <source_path> <destination_path> """ __author__ = "Daniel Urtnowski" __version__ = "0.1" import sys import os import shutil import random def get_args(): args_cnt = len(sys.argv) if args_cnt != 4: print("Usage: ./selective_copy.py <extension> <source_path> " "<destination_path>") return None else: extension, source, destination = sys.argv[1:] if not extension: print('Error! The extension cannot be an empty string!') return None if not os.path.exists(source) or not os.path.isdir(source): print("Error! The source path: {} is incorrect!".format(source)) return None if not os.path.exists(destination): os.makedirs(destination) elif not os.path.isdir(destination): print('Error! The destination path leads to a file') return None if not os.path.isabs(destination): destination = os.path.abspath(destination) return extension, source, destination def main(): args = get_args() if args is not None: extension, source, destination = args for curr_dir, _, files in os.walk(source): for file in files: if file.endswith('.{}'.format(extension)): if os.path.exists(os.path.join(destination, file)): name, ext = os.path.splitext(file) new_name = '{}_{}_{}'.format(name, random.randint(1, 999999), ext) shutil.copy(os.path.join(curr_dir, file), os.path.join(destination, new_name)) print('File names collision; renaming file {} copied ' 'from: {} to {}'.format(file, curr_dir, new_name) ) else: shutil.copy(os.path.join(curr_dir, file), destination) if __name__ == '__main__': main()
true
e378df9b54fea15bafa5ae8363e0e60c9604ff4e
jedzej/tietopythontraining-basic
/students/biegon_piotr/lesson_03_functions/exponentiation.py
267
4.46875
4
print("Exponentiation\n") def power(a, n): if n == 0: return 1 if n >= 1: return a * power(a, n-1) a = float(input("Enter a power base: ")) n = int(input("Enter an exponent exponent: ")) print("\nThe result is: {:f}".format(power(a, n)))
false
f406f56d29ee2683f6caefe267c06a0be06139fd
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_01_basic/total_cost.py
625
4.15625
4
# Problem «Total cost» (Medium) # Statement # A cupcake costs A dollars and B cents. Determine, how many dollars and cents # should one pay for N cupcakes. A program gets three numbers: A, B, N. # It should print two numbers: total cost in dollars and cents. print('Please input cost of 1 piece in dollars part:') dollars = int(input()) print('Please input cost of 1 piece in cents part:') cents = int(input()) print('Please input number of cupcakes:') number = int(input()) print('Total cost = ' + str((dollars * number) + int((cents * number) / 100)) + ' dollars, ' + str((cents * number / 100) % 1) + ' cents.')
true
96989ad57c10d19feaf9fc6c2c4bab7c01da93be
jedzej/tietopythontraining-basic
/students/mitek_michal/lesson_01_basics/car_route.py
219
4.125
4
import math def calculate_number_of_days(): n = int(input("Provide a distance that can move a day ")) m = int(input("Provide a length in kilometers ")) print(math.ceil(m/n)) calculate_number_of_days()
false
dea8bde4d91c6cb0c446a0a0899da9df3d077c14
jedzej/tietopythontraining-basic
/students/urtnowski_daniel/lesson_08_regular_expressions/automate_the_boring_stuff.py
2,422
4.1875
4
#!/usr/bin/env python3 """ automate_the_boring_stuff.py: a practice projects: "Regex version of strip" and "Strong Password Detection" from: https://automatetheboringstuff.com/chapter7/ """ __author__ = "Daniel Urtnowski" __version__ = "0.1" import re def regex_strip(input_str, chars=' '): """ This function takes a string and does the same thing as the strip() string method. :param string input_str: a string to be stripped :param string chars: characters to be removed form the beginning and the end of the input string :return string: the modified string """ escaped_chars = re.escape(chars) strip_regex = re.compile('^([{0}]+)'.format(escaped_chars)) modified_str = strip_regex.sub('', input_str) strip_regex = re.compile('([{0}]+)$'.format(escaped_chars)) modified_str = strip_regex.sub('', modified_str) return modified_str def is_password_strong(password): """ This function checks if input string is a strong password :param password: a string with password for verification :return bool: True if the passed string is a strong password, False otherwise """ is_strong = True patterns = [r'^.{8,}$', r'\d+', r'[a-z]+', r'[A-Z]+'] for pattern in patterns: passwd_regex = re.compile(pattern) mo = passwd_regex.search(password) if mo is None: is_strong = False break return is_strong def main(): # Regex version of strip for string, chars in [('0900-123-456-789-090-00', '0-9'), (' ala ma kota ', ' '), ('***aa*.a...', '*.a'), ('bcd ala ma kota cbdc dcdc db ', 'bcd '), ('***** ala ma kota ********', ' *')]: print("'{}' with stripped char(s): '{}' is: '{}'" .format(string, chars, regex_strip(string, chars))) for string in ['ala ma kota ', ' ala ma kota', ' ala ma kota ']: print("'{}' with stripped white spaces is: '{}'" .format(string, regex_strip(string))) print('') # Strong Password Detection for password in ['Password5', 'weaK123', '123456789', 'AbcDefghijk', 'Admin1', 'A1B2C3D4E5', '1a2b3c4d5e', 'stR0ngPass', ' ']: print("'{}' is strong password: {}" .format(password, is_password_strong(password))) if __name__ == '__main__': main()
true
329f29d43b0f47a5cb6db356bce578493406d4b3
jedzej/tietopythontraining-basic
/students/skowronski_rafal/lesson_06_dicts_tuples_sets_args_kwargs/project_04_snakify_lesson_10/cubes.py
588
4.125
4
def print_set(set): print(len(set)) for element in sorted(set): print(element) if __name__ == '__main__': alice_count, bob_count = \ tuple([int(i) for i in input('Enter two integers separated by space: ') .split()]) print('Enter Alice\'s set:') alice_set = set([int(input()) for i in range(alice_count)]) print('Enter Bob\'s set:') bob_set = set([int(input()) for i in range(bob_count)]) print('Answer: ') print_set(alice_set.intersection(bob_set)) print_set(alice_set - bob_set) print_set(bob_set - alice_set)
false
bf0ff9aaa89d6b411a58785e8d12becbc3adcc60
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_01_basics/Lesson2/ex02_07.py
599
4.34375
4
#Statement #Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock? #The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59). #For example, if N = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So the program should print 2 30. print("Please enter the number of minutes that is passed since midnight: ") a = int(input()) print("Hours and minutes displayed on digital clock are:") print(str(a//60)+ ' ' +str(a-(a//60)*60))
true
558046852a5d20e15639a0c8244e1518ee776bf4
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_01_basics/previous_and_next.py
488
4.15625
4
''' title: prevous_and_next author: arkadiusz.kasprzyk@tieto.com date: 2018-03-05 description: Write a program that reads an integer number and prints its previous and next numbers. There shouldn't be a space before the period. ''' print('''Reads an integer number and prints its previous and next numbers. ''' ) n = int(input("Give an integer: ")) print("The next number to {} is {}".format(n,n+1)) print("The previous number to {} is {}".format(n,n-1)) input("Press Enter to quit the program.")
true
769a73aa4e312c861c0eb9b54ca793f6121f5c89
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_05_lists/comma_code.py
968
4.53125
5
""" Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats'] Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it. """ def transform_string(collection): string = "" collection.insert(-1, 'and') for i in range(len(collection)): if len(collection) - i > 2: string += collection[i] + str(", ") elif len(collection) - i == 2: string += collection[i] + str(" ") elif len(collection) - i == 1: string += collection[i] return string def main(): spam = ['apples', 'bananas', 'tofu', 'cats'] print(transform_string(spam)) if __name__ == '__main__': main()
true
a465ed16d43516dda5d529acb4d4e7f0ded681e2
jedzej/tietopythontraining-basic
/students/kaczmarek_katarzyna/lesson_03_functions/the_length_of_the_segment.py
706
4.15625
4
from math import sqrt def distance(x1, y1, x2, y2): return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) def main(): while True: try: x1coordinate = float(input("Type x1 coordinate: ")) y1coordinate = float(input("Type y1 coordinate: ")) x2coordinate = float(input("Type x2 coordinate: ")) y2coordinate = float(input("Type y2 coordinate: ")) print("The distance is:", distance(x1coordinate, y1coordinate, x2coordinate, y2coordinate)) break except ValueError: print("All numbers must be real.") continue if __name__ == '__main__': main()
true
1db7a306d1c531fdce7503e61024bf24f3b9ea29
jedzej/tietopythontraining-basic
/students/lakatorz_izaak/lesson_07_string_datetime/date_calculator.py
657
4.15625
4
# Date calculator - write a script that adds custom number of years, # days and hours and minutes to current date and displays the result in # human readable format. import time import datetime def main(): print('Enter years, days, hours and minutes you want to add.') years, days, hours, mins = [int(x) for x in input().split(' ')] add_value = (years * 31536000 + days * 86400 + hours * 3600 + mins * 60) timestamp = time.time() my_data = datetime.datetime.fromtimestamp(timestamp + add_value) print(my_data.strftime("%Y-%m-%d %H:%M")) if __name__ == "__main__": main()
true
9f34d8aba1c553781e6866d34b623f25685d49c4
jedzej/tietopythontraining-basic
/students/zelichowski_michal/lesson_02_flow_control/the_number_of_zeroes.py
414
4.125
4
"""Given N numbers: the first number in the input is N, after that N integers are given. Count the number of zeros among the given integers and print it. You need to count the number of numbers that are equal to zero, not the number of zero digits. """ # Read an integer: a = int(input()) zeroes = 0 for x in range(1, a+1): b = int(input()) if b == 0: zeroes += 1 # Print a value: print(zeroes)
true
d6647eeab421b36b3a5f985071184e5d36a7fe9c
jedzej/tietopythontraining-basic
/students/pietrewicz_bartosz/lesson_03_functions/the_collatz_sequence.py
758
4.40625
4
def collatz(number): """Calculates and prints the next element of Collatz sequence""" if number % 2 == 0: number //= 2 else: number = number * 3 + 1 print(number) return number def read_number(): number = 0 # read integer from user until it is positive while number < 1: print("Enter positive integer: ", sep="", end="") number = int(input()) if number < 1: print("The number must be positive!") return number def main(): # read number from the user number = read_number() # calculate Collatz sequence until function calculating next element # returns 1 while number != 1: number = collatz(number) if __name__ == '__main__': main()
true
45026f81aa56c85fb70b6f60f60d24b8172605d0
jedzej/tietopythontraining-basic
/students/jemielity_kamil/lesson_01_basics/area_of_right_angled_traingle.py
208
4.28125
4
length_of_base = float(input("Write a length of the base: ")) height = float(input("Write a height of triangle: ")) area = (length_of_base * height)/2 print("Area of right-angled triangle is: %s" % area)
true
c33eb58a3e743b1bcb66e7be1ce1649126092894
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_06_dictionaries/the_number_of_distinct_words.py
544
4.21875
4
""" Given a number n, followed by n lines of text, print the number of distinct words that appear in the text. For this, we define a word to be a sequence of non-whitespace characters, seperated by one or more whitespace or newline characters. Punctuation marks are part of a word, in this definition. """ def main(): word_set = set() rows = int(input()) for i in range(rows): line = input().split() for word in line: word_set.add(word) print(len(word_set)) if __name__ == '__main__': main()
true
12de4d9871dee7d1bf3bcec9c672832d2f374f2f
jedzej/tietopythontraining-basic
/students/baker_glenn/lesson_3_scripts/exponentiation_recursion.py
615
4.25
4
def exponentiation_recursion(num, exp, calculated_number): if exp > 1: exp -= 1 calculated_number = calculated_number * num exponentiation_recursion(num, exp, calculated_number) else: print(str(calculated_number).rstrip('0').rstrip('.')) while True: try: print("Please enter a real number") number = float(input()) print("Please enter the exponent") exponent = int(input()) break except: print("Please enter a real number first, followed by an integer") counter = 0 exponentiation_recursion(number, exponent, number)
true
bea6cd3642874532f071326c5ddb2e6f7c9eff5c
jedzej/tietopythontraining-basic
/students/serek_wojciech/lesson_02_flow_control/elements_equal_maximum.py
425
4.125
4
#!/usr/bin/env python3 """The number of elements equal to the maximum""" def main(): """Main function""" max_value = -1 max_count = -1 number = -1 while number: number = int(input()) if number > max_value: max_value = number max_count = 1 elif number == max_value: max_count += 1 print(max_count) if __name__ == '__main__': main()
true
8f1b4f06ac87cc4d8bd5a968b8ade41d78ccd877
jedzej/tietopythontraining-basic
/students/baker_glenn/snakify_lesson_4/factorials_added.py
210
4.1875
4
# script to calculate the factorial print("enter a number") number = int(input()) result = 1 results_added = 0 for i in range(number): result *= (i+1) results_added += result print(str(results_added))
true
ca92c30e1ed48ad6404ea25fb6ac2aa5710dbc2a
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_02_flow_control/Snakify_Lesson6__2problems/the_second_maximum.py
697
4.34375
4
# Statement # The sequence consists of distinct positive integer numbers # and ends with the number 0. # Determine the value of the second largest element in this sequence. # It is guaranteed that the sequence has at least two elements. def second_maximum(): second = 0 print("Enter positive integer number:") first = int(input()) a = first while(a != 0): print("Enter a positive integer number (0 to end processing)):") a = int(input()) if (a > first): first, second = a, first elif (a > second): second = a print("The second maximum value is:") print(second) if __name__ == '__main__': second_maximum()
true
f0e4d4266a40a28a83c6a92f25da009a8b3b281a
jedzej/tietopythontraining-basic
/students/bedkowska_julita/lesson_03_functions/the_collatz_sequence.py
283
4.28125
4
def collatz(number): if number % 2 == 0: result = number // 2 print(result) return result else: result = 3 * number + 1 print(result) return result num = int(input('Give the number: ')) while num != 1: num = collatz(num)
true
d57e8619470c765eeedac5d4281d1f9b92748a62
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_02_flow_control/ladder.py
591
4.3125
4
""" description: For given integer n ≤ 9 print a ladder of n steps. The k-th step consists of the integers from 1 to k without spaces between them. To do that, you can use the sep and end arguments for the function print(). """ print(""" For given integer n ≤ 9 prints a ladder of n steps. The k-th step consists of the integers from 1 to k without spaces between them. """) n = int(input("n = ")) step = "" if n > 0 and n <= 9: for k in range(1, n+1): step += str(k) print(step) else: print("n is too large; should be between 1 and 9.")
true
07e29275bed340dfcc2d245a4c30e17ecc859e7f
jedzej/tietopythontraining-basic
/students/hyska_monika/lesson_03_functions/Collatz_Sequence.py
323
4.28125
4
# The Collatz Sequence def collatz(number): if (number % 2) == 0: m = number // 2 print(number, "\\", "2 =", m) return m else: m = 3 * number + 1 print("3 *", number, "+ 1 =", m) return m n = (int(input("put number to check:"))) while n != 1: n = collatz(n)
false
67c1553add8841549f017b90a6815e9c65d9a8fa
jedzej/tietopythontraining-basic
/students/mariusz_michalczyk/lesson_07_strings/delta_time_calculator.py
594
4.1875
4
from datetime import date, datetime def get_user_input(): print("Enter future date: ") entered_y = int(input("Enter year: ")) entered_m = int(input("Enter month: ")) entered_d = int(input("Enter day: ")) return date(entered_y, entered_m, entered_d) def current_date(): return date(datetime.now().year, datetime.now().month, datetime.now().day) if __name__ == '__main__': custom_date = get_user_input() print("Difference between your date and current date is: ") print(str((custom_date - current_date()).days) + " days")
true
55ba081b6820d5a6e5e871c41cdcb2b339954456
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_01_basics/Lesson1/ex01_05.py
511
4.21875
4
#Statement #Write a program that reads an integer number #and prints its previous and next numbers. #See the examples below for the exact format your answers should take. # There shouldn't be a space before the period. #Remember that you can convert the numbers to strings using the function str. print("Enter an integer value:") a = int(input()) print("The next number for the number " + str(a) + " is " + str(a + 1) + ".") print("The previous number for the number " + str(a) + " is " + str(a - 1) + ".")
true
2e9d015e9838c529c1b4f447a5fa96fa56fd0763
jedzej/tietopythontraining-basic
/students/serek_wojciech/lesson_03_functions/negative_exponent.py
366
4.125
4
#!/usr/bin/env python3 """Negative exponent""" def power(a_value, n_value): """Compute a^n""" result = 1 for _ in range(abs(n_value)): result *= a_value if n_value > 0: return result return 1 / result def main(): """Main function""" print(power(float(input()), int(input()))) if __name__ == '__main__': main()
false
0caa727fb0d611f93916061e80772ac331c36224
jedzej/tietopythontraining-basic
/students/hyska_monika/lesson_07_manipulating_strings_datetime_formatting/DatePrinter.py
941
4.28125
4
# Date printer - script that displays current date in human-readable format import datetime now = datetime.datetime.now() print('Full current date and time' 'using str method of datetime object: ', str(now)) print(str(now.day) + '.' + str(now.month) + '.' + str(now.year)) print(str(now.day) + '.' + str(now.month) + '.' + str(now.year) + ' ' + str(now.hour) + ':' + str(now.minute)) print("\nCurrent date and time using instance attributes:") print('Year: %d' % now.year) print('Month: %d' % now.month) print('Day: %d' % now.day) print('Hour: %d' % now.hour) print('Minute: %d' % now.minute) print('Second: %d' % now.second) print('Microsecond: %d' % now.microsecond) print("\nCurrent date and time using strftime:") print(now.strftime("%Y-%m-%d %H:%M")) print(now.strftime("%d.%m.%Y %H:%M")) print(now.strftime("%d %B %Y %H:%M")) # month by word print("\nCurrent date and time using isoformat:") print(now.isoformat())
false
204037e5dd7a1ef15c58f2063150c72f1995b424
jedzej/tietopythontraining-basic
/students/biegon_piotr/lesson_02_flow_control/chocolate_bar.py
473
4.21875
4
print("Chocolate bar\n") n = int(input("Enter the number of portions along the chocolate bar: ")) m = int(input("Enter the number of portions across the chocolate bar: ")) k = int(input("Enter the number of portions you want to divide the chocolate bar into: ")) print("\nIs it possible to divide the chocolate bar so that one part has exactly {:d} squares?".format(k)) if (k % n == 0 and k / n < m) or (k % m == 0 and k / m < n): print('YES') else: print('NO')
true
adb1d13da8f60604a0643d325404d5de692fea9b
jedzej/tietopythontraining-basic
/students/swietczak_monika/lesson_02_flow_control/the_number_of_elements_equal_to_maximum.py
293
4.21875
4
the_highest = 0 count = 0 number = int(input("Enter a number: ")) while number != 0: if number > the_highest: the_highest = number count = 1 elif number == the_highest: count += 1 number = int(input("Enter another number: ")) # Print a value: print(count)
true
47f9e146863f7aba249c6c5893c18f3023ee6a1b
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_05_lists/swap_min_and_max.py
605
4.28125
4
def swap_min_max(numbers): """ Parameters ---------- numbers: int[] Returns ------- numbers with maximum and minimum swapped. Only the first occurences of min and max are taken into account. Examples -------- print(swap_min_max([3, 0, 1, 4, 7, 2, 6])) print(swap_min_max([3, 0, 0, 4, 7, 2, 6])) print(swap_min_max([3, 0, 1, 4, 7, 7, 6])) """ if len(numbers) >= 2: lmin, lmax = min(numbers), max(numbers) imin, imax = numbers.index(lmin), numbers.index(lmax) numbers[imin], numbers[imax] = lmax, lmin return numbers
true
bc69ff4cae55e6fe17e853e3248e6cdb939fb8de
jedzej/tietopythontraining-basic
/students/slawinski_amadeusz/lesson_03_functions/8.02_negative_exponent.py
540
4.25
4
#!/usr/bin/env python3 def power(a, n): return a**n while True: try: print("Calculate a**n:") print("a = ", end='') a = float(input()) if a < 0: print("a needs to be positive!") raise ValueError print("n = ", end='') n = int(input()) if n < 0: print("n needs to be positive!") raise ValueError break except ValueError: print("Please try again!") print(str(a) + "**" + str(n) + " = " + str(power(a, n)))
false
4f66840fcd80f91a7a5689b8c39e75525640723d
jedzej/tietopythontraining-basic
/students/urtnowski_daniel/lesson_06_dicts_tuples_sets_args_kwargs/snakify_lesson_10.py
1,787
4.125
4
#!/usr/bin/env python3 """ snakify_lesson_10.py: Solutions for 3 of problems defined in: Lesson 10. Sets (https://snakify.org/lessons/sets/) """ __author__ = "Daniel Urtnowski" __version__ = "0.1" def read_set_of_integers(items_count): new_set = set() for i in range(items_count): new_set.add(int(input())) return new_set def print_set(input_set): ordered = list(input_set) ordered.sort() ordered_len = len(ordered) print(ordered_len) if ordered_len == 0: print('') else: [print(num) for num in ordered] def cubes(): alice_count, bob_count = [int(i) for i in input().split()] alice_set = read_set_of_integers(alice_count) bob_set = read_set_of_integers(bob_count) # common colors print_set(alice_set & bob_set) # Alice's unique colors print_set(alice_set - bob_set) # Bob's unique colors print_set(bob_set - alice_set) def the_number_of_distinct_words_in_some_text(): lines_cnt = int(input()) words = set() for i in range(lines_cnt): words |= set(input().split()) print(len(words)) def guess_the_number(): n = int(input()) numbers = set(range(n)) input_string = str(input()) while input_string != 'HELP': tries = set([int(num) for num in input_string.split(' ')]) input_string = str(input()) if input_string == 'YES': numbers &= tries elif input_string == 'NO': numbers -= tries else: break input_string = str(input()) numbers = list(numbers) numbers.sort() print(' '.join([str(num) for num in numbers])) def main(): cubes() the_number_of_distinct_words_in_some_text() guess_the_number() if __name__ == '__main__': main()
true
7e4ae48b861867e6abbc7ff17617701644e364d7
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_03_functions/negative_exponent.py
562
4.34375
4
""" Statement Given a positive real number a and integer n. Compute an. Write a function power(a, n) to calculate the results using the function and print the result of the expression. Don't use the same function from the standard library. """ def power(a, n): if (n < 0): return (1 / (a ** abs(n))) else: return a ** n if __name__ == "__main__": try: print(power(float(input("Enter real number: ")), float(input("Enter power number:")))) except ValueError: print("Error, invalid value.")
true
f6ef5524112318c4507e64dd7c24bec374c71e06
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_09_reading_and_writing_files/mad_libs.py
730
4.1875
4
""" Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. """ import re REPLACE_WORDS = ["ADJECTIVE", "NOUN", "ADVERB", "VERB"] def main(): input_file = open("text_file_input.txt") output_file = open("text_file_output.txt", 'w') text = input_file.read() input_file.close() text = re.sub('[,.]', '', text) text = text.split(" ") for word in text: if word in REPLACE_WORDS: print("Please write a word to replace \"" + word + "\":") word = str(input()) output_file.write(word + " ") output_file.close() if __name__ == '__main__': main()
true
e9fdbb006ba374972ff68b0b62f83ff578a8c8cf
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_08_regular_expressions/regex_version_of_strip.py
818
4.5625
5
""" Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string. """ import re def strip_regex(line, strip=''): stripped_line = re.compile(r"^ +| +$") result = stripped_line.sub('', line) if strip != '': arg_strip = re.compile(strip) result = arg_strip.sub('', result) return result def main(): print("Please input line to strip:") line = input() print("Please input optional parameter") arg = input() print(strip_regex(line, arg)) if __name__ == '__main__': main()
true
411c81ea9bc2c6cb7083f38c68f05f7f9e373e10
jedzej/tietopythontraining-basic
/students/grzegorz_bajorski/lesson_03_functions/input_validation.py
366
4.15625
4
def collatz(number): if number % 2 == 0: return number // 2 else: return 3 * number + 1 print('Enter number') number = 0 while 1: try: number = int(input()) if collatz(number) != 1: print(collatz(number)) else: break except: print('enter an integer') print('Got 1 - break')
true
f50a67ca0fb86a594847ff090cedafd1d8631ac1
jedzej/tietopythontraining-basic
/students/myszko_pawel/lesson_01_basics/15_Clock face - 1.py
450
4.125
4
# H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60). # Determine the angle (in degrees) of the hour hand on the clock face right now. # Read an integer: H = int(input()) M = int(input()) S = int(input()) sec_in_h = 3600 sec_in_m = 60 sec_in_half_day = 43200 #12 * 3600 # Print a value: # print(a) total_sec = H*sec_in_h + M*sec_in_m + S angle = total_sec / sec_in_half_day print(angle*360)
true
11dfb2125ddb76cd84df120a4295dc52fe619a27
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_01_basics/Lesson2/ex02_06.py
396
4.15625
4
#Statement #A car can cover distance of N kilometers per day. How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M. print("Please enter how many kilometers per day your car can cover:") a = int(input()) print("Please enter length of a route:") b = int(input()) import math print("It takes " + str(math.ceil(b/a)) + " day(s) to cover a route.")
true
3ccd4ac5ff4735cd8d8f0372219100c0d579b331
jedzej/tietopythontraining-basic
/students/bedkowska_julita/lesson_03_functions/calculator.py
1,133
4.1875
4
def menu(): return """ a - add s - subtract m - multiply d - divide p - power h,? - help q - QUIT """ def get_values(): print("Input 1st operand:") var_1 = int(input()) print("Input 2nd operand:") var_2 = int(input()) print("Result:") return [var_1, var_2] print("Welcome to badly organized calculator:") option = '' print(menu()) while option != 'q': print("Enter option:") option = input() if option == "a": print("ADDING") var_1, var_2 = get_values() print(var_1 + var_2) if option == "s": print("SUBTRACT") var_1, var_2 = get_values() print(var_1 - var_2) if option == "m": print("MULTIPLY") var_1, var_2 = get_values() print(var_1 * var_2) if option == "d": print("DIVIDE") var_1, var_2 = get_values() print(var_1 / var_2) if option == "p": print("POWER") var_1, var_2 = get_values() print(var_1 ** var_2) if option == "h" or option == "?": print("HELP") print(menu()) print("GOOD BYE")
false
3095e5ec9ebe36b871411033596b3741754a3fe9
jedzej/tietopythontraining-basic
/students/pietrewicz_bartosz/lesson_03_functions/the_length_of_the_segment.py
699
4.3125
4
from math import sqrt def distance(x1, y1, x2, y2): """Calculates distance between points. Arguments: x1 -- horizontal coordinate of first point y1 -- vertical coordinate of first point x2 -- horizontal coordinate of second point y2 -- vertical coordinate of second point """ horiz_len = abs(x2 - x1) vert_len = abs(y2 - y1) return sqrt(horiz_len**2 + vert_len**2) def main(): # Read first point (x1, y1) x1 = float(input()) y1 = float(input()) # Read second point (x2, y2) x2 = float(input()) y2 = float(input()) # Calculate distance between points print(distance(x1, y1, x2, y2)) if __name__ == '__main__': main()
true
82bf7346994efd7061d730228942cf0bc3db4e43
jedzej/tietopythontraining-basic
/students/zelichowski_michal/lesson_02_flow_control/the_second_maximum.py
454
4.21875
4
"""The sequence consists of distinct positive integer numbers and ends with the number 0. Determine the value of the second largest element in this sequence. It is guaranteed that the sequence has at least two elements. """ a = int(input()) maxi = 0 second_max = 0 while a != 0: if a > maxi: second_max = maxi maxi = a elif a <= maxi: if a > second_max: second_max = a a = int(input()) print(second_max)
true
ef537ad5a6899505feab95649248519b313092ef
jedzej/tietopythontraining-basic
/students/sendecki_andrzej/lesson_01_basics/digital_clock.py
494
4.40625
4
# lesson_01_basics # Digital clock # # Statement # Given the integer N - the number of minutes that is passed since midnight - # how many hours and minutes are displayed on the 24h digital clock? # The program should print two numbers: the number of hours (between 0 and 23) # and the number of minutes (between 0 and 59). print("Enter the number of minutes from midnight") m = int(input()) res_h = (m // 60) % 24 res_m = m - (m // 60) * 60 print("It is " + str(res_h) + ":" + str(res_m))
true
a805b909977d6399953580ed271062b3ccbe840d
jedzej/tietopythontraining-basic
/students/ryba_paula/lesson_13_objects_and_classes/circle.py
1,851
4.21875
4
import math class Point: def __init__(self, x, y): self.x = x self.y = y class Circle: def __init__(self, center, radius): self.center = center self.radius = radius class Rectangle: def __init__(self, width, height, corner): self.width = width self.height = height self.corner = corner def distance_between_points(first, second): dx = first.x - second.x dy = first.y - second.y distance = math.sqrt(dx**2 + dy**2) return distance def point_in_circle(circle, point): center = circle.center radius = circle.radius return distance_between_points(center, point) <= radius def rectangle_points(rect): d_left = rect.corner d_right = Point(d_left.x + rect.width, d_left.y) u_right = Point(d_right.x, d_right.y + rect.height) u_left = Point(d_left.x, rect.height + d_left.y) points = [d_left, d_right, u_left, u_right] return points def rect_in_circle(circle, rect): points = rectangle_points(rect) for p in points: if not point_in_circle(circle, p): return False return True def rect_circle_overlap(circle, rect): points = rectangle_points(rect) for p in points: if point_in_circle(circle, p): return True return False def main(): circle = Circle(Point(150, 100), 75) point = Point(100, 100) rectangle = Rectangle(100, 10, point) print("Circle: ", circle.__dict__) print("Point: ", point.__dict__) print("Rectangle: ", rectangle.__dict__) print("Is point in the circle? ", point_in_circle(circle, point)) print("Is rectangle in the circle? ", rect_in_circle(circle, rectangle)) print("Does rectangle overlap the circle? ", rect_circle_overlap(circle, rectangle)) if __name__ == '__main__': main()
false
ef365efc8266522c0dd521d9cd57dbbf1cab1c3b
jedzej/tietopythontraining-basic
/students/medrek_tomasz/lesson_01_basics/fractional_part.py
322
4.15625
4
#!/usr/bin/env python3 try: given_number = float(input("Please enter a number:\n")) except ValueError: print('That was not a valid number, please try again') exit() real_part, fractional_part = str(given_number).split(".") if (fractional_part == "0"): print("0") else: print("0." + fractional_part)
true
39307299087bd61598c27d2af3dd1aa8f04d3be5
jedzej/tietopythontraining-basic
/students/wachulec_maria/lesson_03_functions/the_collatz_sequence_and_input_validation.py
298
4.1875
4
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 try: n = int(input('Take me number: ')) while n != 1: n = collatz(n) print(n) except ValueError: print('Error: I need integer, not string')
true
d131c1b41d71cf1ce66624f81b3c105cb64e4bdb
jedzej/tietopythontraining-basic
/students/serek_wojciech/lesson_06_dict/uppercase.py
349
4.1875
4
#!/usr/bin/env python3 """Uppercase""" def capitalize(lower_case_word): """Change the first letter to uppercase""" return lower_case_word[0].upper() + lower_case_word[1:] def main(): """Main function""" text = input().split() for word in text: print(capitalize(word), end=' ') if __name__ == '__main__': main()
true
549edc4edb0ed0667b8cbe4eff8e56b398843897
jedzej/tietopythontraining-basic
/students/BRACH_Jakub/lesson_01_basics/L01P01_Three_Numbers.py
230
4.15625
4
#!/usr/bin/env python3 number_of_factors = 3 summ = 0 for x in range(0, number_of_factors): #print('Enter the number {0:d} of {1:d}:'.format(x, number_of_factors)) summ = summ + int(input()) print ("{0:d}".format(summ))
true
ffdd1515810c94ca20ac8f3e61c5cd339b181e1c
jedzej/tietopythontraining-basic
/students/piechowski_michal/lesson_05_lists/comma_code.py
348
4.25
4
#!/usr/bin/env python3 def join_list(strings_list): if not strings_list: return "List is empty" elif len(strings_list) == 1: return str(strings_list[0]) else: return ", ".join(strings_list[:-1]) + " and " + strings_list[-1] strings_list = ['apples', 'bananas', 'tofu', 'cats'] print(join_list(strings_list))
true
57b4d4e7572261d52016a6079ff900ed100db4a4
jedzej/tietopythontraining-basic
/students/arkadiusz_kasprzyk/lesson_01_basics/area_of_right-angled_triangle.py
589
4.25
4
''' title: area_of_right-angled_triangle author: arkadiusz.kasprzyk@tieto.com date: 2018-03-05 description: Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. Every number is given on a separate line. ''' print("Reads the length of the base and the height of a right-angled triangle and prints the area.\n" "Every number is given on a separate line.") b = float(input("give base length: ")) h = float(input("give height: ")) a = b*h/2 print("The area of the triangle is {}".format(a)) input("Press Enter to quit the program.")
true
6fafbc30d64f641d0f4766207dc5a348604ead0c
jedzej/tietopythontraining-basic
/students/baker_glenn/lesson_1_scripts/previous_next.py
279
4.3125
4
# Script to print the previous and next number of a given number print("enter a number") number = int(input()) print("The next number for the number " + str(number) + " is " + str(number + 1)) print("The previous number for the number " + str(number) + " is " + str(number - 1))
true
423f23d1bce7d52dd7382fc64edc1ef64527c649
jedzej/tietopythontraining-basic
/students/piatkowska_anna/lesson_03_functions/exponentiation.py
589
4.3125
4
""" Statement Given a positive real number a and a non-negative integer n. Calculate an without using loops, ** operator or the built in function math.pow(). Instead, use recursion and the relation an=a⋅an−1. Print the result. Form the function power(a, n). """ def power(a, n): if (n == 0): return 1 else: return a * power(a, n - 1) if __name__ == "__main__": try: print(power(float(input("Enter positive real number: ")), int(input("Enter a power number: ")))) except ValueError: print("Error, invalid value.")
true
4c4aeb55d10a94f8c8db6d4ceb5f73f02aa0fc0f
jedzej/tietopythontraining-basic
/students/urtnowski_daniel/lesson_05_lists/snakify_lesson_7.py
2,308
4.40625
4
#!/usr/bin/env python3 """ snakify_lesson_7.py: Solutions for 3 of problems defined in: Lesson 7. Lists (https://snakify.org/lessons/lists/problems/) """ __author__ = "Daniel Urtnowski" __version__ = "0.1" def greater_than_neighbours(): """ This function reads a list of numbers and prints the quantity of elements that are greater than both of their neighbors """ print("Problem: Greater than neighbours") numbers = [int(a) for a in input().split()] counter = 0 for i in range(1, len(numbers) - 1): if numbers[i - 1] < numbers[i] and numbers[i + 1] < numbers[i]: counter += 1 print(counter) def swap_min_and_max(): """ This function reads a list of unique numbers, swaps the minimal and maximal elements of this list and prints the resulting list. """ print("Problem: Swap min and max") numbers = [int(a) for a in input().split()] idx_max = 0 idx_min = 0 for i in range(1, len(numbers)): if numbers[i] > numbers[idx_max]: idx_max = i if numbers[i] < numbers[idx_min]: idx_min = i if idx_max != idx_min: numbers[idx_min], numbers[idx_max] = numbers[idx_max], numbers[idx_min] stringified_nums = [str(num) for num in numbers] print(' '.join(stringified_nums)) def the_bowling_alley(): """ This function reads the number of pins and the number of balls to be rolled, followed by pairs of numbers (one for each ball rolled). The subsequent number pairs represent the start to stop (inclusive) positions of the pins that were knocked down with each role. Then it prints a sequence of characters representing the pins, where "I" is a pin left standing and "." is a pin knocked down. """ print("Problem: The bowling alley") pins_num, balls_num = [int(num_str) for num_str in input().split()] pins_states = pins_num * ['I'] for i in range(balls_num): start, end = [int(num_str) for num_str in input().split()] for k in range(start - 1, end): pins_states[k] = '.' if 'I' not in pins_states: break print(''.join(pins_states)) def main(): greater_than_neighbours() swap_min_and_max() the_bowling_alley() if __name__ == '__main__': main()
true
a32193a1eba244238f9eea90c930927eae10ac8d
jedzej/tietopythontraining-basic
/students/saleta_sebastian/lesson_02_flow_control/the_number_of_elements_equal_to_the_maximum.py
416
4.25
4
def get_how_many_elements_are_equal_to_largest_element(): maximum = 0 num_maximal = 0 element = -1 while element != 0: element = int(input()) if element > maximum: maximum, num_maximal = element, 1 elif element == maximum: num_maximal += 1 print(num_maximal) if __name__ == '__main__': get_how_many_elements_are_equal_to_largest_element()
false
0f1ea0541aced96c8e2fe19571752af04fdf488d
jedzej/tietopythontraining-basic
/students/semko_krzysztof/lesson_01_basic/area_of_right-angled_triangle.py
408
4.1875
4
# Problem «Area of right-angled triangle» (Easy) # Statement # Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. # Every number is given on a separate line. print('Please input triangle\'s base:') base = int(input()) print('Please input height of the triangle:') height = int(input()) print('Triangle\'s area is ' + str((base * height) / 2))
true