blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ed27b521d9e887bc1d091a099a5c8e561e1c9119
Noburu-Hasashi/FaceDetect
/noburu-hasashi.py
293
4.40625
4
def is_palindrome(string): # enter a string value while calling the function if string == string[::-1]: return True # returns TRUE if the given string IS a palindrome else: return False # returns FALSE if the given string IS NOT a palindrome
true
64cb0d8fcc5b573b0f1730d28d2dc6a55b69585a
metse/py
/binary-search/recursive.py
687
4.125
4
def binary_search_recursive(list, target, left, right): if left > right: return False middle = (left + right) // 2 print('Middle', list[middle]) if (list[middle] == target): return True elif target < list[middle]: print('right') print(list[left:middle - 1]) return binary_search_recursive(list, target, left, middle - 1) else: print('left') print(list[middle + 1:right]) return binary_search_recursive(list, target, middle + 1, right) numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # 40 as an example # [10, 20, 30, 40] # [10, 20, 30] # [20, 30, 40] # [30, 40] print(binary_search_recursive(numbers, 40, 0, len(numbers) - 1))
true
28711094ce9bd5469fa68786db2e94e68b9a8f0e
muhammadmuzzammil1998/CollegeStuff
/MCA/Machine Learning/fibonacci.py
285
4.125
4
import sys def fibonacci(n): f, s = 0, 1 series = "{} {} ".format(f, s) for i in range(2, n): series += "{} ".format(f+s) f, s = s, f+s return series term = int(sys.argv[1]) print("Fibonacci series till {} term".format(term)) print(fibonacci(term))
false
373f1adb05dad99e16471fc968820a5565b5f9bc
cs-fullstack-2019-fall/codeassessment2-Kenn-CodeCrew
/q1.py
1,371
4.40625
4
# ### Problem 1 # Ask the user to enter a number. userInputInteger = int(input("Enter a number: ")) # Using the provided list of numbers, use a for loop to iterate the array and print out all the values that are smaller than the user input and print out all the values that are larger than the number entered by the user. # ``` # # Start with this List list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7] listOfSmallerNumbers = [] listOfLargerNumbers = [] for eachNumberInArray in list_of_many_numbers: if userInputInteger > eachNumberInArray: listOfSmallerNumbers.append(eachNumberInArray) elif userInputInteger < eachNumberInArray: listOfLargerNumbers.append(eachNumberInArray) # print(listOfSmallerNumbers) # print(listOfLargerNumbers) print("The User entered " + str(userInputInteger)) stringOfSmallerNumbers = "" for eachNumber in listOfSmallerNumbers: stringOfSmallerNumbers += str(eachNumber) + " " print(stringOfSmallerNumbers + "are smaller than " + str(userInputInteger)) stringOfLargerNumbers = "" for eachNumber in listOfLargerNumbers: stringOfLargerNumbers += str(eachNumber) + " " print(stringOfLargerNumbers + "are larger than " + str(userInputInteger)) # ``` # Example Input/Output if the user enters the number 9: # ``` # The User entered 9 # 1 2 7 are smaller than 9 # 12 24 34 10 are larger than 9 # ```
true
401a98c180144f58a23eb9889b5c932af02cc69f
berkevlk/yazilim
/python/projeler/hesapmakinesi.py
607
4.125
4
num1=int(input('1. sayıyı giriniz ')) #buradaki int komutu tam sayı girilmesini sağlar num2=int(input('2. sayıyı giriniz '))#buradaki input değeri kullnıcıdan değer alır op=input('işlemi seçiniz(+,-,*,/) ') if op=='*': #buradaki yazılan koşullar uygunsa altındaki kodu çalıştırır. print(num1, '*', num2,'=', num1*num2) elif op=='+': #elif komutu değilse eğer anlamı katar.yani else if yazmak yerine komut yazmayı hızlandırır. print(num1, '+', num2,'=', num1+num2) elif op == '-': print(num1, '-', num2, '=', num1-num2) elif op=='/': print(num1,'/',num2,'=', num1/num2)
false
4426909c19f58cd40c617a295f68b5c7e110b75f
basanneh/python_DataStructures
/linkedlist.py
1,501
4.21875
4
class Node(object): def __init__(self,data): self.data = data self.next = None class linkedlist(object): def __init__(self): self.head = None self.size = 0 def insert(self,data): self.size +=1 current = self.head temp = Node(data) if current is None: self.head = temp else: while(current.next is not None): current = current.next current.next = temp def size(self): return self.size def insertStart(self,data): self.size +=1 temp = Node(data) if self.head is None: self.head = temp else: temp.next =self.head self.head = temp def display(self): current = self.head if current is None: print("The list is empty ") return else: while(current): print("%d " %current.data,end=' ') current =current.next print() def reverse_linkedlist(self): prev = None current = self.head while current: nxt = current.next current.next = prev prev = current current = nxt self.head = prev l1 =linkedlist() l1.insert(10) l1.insert(20) l1.insert(30) l1.display() print() l1.insertStart(5) l1.display() l1.insertStart(0) l1.display() print() l1.reverse_linkedlist() print("Reverse Linkedlist") l1.display()
true
27ba10f99c8d551072aa3abc65c463a1b445310d
eatdembeanz/Python-Code-Samples-1
/Week 7 Problem 1.py
333
4.25
4
#Benjamin Page #2/28/2019 #Problem : Write a function areaOfCircle(r)which returns the area of a circle of radius r.Make sure you use the math module in your solution ##Note that the function only works with floats and integers. def areaofcircle(x): import math A = math.pi * (x * x) return A print(areaofcircle(5.5))
true
a3c201b807191543c6c863a424d8b5f6bbc02cf9
eatdembeanz/Python-Code-Samples-1
/Week6 Problem 6.py
378
4.3125
4
#Benjamin Page #2/21/2019 #Calculates the factorial of a given value. Prints both the calculated value as well as the same value run through the math module. import math facto = int(input("Please input number to factorialize:")) x = 1 for i in range(1,facto+1): x = x*i print("Program-calculated factorial:",x) print("Module-calculated factorial:",math.factorial(facto))
true
d361c33c63f97f12d996c654588474a0036222ad
eveafeline/coding-challenges
/python/arrays_n_strings/3_URLify_test.py
1,293
4.28125
4
""" Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.) e.g. INPUT: "Mr John Smith ", 17 OUTPUT: "Mr%20John%20Smith" """ from collections import namedtuple Case = namedtuple("Case", ["test_string", "length", "expected"]) def URLify(s, n): trimmed = s[:n] return trimmed.replace(' ', '%20') def URLify_regex(s, n): import re rex = re.sub(r'[^\w\s]', ' ', s) return re.sub(r'\s', '%20', rex[:n]) def test_run(): test_cases = [ Case("Mr John Smith ", 13, "Mr%20John%20Smith"), Case("Mr John Smith ", 15, "Mr%20John%20Smith%20%20")] for case in test_cases: result = URLify(case.test_string, case.length) assert result == case.expected def test_regex(): test_cases = [ Case("Mr John Smith ", 13, "Mr%20John%20Smith"), Case("Mr John Smith ", 15, "Mr%20John%20Smith%20%20")] for case in test_cases: result = URLify_regex(case.test_string, case.length) assert result == case.expected
true
fac1b3f0b0049168620df6cdfbd29e6b7e7d68e6
tan-map/python-directory-
/tower.py
1,091
4.21875
4
class Disk: def __init__(self,bk): self.bk=bk def diameter(self): return self.bk class Stack: def __init__(self): self.items=[] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() def hanoi(n, source, helper, target): if n > 0: hanoi(n - 1, source, target, helper) if source: print('Tru 1:',source.items) print('Tru 2:',helper.items) print('Tru 3:',target.items) print('====================') target.push(source.pop()) hanoi(n - 1, helper, source, target) disk1=Disk(1).diameter() disk2=Disk(2).diameter() disk3=Disk(3).diameter() stack1=Stack() stack1.push(disk3) stack1.push(disk2) stack1.push(disk1) if __name__ == '__main__': print('Tru 1 before:',stack1.items) if __name__ == '__main__': print('==================') stack2=Stack() stack3=Stack() hanoi(len(stack1.items),stack1,stack2,stack3) if __name__ == '__main__': print('Result') if __name__ == '__main__': print('Tru 1:',stack1.items) if __name__ == '__main__': print('Tru 2:',stack2.items) if __name__ == '__main__': print('Tru 3:',stack3.items)
false
4aeb79c2407766c30d3cb6afb47a251091c71dab
jzhan160/Python
/PythonBasic/set.py
507
4.21875
4
# Set: only contains immutable obj set1 = {1,3,4,1,4,5} print(set1) set2 = set() # create an empty set. set = {} will create a dict # convert other types to set set2 = set([1,2,3,2]) print(set2) set2 = set('hello') print(set2) set2 = set({'a':1,'b':2}) # only use keys print(set2) set2.add(100) print(set2) set2.update((10,30,40)) print(set2) res = set2.pop() print(res) res = set2.remove(40) print(set2) # 交集、并集、差集、异或集、子集、真子集 # & | - ^ <= <
true
236306e2dc98b6f8455892658fcc52e62bcf3e22
rrathbone/python-learning
/number_guess.py
2,030
4.625
5
"""Wanna play a game? In this project, we'll build a program that rolls a pair of dice and asks the user to guess a number. Based on the user's guess, the program should determine a winner. If the user's guess is greater than the total value of the dice roll, they win! Otherwise, the computer wins. The program should do the following: Randomly roll a pair of dice Add the values of the roll Ask the user to guess a number Compare the user's guess to the total value Decide a winner (the user or the program) Inform the user who the winner is""" from random import randint from time import sleep """Prompt user for their guess and store in a variable. Use int to change the type of the input from a string to an integer.""" def get_user_guess(): user_guess = int(raw_input("Guess a number: ")) return user_guess """roll_dice allows user to specify the number of sides the dice has. This function simulates the rolling of a pair of dice. randint generates a random integer between 1 and number_of_sides max_val is an int so needs to be converted to str()""" def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sides) max_val = number_of_sides * 2 print "The maximum possible value is: " + str(max_val) sleep(1) #call the get_user_guess function so we have access to it within this function user_guess = get_user_guess() if user_guess > max_val: print "Your guess was too high!" return else: print "Rolling..." sleep(2) # user string formatting - %d is used to format integers print "The first value is: %d" % first_roll sleep(1) print "%d" % (second_roll) sleep(1) total_roll = first_roll + second_roll print "%d" % (total_roll) print "Result" sleep(1) if user_guess > total_roll: print "You won!" return else: print "You lost." return roll_dice(6)
true
23f934815cb70314cdc9cbe264a560b99e898ab8
ankitomss/python_practice
/increasingTripletSubS.py
479
4.25
4
def increasing_triplet(nums): n=len(nums) if not n or n<2: return False m1, m2=n-1, -1 for i in range(n-2, -1, -1): if m2 is not -1 and nums[i] < nums[m1] and nums[i] < nums[m2]: return True elif nums[i] < nums[m1] and (m2 is -1 or nums[i] > nums[m2]): m2=i elif nums[i] > nums[m1]: m1=i m2=-1 return False nums=[1,2,3,4,5] nums1=[5,4,3,2,1] print increasing_triplet(nums1)
false
b625fdcb1d627dec4e578c08a49f8b6ac967486a
joysreb/python
/specifiedvalues in group.py
236
4.125
4
def value_present(n): group=[1,2,3,4,5] if n in group: print("the number is present in the group") else: print("the number is outside the group") n=int(input("enter the number:")) print(value_present(n))
true
cf7616f9c467483a89a6b212228db2843120066f
KatieStevenson/Sandbox
/password_check.py
865
4.59375
5
''' Creates a basic password checking program. ''' min_length = 8 # Asks user for password and then sends the password off to a function of be validated. def main(): print("Please create a password with a minimum of 8 characters: ") password = input("> ") return valid_char_length(password) # Checks password fulfills minimum length and prompts user if invalid length. def valid_char_length(password): char_length = (len(password)) if min_length > char_length: print("The password you have entered is invalid") return main() else: return convert_to_asterisks(password) # Converts each character in password into an asterisks and then displays it to the user. def convert_to_asterisks(password): print("Your password is: ") for char in password: print(char.replace(char, '*'), end = '') main()
true
5d1bc5cd1e876383466c5dddd7c351699589c7d1
ksp1510/Coding_in_Class_Day1
/Que_2.py
765
4.15625
4
""" Author: Kishankumar Sanjaybhai Patel Course: Emerging Technologies Student Id: C0805822 Coding in class Question 2 """ # Write a Python program which accepts the user's first and last name and print them in reverse order with a space # between them. print("Welcome to the program that takes first and last name from user and print it in reverse order\n") fname = input("Enter your first name: ").capitalize() lname = input("Enter your last name: ").capitalize() name = fname+" "+lname print(f"\nUser name is '{name}'") print(f"\nReverse of user's name using reverse indexing:") print(f"'{name[::-1].lower()}'") print(f"\nReverse of user's name using for loop:") name1 = "" for x in name: name1 = x+name1 print(f"'{name1.lower()}'") print("\nThank you for using the program")
true
703c198ff7660f2b36de69aca93a95e3f9824144
RonanLeanardo11/Python-Lectures
/Lectures, Labs & Exams/Lecture Notes/Lect 6 -/Lecture 10 Abstract Classes/Exercise 3.py
1,141
4.15625
4
class Result: moduleName = "" Grade = 0 def __init__(self, Mod_Name="", Grade=0): self.moduleName = Mod_Name self.grade = Grade def print(self): print("Module Name: ".format(self.moduleName)) print("Grade Name: ".format(self.grade)) class Student: name = "" XNumber = "X" StudentResults = [] def __init__(self, name_in, X_in, Results_in): self.name = name_in self.XNumber = X_in self.StudentResults = Results_in def add_result(self, grade): self.grade = grade self.StudentResults.append(self.grade) def print(self): Result.print(self) print("Student Name: ".format(self.name)) print("X Number: ".format(self.XNumber)) print("Results: ".format(self.StudentResults)) # In your main program body: #  Create a Student with appropriate arguments. Student1 = Student("Ronan", "X00152190", 80) #  Add three results (with arguments of your choice) Result1 = Result("KComp", 40) Result2 = Result("BComp", 50) Result3 = Result("FComp", 60) #  Print the Students details Student1.print()
true
3b56bd63ad39c52532df8536114b889d87c67390
RonanLeanardo11/Python-Lectures
/Lectures, Labs & Exams/Lecture Notes/Lect 3 - Functions/Lab 4.2.py
864
4.125
4
# Lab 4.2 X001522190 # Create a definition called “discount” that has two arguments. The first argument is the RRP and is # required, the second argument is a percentage discount. The second argument should have a default # value of 0.00% if the user only enters one argument the required RRP. # The definition should print the sale price which is defined by the following formula: # Test this definition with the values # • 100, 50 # • 100 # • 100, 20 # Definition def discount(RRP,discount_perc=0.00): sale_price = RRP * (1 - (discount_perc/100)) sale_price = sale_price.__round__(2) print("Sale price is €{}".format(sale_price)) # inputs RRP = int(input("Please enter the RRP: ")) discount_perc = float(input("Please enter discount %: ")) # Call Function - providing above inputs (RRP, discount_perc) discount(RRP, discount_perc)
true
d169007d98e5c6ab7b5695dfd075c8dd0e8ca9e2
bhojnikhil/LeetCodeProblems
/Grokking/Two Pointers/dutch_oven_fart_flag_shit.py
815
4.25
4
# Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array. # The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists of three different numbers that is why it is called Dutch National Flag problem. # Example 1: # Input: [1, 0, 2, 1, 0] # Output: [0 0 1 1 2] def dutch_flag(arr): left = 0 right = len(arr)-1 i = 0 while i<=right: if arr[i]==0: arr[i], arr[left] = arr[left], arr[i] i+=1 left+=1 elif arr[i]==1: i+=1 else: arr[i], arr[right] = arr[right], arr[i] right-=1 return arr print(dutch_flag([1, 0, 2, 1, 0]))
true
c5ebc43c8d7fdeb14ea0cb8214820611f37a7e3e
JohnLoomis/InterviewInPython
/InterviewCake/tree_bst_checker.py
935
4.1875
4
from InterviewCake.tree_binary import * def largest(node): while node.right: node = node.right return node # Use depth-first search testing for validity for each node as we go # O(n) time and O(h) space where h is height of tree def is_binary_search_tree(node): if not node: return True if not node.left: if not node.right: return True return node.value < node.right.value and node.value < largest(node.right).value \ and is_binary_search_tree(node.right) elif not node.right: return node.value > node.left.value and node.value > largest(node.left).value \ and is_binary_search_tree(node.left) return node.left.value < node.value < node.right.value \ and largest(node.left).value < node.value < largest(node.right).value \ and is_binary_search_tree(node.left) and is_binary_search_tree(node.right)
true
0ae764a4a350e9b52bf1398db7c4e7ea9a77894a
bettertaught/python_notes
/oops/encapsulation_examples/encapsulation.py
497
4.25
4
class Car: def __init__(self, make='Ford', model='Pinto', year='1971', color='orange'): self._make = make self.__model = model self.__year = year self.__color = color def move_forward(self, speed): print("Your %s is moving forward at %s" % (self.__model, speed)) def move_backward(self, speed): print("Moving backward at %s" % speed) mycar = Car() print mycar._Car__model # This is how you access __ attribute # print mycar.__model
true
48286fb11fe38c603458a65040f252adac9e66b4
CloudAssignment/Assignment
/testing_for_cloud.py
1,945
4.21875
4
import time import datetime ''' Program that will run y x n x n iterations (basically very inefficient) In total there will be 18 points that you can plot on the graph Appends the Points in a File called VanillaWindows.txt Looks like : Execution Time | Iteration 0 3s etc.... @Author: Sebastian Racki ''' def run(t,n,file): text = open(file,"w") text.write("Execution Time | Iteration" + '\n') text.write("--------------------------" + '\n') iteration = 0 start = time.time() for y in range(t): for amount in range(n): for x in range(n): amount * x iteration +=1 this = (time.time() - start).__round__(5) text.write(str(this) + '\t' + str(iteration) + '\n') text.close() run(100,2000,"VanillaWindows.txt") ''' Function run will take three paramaters(t = how many points we would like,n = how many iterations,file) hours is going to be how many hours the program should run for x is going to be the file that we are going to write the points to #we want the output of the file to look like this v Execution Time | Iteration ___________________________ 20 1 30 2 ''' ''' Function 2 is going to be the graph So we will have two files one from the Virtual Machine with all the points and one from the normal machine without the Virtual one and we are going to read the points and put them on a graph and get the line of best fit and see how they compare based on that ''' def graph(file1,file2): pass ''' Function 3 will evalute the results and return a conclusion for us So it will return which one is more efficient and it will be based on these points 1. How much memory the system used 2. How much time it took for each execution 3. How much of the CPU was in use 4. How many threads we used in the process @return this will all be logged inside another txt file and returned in a nice format '''
true
0e6878790570468855b19532ed5f28702dea9f7f
Iiridayn/sample
/Coderbyte/09b-LongestWord.py
673
4.15625
4
# Challenge: Return first longest word in str. 10 points, 12 mins, 1 failed test ("123456789 98765432") def LongestWord(sen): word = "" longest = "" state = 0 # 1 is in word for c in sen+' ': # too lazy to fix it right, just force the else on last word if (ord(c) in range(ord('a'), ord('z')+1) or ord(c) in range(ord('A'), ord('Z')+1)): state = 1 word += c else: # reached a non-word character if state == 1 and len(word) > len(longest): longest = word word = "" state = 0 return longest # keep this function call here # to see how to enter arguments in Python scroll down print LongestWord(raw_input())
true
7c985f6e776a7aa1fc80c0bfc8ae22ca302d910c
Dawca22/zajeciaPyt4
/dzien3/War2.py
793
4.3125
4
#nazwisko = "Kowalska" #if nazwisk[-1] == "a": # print('To kobieta') #else nazwisko[-1] != "a": # print ('To mężczyzna') #print ("Koniec programu") nazwisko = input("Podaj nazwisko:\n ") #print(type(nazwisko)) #jeśli w stringu są cyfry napisać komunikat i przerwać program if not nazwisko.isalpha(): print("Muszą być tylko litery") #usunąć whistpace z początku i końca naz_czyste = nazwisko.strip() #nazwisko = nazwisko.strip() #zamienić wszystkie litery na duże naz_czyste = nazwisko.upper() print(naz_czyste) if naz_czyste [-1] == "A": print("Chyba jesteśn kobietą.") elif naz_czyste.endswith ("SKI"): print("Najprawdopodobniej jesteś mężczyzną") elif naz_czyste.isupper(): print("Chyba jesteś złośliwa :/") print ("Koniec programu")
false
f748b0c4f6ee3ec381ba5e1970a65365767b368d
oguznsari/python-cs
/data types/string.py
2,045
4.3125
4
""" If you have a single quote(') in your string use double quotes(") or escape \' and vice versa or use three quotes Think of a string as a string of individual characters """ message = "Hello World!" print(message) print(len(message)) print(message[:5]) print(message[-6:]) print(message.lower()) # lowercase method print(message.upper()) # uppercase print(message.count('l')) # 3 print(message.find('World!')) # 6 --> start index print(message.find('Universe')) # -1 does not contains message = message.replace('World', 'Universe') print(message) # concatenating greeting = 'Hello' name = 'Michael' # message = greeting + ', ' + name + '. Welcome!' # message = '{}, {}. Welcome!'.format(greeting, name) # format string message = f'{greeting}, {name}. Welcome!' # f string --> easy format string Python 3.6 and higher print(message) message = f'{greeting}, {name.upper()}. Welcome!' # f strings are reaaly useful print(message) print(dir(name)) # all of the attributes and methods that we have access to for utils in dir(name): print(utils) print(help(str)) print(help(str.lower)) # A bit of string formatting for i in range(1, 11): sentence = 'This value is {:03}'.format(i) # 0 pads all the way up to 3 digits print(sentence) pi = 3.14159265 sentence = 'Pi is equal to {:.2f}'.format(pi) # 2 decimal places print(sentence) sentence = '1 MB is equal to {:,} bytes'.format(1000**2) # comma(,) separated values print(sentence) sentence = '1 MB is equal to {:,.2f} bytes'.format(1000**2) # comma(,) separated values and 2 decimal places print(sentence) import datetime my_date = datetime.datetime(1993, 2, 28, 12, 30, 45) print(my_date) # February 28th, 1993 sentence = '{:%B %dth, %Y}'.format(my_date) print(sentence) # February 28th, 1993 fell on a Sunday and was the 059 day of the year sentence = '{0:%B %dth, %Y} fell on a {0:%A} and was the {0:%j} day of the year'.format(my_date) print(sentence)
true
4434a745037da5928184d2a7ba5e32b06c63a531
domyounglee/Code_interview
/Python/Bubble_sort.py
317
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def Bubble_sort(data): #오름차순 for i in range(len(data)-1): for j in range(i+1,len(data)): if data[i]>=data[j]: temp=data[i] data[i]=data[j] data[j]=temp return data if __name__ == '__main__': data=[5,1,1,1,1,1,6] print(Bubble_sort(data))
false
9bbfbb073fafa949cc7a862702b39f8087020642
JosephDrahos/EE361_Lab4
/main.py
2,801
4.125
4
# EE361 Lab 4 # Joseph Drahos & Tarak Patel import palindrome import transposition import substitution # Transposition str = "this is transposition" #sender generates plaintext st1 = transposition.scramble2Encrypt(str) #sender generates passkey using scramble2Encrypt (odd characters before even characters) print("Transposition Cypher encryption of: " + str) print("Encryption: " + st1) print("Transposition Decryption: " + transposition.scramble2Decrypt(st1)) #receiver decrypts message to recover original plaintext print() # Substitution with key key = substitution.keyGen() #sender generates key which consists of random characters of the alphabet print("Generated key for Substitution Cypher: " + key) print("Substitution Cypher encyption of: substitutioncypher") str = "a white fox jumps on snow" st1 = substitution.substitutionEncrypt(str, key) #Sender encrypts plaintext with generated key print("Encryption: " + st1) print("Substitution with key Decryption: " + substitution.substitutionDecrypt(st1, key)) #Receiver decrypts ciphertext and recovers plaintext print() # Substitution with passkey str = "substitutioncypher" passkey = substitution.genKeyFromPass("hello") #Sender generates passkey from the passphrase "hello" print("Passphrase key for Substitution Cypher: " + passkey) print("Substitution Cypher with passphrase key encryption of: substitutioncypher") st1 = substitution.substitutionEncrypt(str, passkey) #Sender generates ciphertext from provided passkey and the plaintext print("Encryption: " + st1) print("Substitution with passkey Decryption: " + substitution.substitutionDecrypt(st1, passkey)) #Receiver decrypts ciphertext using the passkey generated by the sender - provided passphrase print() # Transposition 2 str = "this is transposition2" st1 = transposition.scramble2Encrypt2(str) #Sender encrypts message using transposition cipher which separates the string into even and odd characters and generates a ciphertext by printing even characters before odd characters print("Transposition Cypher with evens first encryption of: " + str) print("Encryption: " + st1) print("Transposition2 Decryption: " + transposition.scramble2Decrypt2(st1)) #Receiver decrypts cipher text and recovers plaintext print() print("Palindrome Function Testing:") print("Testing madam: ", palindrome.palindromCheck("madam")) print("Testing nurses run: ", palindrome.palindromCheck("nurses run")) print("Testing a: ", palindrome.palindromCheck("a")) print("Testing a man a plan a canal panama: ", palindrome.palindromCheck("a man a plan a canal panama")) print("Testing aabb: ", palindrome.palindromCheck("aabb")) print("Testing race car: ", palindrome.palindromCheck("race car")) print("Testing nurse run: ", palindrome.palindromCheck("nurse run"))
true
a955cd041bb724c6eb204355329d8c21b4ead5c8
Polaricicle/practical04
/q6_sum_digits.py
921
4.46875
4
#Filename: q6_sum_digits.py #Author: Tan Di Sheng #Created: 20130221 #Modified: 20130221 #Description: This program writes a function that sums up the digits #of an integer print("""This program writes a function that sums up the digits of an integer.""") #Creates a loop so that the user can keep using the application #without having to keep restarting the application while True: def sum_digits(n): if n == 0: return n else: return (n % 10) + sum_digits(int(n / 10)) while True: n = input("\nEnter an integer: ") try: int(n) except: print("\nPlease input an integer") else: break n = int(n) print(sum_digits(n)) #gives the user an option to quit the application contorquit = input("\nContinue? Type no to quit: ") if contorquit == "no": quit() else: continue
true
d5d9fde902fdd9fa28a3f9a1024807ac64355289
Carmeganda/ASSIGNMENT-3-BSCOE-1-6
/buying_apples&oranges.py
1,431
4.1875
4
# Create a program that will ask how many apples and oranges you want to buy. # Display the total amount you need to pay if apple price is 20 pesos and orange is 25. # Display the output in the following format. # The total amount is ______. def showPriceAp(): _PriceAP = 20 print(f"The price of an apple is {_PriceAP} pesos.") return _PriceAP def showPriceOr(): _PriceOR = 25 print(f"The price of an orange is {_PriceOR} pesos.") return _PriceOR def amountAP(): _AmountAP = int(input("How many apples will you buy? ")) return _AmountAP def amountOr(): _AmountOr = int(input("How many orange will you buy? ")) return _AmountOr def totalP(): _TPofApple = applePrice*appleQuantity _TPofOrange = orangePrice*orangeQuantity _TotalPrice = _TPofApple + _TPofOrange return _TotalPrice def display(TtlPrice): print(f"The total amount is {TtlPrice} pesos. ") # steps # 1. Ask how many apples you want to buy then save the variable. appleQuantity = amountAP() # 2. Ask how many oranges you want to buy then save the variable. orangeQuantity = amountOr() # 3. Show the price of an apple then set as a variable. applePrice = showPriceAp() # 4. Show the price of an orange then set as a variable. orangePrice = showPriceOr() # 5. Solve for the total price then save to variable. ttlPrice = totalP() # 6. Display the total price. total = display(ttlPrice)
true
d8c06bd49b92d8e74797e6d616e689aed859798e
sujjanyun/python3
/cats.py
613
4.25
4
class Cat: # CLASS ATTRIBUTE - applies to all cats! species = "Mammal" # INSTANCES ATTRIBUTES - different for each instance of cat # self means it is pointing back to itself (the class of cat) def __init__(self, name, age): super().__init__() self.name = name self.age = age # INSTANCE METHOD - different for each instance of cat def description(self): return "{} is {} years old.".format(self.name, self.age) gus = Cat("Gus", 10) beans = Cat("Beans", 11) print(gus.name) print(gus.age) print(gus.species) print(gus.description()) print(beans.description())
true
0b1d80db6e721b2fba735e3a2986ed69fc45e367
bdejene19/PythonMLandTensorflowCourse
/Clustering.py
1,265
4.1875
4
# Clustering is the first unsupervised algorithm we've looked at # is very powerful # clustering --> used only when having lots of input information (features) but have no output information (i.e. labels) # clustering finds like data points and finds the locations of those data points ''' we will be doing be doing clustering via K-means # first we randomly pick points to place centroids # Centroids: where our current cluster is defined # random K-centroids are placed where ever on the graph of data points # each data point is assigned to a cluster by distance --> find the uclivian or manhattan distance # assign the data point to the closest centroid ==> we then do this for every single data point Then you move the centroid to the middle of all its data points (its center of mass) Repeat the process process with the re-evaluated placement of the centroids Keep doing this where none of the data points are changing which centroid they belong to i.e. centroids are as central as possible ==> now have cluster with centroids resembling center of mass When we have have a new data point --> we see the distance to the centroids for each cluster depending on distance, you assign data point to a particular cluster that has an assigned label '''
true
4f32e4dd311542358feae85bafc2bc268a80a663
zipporia/Phyton-Training
/OOP/project.py
746
4.15625
4
name = input("Enter Name: ") age = input("Enter Age: ") gender = input("Enter Gender: ") if age.isalpha(): print("age must be a number") else: if int(age) <= 0: print("age must be 1 and up") else: if gender != "male" and gender != "female": print("there is an error in your input data") else: if gender.lower() == "male" and int(age) >= 13: print("Hello", name, "You are handsome teenager.") elif gender.lower() == "female" and int(age) >= 13: print("Hi", name, "You are a beautiful teenager.") elif gender.lower() == "male" or gender.lower() == "female" and int(age) <= 12: print("Hello", name, "You are young")
false
9a6b7fc817aa50c72e05f683f624d9bdb4a7c0cb
SuciuPatrick/FP---Python-projects
/sapt1/Homework/B_11.py
1,306
4.125
4
''' [11] The palindrome of a number is the number obtained by reversing the order of digits. E.g. palindrome (237) = 732). For a given natural number n, determine its palindrome. ''' def reverseNumber(nr): ''' This function return the reverse of a number input- integer output- integer ''' rev = 0 while (nr): rev = rev * 10 + nr % 10 nr //=10 return rev def printNumber(nr): print("Inversul numarului este: " + str(nr)) def reverseTests(): assert reverseNumber(123)==321 assert reverseNumber(53214)==41235 assert reverseNumber(65432)==23456 assert reverseNumber(9)==9 assert reverseNumber(1111)==1111 def ui_homework(): while True: try: nr = input('Insert Number->') nr = int(nr) if (nr < 0): print("enter a positive number.") else: resolve = reverseNumber(nr) printNumber(resolve) return except ValueError as ve: print ("Illegal integer value given!") def run(): while True: x = input('Press y/n: ') if x == 'y': ui_homework() elif x == 'n': return else: print('invalid command()') reverseTests() run()
true
884214abde773cdb023c471d39525b8d0a098f14
distractedpen/datastructures
/ExpressionParser.py
721
4.1875
4
#postfix parser from stack import Stack as Stack operands = Stack(3) operators = "^*/+-" string = input("Enter an expression in postfix notation: ") for x in string: a = 0 b = 0 c = 0 if x not in operators: operands.push(x) else: b = float(operands.pop()) a = float(operands.pop()) if x == "^": c = a**b elif x == "*": c = a*b elif x == "/": c = a/b elif x == "+": c = a+b elif x == "-": c = a-b else: print("Error, cannot parse {0}.".format(x)) break operands.push(c) print(operands.pop())
true
e9dd8cf7e0f82dc82cbfe4d3fad725d9545a707e
mkasulecoder/python
/whileloops.py
1,165
4.1875
4
# while loopa will iterate whenever the condition is true # while boolean_condition: # do_something # else: # do something different. x = 0 while x < 5: print(f"The current value of x is {x}") x += 1 # same as x = x+1 else: print("X is not less than 5") # Break , continue and pass statements # Break: breaks out of a closest enclosing loop # continue: goes to the top of the closeest enclosing loop # pass: does nothing at all. Its used to hold onto a script before testing not to return an error. # PASS x = [1, 2, 3] for item in x: # haven't decided yet what to print yet from these items but want to end script for future use pass print("End of script for now, will return later") # CONTINUE - USED TO SKIP AN ITEM IN SEQUENCE name = "mark" for letter in name: if letter == "a": # skip letter and return to loop sequence. continue print(letter) print() # BREAK name1 = "kasule" for letter in name1: if letter == "u": break print(letter) # while and break numb1 = 0 while numb1 < 6: if numb1 == 5: break print(numb1) numb1 += 1
true
4ea6a43431f70a89c7ac7a9fef3a70e4beef476a
akankshaagrawal26/BasicPython
/Palindrome.py
378
4.5
4
str = input('Enter the string to be checked :') # Inputs string from the user def palindrome(str): ''' Returns the reverse of the string ''' return str[::-1] check = palindrome(str) print("Reversed string is :",check) if str == check: print("String entered is a palindrome string") else: print("String entered is not a palindrome string")
true
ff0753ea5eb3362d924ab0f78aee46e6fa8aadee
mbiannaccone/stacks-equal_stacks
/equal_stacks.py
1,755
4.25
4
""" You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they're all the same height, then print the height. The removals must be performed in such a way as to maximize the height. Note: An empty stack is still a stack. Input Format The first line contains three space-separated integers, n1, n2, and n3, describing the respective number of cylinders in stacks 1, 2, and 3. The subsequent lines describe the respective heights of each cylinder in a stack from top to bottom: - The second line contains n1 space-separated integers describing the cylinder heights in stack 1. - The third line contains n2 space-separated integers describing the cylinder heights in stack 2. - The fourth line contains n3 space-separated integers describing the cylinder heights in stack 3. Output Format Print a single integer denoting the maximum height at which all stacks will be of equal height. """ n1, n2, n3 = raw_input().strip().split(' ') n1, n2, n3 = [int(n1), int(n2), int(n3)] h1 = map(int, raw_input().strip().split(' '))[::-1] h2 = map(int, raw_input().strip().split(' '))[::-1] h3 = map(int, raw_input().strip().split(' '))[::-1] h = [h1, h2, h3] sums = [sum(h1), sum(h2), sum(h3)] while ((sums[0] != sums[1]) or (sums[0] != sums[2])): max_index = sums.index(max(sums)) remove = h[max_index].pop() sums[max_index] -= remove print sums[0]
true
c0053d1b86e793c9ac4577489646b36639a2dc6f
Luorinz/Lintcode
/637_Valid Word Abbreviation.py
2,041
4.25
4
#Easy # Given a non-empty string word and an abbreviation abbr, return whether the string matches with the given abbreviation. # A string such as "word" contains only the following valid abbreviations: # ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] # Example # Example 1: # Given s = "internationalization", abbr = "i12iz4n": # Return true. # Example 2: # Given s = "apple", abbr = "a2e": # Return false. # Notice # Notice that only the above abbreviations are valid abbreviations of the string word. Any other string is not a valid abbreviation of word. class Solution: """ @param word: a non-empty string @param abbr: an abbreviation @return: true if string matches with the given abbr or false """ def validWordAbbreviation(self, word, abbr): # write your code here #My solution if not word and abbr: return False elif not abbr and word: return False elif not word and not abbr: return True ind1 = 0 ind2 = 0 len1 = len(word) len2 = len(abbr) while ind1< len1 and ind2 < len2: if abbr[ind2] == '0': return False if abbr[ind2].isnumeric(): count = 0 while abbr[ind2].isnumeric() and ind2<len2-1: ind2+=1 count+=1 if abbr[ind2].isnumeric(): ind1+=int(abbr[ind2-count:ind2+1]) if ind1>len1: return False else: ind1+=int(abbr[ind2-count:ind2]) elif word[ind1]!=abbr[ind2]: return False else: ind1+=1 ind2+=1 if ind1<len1-1 or ind2<len2-1: return False else: return True testcase = Solution() print(testcase.validWordAbbreviation("internationalization","i12iz4n"))
true
cf302c7e17ac3caddafd1f41a40aade40d0824b7
ramishtaha/Understanding_Conditional_Statements
/03_Leap_Year.py
853
4.34375
4
print("Welcome to Leap Year Checker!!") year = int(input("Please, Enter the Year: ")) # Check if year is totally Divisible By 4. if year % 4 == 0: # Check if year is totally Divisible By 100. if year % 100 == 0: # Check if year is totally Divisible by 400. if year % 400 == 0: # If year is divisible by 400 Then it's a Leap Year. print(f"The Year {year} is a leap year.") else: # If year is divisible by 100 and not by 400 then it's not a leap year. print(f"The Year {year} is not a leap year.") else: # If year is divisible by 4 then it's a leap year (also keep above 2 conditions in mind). print(f"The Year {year} is a leap year.") else: # If year is not divisible by 4 then it's not a Leap year. print(f"The Year {year} is not a leap year.")
false
f6ab518be8674ecc69c800b7aa316f88d7cc055f
opetrovskyi/webacademy_python
/HomeTask_3/HomeTask_3.5.py
1,007
4.4375
4
#4. Написать функцию принимающую имя фигуры (квадрат, треугольник, ромб), ее размерность и рисует эту фигуру на экран #Пример: #>> print_figure(‘треугольник’, 3) #* #** #*** def print_figure(f, n): def triangel(a): for i in range(a): print('*' * (i + 1)) def square(a): for sq in range(a): print('*' * a) def rhombus(a): for rh in range(1, a + 1): print(' ' * (a - rh), end='') print('*' * rh, end='') print('*' * (rh - 1), end='') print() for rh1 in range(1, a + 1): print(' ' * rh1 , end='') print('*' * (a - rh1), end='') print('*' * ((a - rh1) -1), end='') print() if f == 'triangel': triangel(n) if f == 'square': square(n) if f == 'rhombus': rhombus(n) print_figure('rhombus', 3)
false
05c927d4d3619ac4ae23be6f694e4cbc8c2579dc
QAMilestoneAcademy/python_basic
/Class6-7-8-list/excercise_even_odd.py
820
4.5
4
# Problem Description # The program takes a list and puts the even and odd elements in it into two separate lists. # # Problem Solution # 1. Take in the number of elements and store it in a variable. # 2. Take in the elements of the list one by one. # 3. Use a for loop to traverse through the elements of the list and an if statement to check if the element is even or odd. # 4. If the element is even, append it to a separate list and if it is odd, append it to a different one. # 5. Display the elements in both the lists. a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=int(input("Enter number:")) print(b) a.append(b) print(a) even=[] odd=[] for j in a: if j%2==0: even.append(j) else: odd.append(j) print("The even list",even) print("The odd list",odd)
true
07afebad1d7801ecc79c60b77e84ee033a7a3457
QAMilestoneAcademy/python_basic
/Class6-7-8-list/project_travis_security_guard.py
802
4.125
4
known_users = ["Shrek", "Donkey", "Fiona", "Patrick", "Bob", "Joe"] print("Hi my name Travis") name = input("What is your name? ") name=name.strip().capitalize() print(name) if name in known_users: print("Hello {}.How are you".format(name)) stay=input("Would you like to stay in the list-Yes/No: ") stay=stay.strip().capitalize() print(stay) if stay=="No": known_users.remove(name) print(known_users) # # elif name not in known_users: # print("Sorry {} you are not in the list ".format(name)) # enter = input("Would you like to enter the system? ") # enter=enter.strip().capitalize() # # if enter == "Yes": # known_users.append(name) # print("Welcome to the system! \t") # print(known_users) # else: # print("have a good day \t")
true
b3579525e9c1e7dffafea0eafa1e553f6387c7f1
QAMilestoneAcademy/python_basic
/Class4-5-Conditional/excercise_discountornot.py
343
4.125
4
# A shop will give discount of 10% if the cost of purchased quantity is more than 1000. # Ask user for quantity # Suppose, one unit will cost 100. # Judge and print total cost for user. quantity = int(input("Enter quantity ")) if quantity*100 > 1000: print("Cost is",((quantity*100)-(.1*quantity*100))) else: print("Cost is",quantity*100)
true
60fb16c7fa21fd2d0f23658c5d1c0e7d5be225b9
QAMilestoneAcademy/python_basic
/Class17-18-19-functions/excercise_common_list_element.py
477
4.125
4
# https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-11.php #Write a Python function that takes two lists # and returns True if they have at least one common member. def common_data(list1, list2): result = False for x in list1: for y in list2: if x == y: result = True return result print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, 9])) print(common_data([1, 2, 3, 4, 5], [6, 7, 8, 9]))
true
a4427448712031e85ff457fadb92f4c65c4935ce
DaniilMelnik/python_algorithm_course
/homeworks/les3/task6.py
994
4.28125
4
""" В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. Сами минимальный и максимальный элементы в сумму не включать. """ import random random_list = [random.randint(-10, 10) for _ in range(0, 10)] print(random_list) max_index = 0 min_index = 0 for index, el in enumerate(random_list): if el > random_list[max_index]: max_index = index if el < random_list[min_index]: min_index = index result = 0 if max_index > min_index: for el in range(min_index + 1, max_index): result += random_list[el] print(f"суммируемые числа {random_list[min_index + 1:max_index]}") else: for el in range(max_index + 1, min_index): result += random_list[el] print(f"суммируемые числа {random_list[max_index + 1:min_index]}") print(result)
false
1e03b89708ee6b12abdb9b788f27a4a9b4d5326f
jiyadkamal/CalculatorApp
/calculator.py
1,298
4.1875
4
import time def addition(x, y): return x + y def subtraction(x, y): return x - y def product(x, y): return x * y def division(x, y): return x / y while True: print("\nCALCULATOR") print("1. Addition ") print("2. Subtraction") print("3. Multiplication") print("4. Division") print("5. Exit") print("Enter Your Choice :") user_choice = input() if user_choice == "1": print("Enter two numbers:") x = int(input()) y = int(input()) print(f'The sum of the two numbers is {addition(x, y)}') elif user_choice == "2": print("Enter two numbers:") x = int(input()) y = int(input()) print(f'The difference of the two numbers is {subtraction(x, y)}') elif user_choice == "3": print("Enter two numbers:") x = int(input()) y = int(input()) print(f'The product of the two numbers is {product(x, y)}') elif user_choice == "4": print("Enter two numbers:") x = int(input()) y = int(input()) print(f'The quotient of two numbers is {division(x, y)}') elif user_choice == "5": print("Program is exiting") time.sleep(2) break else: print("Invalid Option. Try Again")
true
1237eaa852dfe31131de0c6f23f11c9fc9a7c654
sip227/lab-07-conditionals
/cake.py
238
4.25
4
userAnswer = input("Do you want some cake? ") if userAnswer == "yes" or userAnswer == "YES": print("Have some cake.") elif userAnswer == "no" or userAnswer == "NO": print("No cake for you.") else: print("I don't understand.")
true
a3a971e642003bfb89aaa8c57a411849a51b80bd
MelbourneHighSchoolRobotics/ev3sim_custom_presets
/Silly Sequences/bot/code.py
398
4.1875
4
print("Easy!") x = 1 # Print x * x * x while it is <= 100. while x * x <= 100: square = x * x print(square) x = x + 1 print("Medium!") x = 1 # Print every send square less than 50 while x * x <= 100: square = x * x print(square) x = x + 1 print("Hard!") x = 1 # Print powers of 2 less than 200. while x * x <= 100: square = x * x print(square) x = x + 1
true
cde9f9a7e0bd3ebb91b1fa1e31801533a7f0210e
kgtdbx/dbchat
/ex1.py
536
4.1875
4
# simple data type number = 1 print number str = "This is string" print str # tuple no_tuple = (1,2) print no_tuple str_tuple = ('This is col1', 'This is col2') print str_tuple print str_tuple[0] print str_tuple[1] # list first_list = [ 1, 2, 3, 4] print first_list for i in first_list: print i sec_list = [ x*x for x in first_list ] print sec_list tuple_list = [ (1, 'String1'), (1, 'String1'), (2, 'String2'), (3, 'String3') ] print tuple_list small_list = [ x for x in tuple_list if x[0] == 2 ] print small_list
false
388711daab120d4cdcec3302eb9a7238500877b4
dteklavya/ProjectEuler100
/multiples-of-3-and-5.py
644
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Answer: 233168 """ def sum_multiples_of(number, target): last = target // number return number * (last * (last + 1)) // 2 def sum_of_multiples_of_three_and_five(number): return sum_multiples_of(3, number-1) + sum_multiples_of(5, number-1) \ - sum_multiples_of(15, number-1) assert(sum_of_multiples_of_three_and_five(1000) == 233168)
true
34d889ab44161172b97f51a554e76400bcd31777
ganes7777/Python1
/number of characters.py
2,601
4.3125
4
# Python implementation to compute # number of characters, words, spaces # and lines in a file # Function to count number # of characters, words, spaces # and lines in a file def counter(fname): # variable to store total word count num_words = 0 # variable to store total line count num_lines = 0 # variable to store total character count num_charc = 0 # variable to store total space count num_spaces = 0 # opening file using with() method # so that file gets closed # after completion of work with open(fname, 'r') as f: # loop to iterate file # line by line for line in f: # incrementing value of # num_lines with each # iteration of loop to # store total line count num_lines += 1 # declaring a variable word # and assigning its value as Y # because every file is # supposed to start with # a word or a character word = 'Y' # loop to iterate every # line letter by letter for letter in line: # condition to check # that the encountered character # is not white space and a word if (letter != ' ' and word == 'Y'): # incrementing the word # count by 1 num_words += 1 # assigning value N to # variable word because until # space will not encounter # a word can not be completed word = 'N' # condition to check # that the encountered character # is a white space elif (letter == ' '): # incrementing the space # count by 1 num_spaces += 1 # assigning value Y to # variable word because after # white space a word # is supposed to occur word = 'Y' # loop to iterate every # letter character by # character for i in letter: # condition to check # that the encountered character # is not white space and not # a newline character if(i !=" " and i !="\n"): # incrementing character # count by 1 num_charc += 1 # printing total word count print("Number of words in text file: ", num_words) # printing total line count print("Number of lines in text file: ", num_lines) # printing total character count print('Number of characters in text file: ', num_charc) # printing total space count print('Number of spaces in text file: ', num_spaces) # Driver Code: if __name__ == '__main__': fname = 'File1.txt' try: counter(fname) except: print('File not found')
true
6185d2f34e2047f741aa3582b1e349742d2c9a7a
EmiliaPavlova/Learning_Python
/04.2.ComplexConditions_ExamProblems/03.Operations.py
717
4.125
4
number_1 = int(input()) number_2 = int(input()) operator = input() result = 0 output = f'{number_1} {operator} {number_2} = ' if operator == '+' or operator == '-' or operator == '*': if operator == '+': result = number_1 + number_2 elif operator == '-': result = number_1 - number_2 else: result = number_1 * number_2 output += f'{result} - ' output += 'even' if result % 2 == 0 else 'odd' elif operator == '/' or operator == '%': if number_2 == 0: output = f'Cannot divide {number_1} by zero' elif operator == '/': result = number_1 / number_2 output += f'{result:.2f}' else: output += f'{number_1 % number_2}' print(output)
false
1312169893f0024bf692ddc8f58bbe8e97b2e8be
rashmierande/python_exercise
/LeetCode/Evaluate_Reverse_Polish_Notation.py
1,528
4.46875
4
''' Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 Solution: The Reverse Polish Notation (RPN) is also known as the postfix notation, because each operator appears after its operands. For example, the infix notation “3 + 4” is expressed as “3 4 +” in RPN. Observe that every time we see an operator, we need to evaluate the last two operands. Stack fits perfectly as it is a Last-In-First-Out (LIFO) data structure. We evaluate the expression left-to-right and push operands onto the stack until we encounter an operator, which we pop the top two values from the stack. We then evaluate the operator, with the values as arguments and push the result back onto the stack. For example, the infix expression “8 – ((1 + 2) * 2)” in RPN is: 8 1 2 + 2 * – ''' def evalRPN(tokens): OPERATORS = set('+-*/') stack =[] for token in tokens: if token in OPERATORS: y = stack.pop() x = stack.pop() stack.append(eval(int(x),int(y),token)) else: stack.append(token) return stack.pop() def eval(x,y,operator): if operator =="+": return x + y elif operator =="-": return x -y elif operator == '*': return x*y elif operator == '/': return x//y print(evalRPN("34*"))
true
57208ab49d03e748b7b17afebc5fd9f3bf591895
rashmierande/python_exercise
/python_workbook/dict_addkey.py
682
4.46875
4
''' Add a new pair of key (e.g. c ) and value (e.g. 3 ) to the dictionary and print out the new dictionary. d = {"a": 1, "b": 2} {'a': 1, 'c': 3, 'b': 2} ''' d = {"a": 1, "b": 2} d["c"] = 3 print(d) ''' Adding pairs of keys and values is straightforward as you can see. Note though that you cannot fix the order of the dictionary items. Dictionaries are unordered collections of items. ''' ''' Calculate the sum of all dictionary values. d = {"a": 1, "b": 2, "c": 3} ''' d = {"a": 1, "b": 2, "c": 3} print(d.values()) print(sum(d.values())) # d.values() returns a list-like dict_values # object while the sum function calculates # the sum of the dict_values items.
true
a003c76d02101f8ed574e561ad2f69f742c85587
rashmierande/python_exercise
/python_workbook/pass.py
611
4.21875
4
''' The code is supposed to get some input from the user, but instead it produces an error. Please try to understand the error and then fix it. Note: Please use raw_input instead of input if you are on Python 2. For Python 3 input is fine. ''' #pass = input("Please enter your password: ") #pass is reserved keyword #There was a SyntaxError error because the syntax to name # the variable was wrong since pass is a reserved keyword in Python. # However you can solve # that by adding a number to the name or simply # choosing another name for the variable. pass1 = input("Please enter your password :")
true
736cb7832b5bac4d3a5f74a09869122790c75d40
rashmierande/python_exercise
/python_workbook/NameErr_1.py
285
4.1875
4
''' The following code is supposed to print out the square root of 9, but it throws an error instead because another line before that is missing. Please fix the script so that it prints out the square root of 9. ''' import math math.sqrt(9) #NameError: name 'math' is not defined
true
6d172d5690a2990db77d10b8ec1e8c366f07ee64
AtulPhirke95/365-Days-Coding
/January_2020/Circular_tour_petrol_distance.py
1,418
4.125
4
""" Problem Statement: Suppose there is a circle. There are N petrol pumps on that circle. You will be given two sets of data. 1. The amount of petrol that every petrol pump has. 2. Distance from that petrol pump to the next petrol pump. Your task is to complete the function tour() which returns an integer denoting the first point from where a truck will be able to complete the circle (The truck will stop at each petrol pump and it has infinite capacity). Input: 1 4 4 6 6 5 7 3 4 5 Output: 1 Explaination: if we start from (6,5) then we left with 1 petrol as 6-5 is 1 At (7,3) we get 1+(7-3) = 6 At (4,5) we get 6+(4-5) = 5 At (4,6) we get 5+(4-6) = 3 Now with 3 liters petrol left you can go to next pertol pump (6,5) which is nothing but our end point. So, At last we have to check if our total sum is greater than 0 or not? """ def tour(lis, n): c = 0 diff = 0 start = 0 for i in range(len(lis)): c += lis[i][0]-lis[i][1] if c < 0: start = i+1 diff += c c=0 return start if (c+diff > 0) else -1 lis = [[4,6],[6,5],[7,3],[4,5]] #here lis=[[petrol,distance],[petrol,distance],] n = 4 print(tour(lis,n))
true
616bdef2745150bad6fdbb1f1a351aedf5a2a9ee
nicefuu/leetCode-python3
/151.py
1,222
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/10 19:48 # @Author : Fhh # @File : 151.py # Good good study,day day up! """给定一个字符串,逐个翻转字符串中的每个单词。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: "  hello world!  " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 示例 3: 输入: "a good   example" 输出: "example good a" 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 说明: 无空格字符构成一个单词。 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 进阶: 请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。 """ class Solution: def reverseWords(self, s: str) -> str: """ :param s:str :return: str """ tmp=s.split()[::-1] return ' '.join(tmp) s=Solution() a='what is your name?' print(s.reverseWords(a))
false
4d3076c72e85b13703d5617aafa036282b2c3276
nicefuu/leetCode-python3
/59.py
1,726
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/26 12:45 # @Author : Fhh # @File : 59.py # Good good study,day day up! """给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: 输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 通过次数 """ from typing import List class Solution: def generateMatrix(self, n: int) -> List[List[int]]: res = [[0 for _ in range(n)] for _ in range(n)] x, y = 0, 0 i = 1 direction = "right" while 1: if i == n * n + 1: break if res[x][y] == 0: res[x][y] = i i += 1 if direction == "right": # print("1") if y == n - 1 or res[x][y + 1] != 0: x += 1 direction = "down" else: y += 1 elif direction == "down": # print("2") if x == n - 1 or res[x + 1][y] != 0: y -= 1 direction = "left" else: x += 1 elif direction == "left": # print("3") if y == 0 or res[x][y - 1] != 0: x -= 1 direction = "up" else: y -= 1 else: # print("4") if x == 0 or res[x - 1][y] != 0: y += 1 direction = "right" else: x -= 1 return res s = Solution() for i in s.generateMatrix(5): print(i)
false
d81b1ddb0ea5cea744ae1e430a54e862dee16008
venkatesheee128/Github_1
/PythonBasics/PythonTypes.py
2,920
4.28125
4
#numbers print(2+2) print((50-5*6)/4) print(8/5) # division always return a floating number print(17//3) #floor division discards the fractional part print(17%3) # the % operator returns the reminder of the revision print(2**7) # 2 to the power of 7 #strings print('Welcome to python world') print("doesn't") print('print first line \nsecond line') #if you dont want characters prefaced by \ to be interpreted #as special characters #you can use raw string by adding an r before the first quote: print(r'c:\some\name') print('c:\some\name') #string literals can span multiple lines #one way is using triple-quotes:"""...""" or '''...''' #End of lines are automatically included in the string, #but it's possible to prevent this by addings a \at the end of the line. print("""\ Usage: thingy [OPTIONS] -h Dislay this usage message -H hostname Host name to connect to """) #strings cane be concatenated with the + operator,and repeated with *: print(3 * 'un' + 'ium') print('py' 'thon') print('this is a test ' 'to write long strings ' 'concatenated together') #can't concatenate a variable and a string literial,but (+) will work prefix='py' #print(prefix 'thon') print(prefix + 'thon') #strings can be indexed, word='python' print(word[0]) print(word[4]) #indeces may also be negative numbers,to start counting from the right: print(word[-1]) print(word[-2]) print(word[-6]) #while indexing is used to obtain invidual characters, #slicing allows you to obtain substring: print(word[0:2]) ## characters from position 0 [included] to 2 [Excluded] #note how the start is always inclluded,and the end always excluded #this makes sure that s[:i] + s[i:] is always equal to s: print(word[:2] + word[2:]) print(word[:4] + word[4:]) #characters from the second-last (included) to the end print(word[-2:]) #python strings can not be changed-- they are immutable #therefore,assigning to an indexd position in the string #results in as error: #word[0]='j' #word[:2]='py' #if you need a different string,you should create a new one: print('j' + word[1:]) #len() returns length of string print(len('python')) #Lists #Lists might contain items of different types, #but usually the items all have the same type squares=[1,4,9,16,25] print(squares) print(squares[0]) print(squares[-3:]) #unlike strings,which are immmutable #lists aremutable type,i.e. it is possible to change their content: cubes=[1,8,27,65,125] cubes[3]=64 print(cubes) cubes.append(6**3) print(cubes) #replace some values cubes[2:1]=[20] print(cubes) #clear the list by replacing all the elements with an empty list cubes[:]=[] print(cubes) cubes=[1,8,27,65,125] cubes[2:2]=[20] print(cubes) #length of the lists print(len(['a','b'])) a=['a','b','c'] n=[1,2,3] x=[a,n] print(x) print(x[0]) print(x[1][0]) #fibonacci series a,b=0,1 while b<1000: print(b,end=',') a,b=b,a+b
true
1bdcd930b3ddd126508b2e54373b4c761868016c
shesha4572/11
/23_2.py
285
4.28125
4
str = input("Enter the string to be searched : ") sub_str = input("Enter the substring to be searched : ") count = str.count(sub_str) if count == 0: print("Given substring not found in string") else: print("Given substring was found in string") print("Frequency :" , count)
true
61bd21ba3ed91d38857647b99d7d979823666fcd
shesha4572/11
/10_2.py
405
4.46875
4
def Reverse_String (s): s = s.lower() reversed = s[::-1] print("Reversed string is : ", reversed ) if reversed == s: return True else: return False string_check = input("Enter the string to be checked : ") check = Reverse_String(string_check) if check == True: print("The entered string is a palindrome") else: print("The entered string is not a palindrome")
true
c8b4591fe39eb38dc7e1035df244ada229c72d9a
codewithsandy/Python-Basic-Exp
/23 Recursion/recursive.py
305
4.375
4
def factorial_recursive(n): """ :param n: Integer :return: n * n-1 * n-2 * n-3..........1 """ if n==1: return 1 else: return n * factorial_recursive(n-1) number = int(input("Enter the number : ")) print("factorial using recursion: ", factorial_recursive(number))
false
8c3de85abd33fd97f630b763e2db9801d4edd90b
trishahanlon/algorithms-review
/merge_sort.py
1,011
4.21875
4
import sys # get the input from the command line arr = list(map(int, sys.argv[1].split(","))) print('unsorted array before: ', arr) def merge_sort(array): if len(array) > 1: # divide the array into left and right middle = (len(array)//2) left = array[:middle] right = array[middle:] # call merge_sort on our left and right arrays recursively left = merge_sort(left) right = merge_sort(right) # start building our final, sorted array array = [] while len(left) > 0 and len(right) > 0: if left[0] < right[0]: array.append(left[0]) left.pop(0) else: array.append(right[0]) right.pop(0) for i in left: array.append(i) for i in right: array.append(i) return array # call merge sort on our array from the command line # merge_sort(arr) print('Sorted array from merge sort: ', merge_sort(arr))
true
578abfbc0aa68f0cdf3631f669dcc74d349a598a
trishahanlon/algorithms-review
/checkArmstrongofNDigits.py
452
4.46875
4
# Python program to check if any number is an Armstrong number or not # take input from the user num = int(input("Enter a number: ")) # calculate the length of the number: order = len(str(num)) print(order) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** int(order) temp //= 10 # display if armstrong or not if num == sum: print(num, "is an Armstrong number") else: print(num, "is not an Armstrong number")
true
35b6f527a61d002df17ef5afc4d4fafd82f3a520
A26mike/Intro_to_scritping
/re example/retest1.py
806
4.90625
5
import re #The string to search for the regular expression occurrence (This is provided to the student) search_string='''This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression''' #1. Write a regular expression that will find all occurrences of: # a. regular expression # b. regular-expression # c. regular:expression # d. regular&expression # in search_string #2. Assign the regular expression to a variable named pattern pattern = 'regular[ -:&]expression' #1. Using the findall() method from the re package determine if there are occurrences in search_string match1 = re.findall(pattern, search_string) if match1 != None: print(pattern +' matched') else: print(pattern +' did not match')
true
d7c9b1c7dc8ccf242785ffc28026ca866dac8185
AlexBieg/python-minesweeper-ai
/minesweeper.py
1,344
4.15625
4
"""This plays a game of minesweeper in the console.""" from board import Board def main(): """The main method that starts the game.""" print("Welcome to Minesweeper!") start = input("Are you ready to start the game? ") if start.lower().startswith("y"): print("starting game!") height = input("What should the height be? (1-99)") width = input("What should the width be? (1-99)") bombs = input("How many bombs should there be? (1-" + str(int(width) * int(height)) + ")") start_game(Board(int(height), int(width), int(bombs))) else: print("Not starting game.") def start_game(board): """Start the game.""" isPlaying = True board.print_board() while (isPlaying): print("Choose a box to click.") coords = input("Coordinates to click? (x y format. ex: 4 10) ").split() board.click_box(int(coords[0]), int(coords[1])) if board.check_mine(int(coords[0]), int(coords[1])): print("You Lose!") isPlaying = False board.click_all() else: if board.check_win(): print("You Win!!") isPlaying = False board.click_all() board.print_board() """Call main function""" if __name__ == "__main__": main()
true
850941a489cd61ccd1f7d11b1c4340851bfe4600
wolfryan97/WeeklyChallenges
/Week1/FizzBuzz.py
905
4.71875
5
# Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz". # If the number is a multiple of 3 the output should be "Fizz". # If the number given is a multiple of 5, the output should be "Buzz". # If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz". # If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below. # The output should always be a string even if it is not a multiple of 3 or 5. # Examples # <code>fizz_buzz(3) ➞ "Fizz" # fizz_buzz(5) ➞ "Buzz" # fizz_buzz(15) ➞ "FizzBuzz" # fizz_buzz(4) ➞ "4"</code> def fizz_buzz(x: int) -> str: output: str = "" if(x%15==0):output += "FizzBuzz" elif(x%3==0):output += "Fizz" elif(x%5==0):output += "Buzz" else:output += f"{x}" print(output) fizz_buzz(3) fizz_buzz(5) fizz_buzz(15) fizz_buzz(4)
true
5122ac705843513b90e10d38a00b81e9b9c76751
tdkumaran/python-75-hackathon
/Dictionaries/dic1del.py
307
4.15625
4
#dictionary dict={"myname":"abc","num":12,"age":18} #to add country in that dictionary dict["country"]="india" print(dict["country"],dict["myname"]) del dict["country"] print(dict["country"]) #gives an error because country key is deleted print(dict["num"]) #it gives values because country key only delted
false
475696c0d3509a1b166ee483fdcf3751c372dfa1
EduardoPorcayo/TC1001-Ejercicio-2
/snake.py
1,978
4.125
4
"""Snake, classic arcade game. Exercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ from turtle import * from random import randrange, randint from freegames import square, vector c = ['green','cyan','purple','orange','yellow','blue','lime','cadetblue','indigo','gold'] colors = randint(0,7)+1 colorf = randint(0,9) if colors == colorf: colorf = colorf +1 food = vector(0, 0) snake = [vector(10, 0)] aim = vector(0, -10) i = randrange(-5,5) j = randrange(-5,5) def change(x, y): "Change snake direction." aim.x = x aim.y = y def inside(head): "Return True if head inside boundaries." return -200 < head.x < 190 and -200 < head.y < 190 def move(): "Move snake forward one segment." head = snake[-1].copy() head.move(aim) global i global j food.x = food.x + i food.y = food.y + j if food.x + i <-200 or food.x + i >190: i = i*(-1) if food.y + j <-200 or food.y + j >190: j = j*(-1) if not inside(head) or head in snake: square(head.x, head.y, 9, 'red') update() return snake.append(head) if abs(head.x-food.x) <= 5 and abs(head.y-food.y) <= 5: print('Snake:', len(snake)) food.x = randrange(-15, 15) * 10 food.y = randrange(-15, 15) * 10 i = randrange(-5,5) j = randrange(-5,5) else: snake.pop(0) clear() for body in snake: square(body.x, body.y, 9, c[colors]) square(food.x, food.y, 9, c[colorf]) update() ontimer(move, 100) setup(420, 420, 370, 0) hideturtle() tracer(False) listen() onkey(lambda: change(10, 0), 'Right') onkey(lambda: change(-10, 0), 'Left') onkey(lambda: change(0, 10), 'Up') onkey(lambda: change(0, -10), 'Down') move() done()
true
82cf20e93d3a593dda2a1bb818aab94abb19c080
Christiancv/Python-Basics
/masterticket.py
1,077
4.125
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 def calculate_price(number_of_tickets): return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining >= 1: print("Tickets remaining: {}".format(tickets_remaining)) username = input("What is your name? ") ticket_amount = input("hey {}, how many tickets would you like? ".format(username)) try: ticket_amount = int(ticket_amount) if ticket_amount > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as e: print("oh no! we ran into an issue. {}".format(e)) else: total = calculate_price(ticket_amount) print("{}, your total is ${}".format(username, total)) answer = input("would you like to continue? (Y/N) ") if answer.lower() == "y": print("Sold!!!") tickets_remaining -= ticket_amount else: print("Thank you anyways {}!".format(username)) print("Sorry, the tickets are sold out!")
true
c25d6e394506bd3358992cef66cc8f7628fbb369
raspberrymeatpi/salary
/module4workingwithnumbers/module4workingwithnumbers.py
1,283
4.40625
4
area = 0 height = 10 width = 20 #calculate the area of a triangle area = width*height /2 #printing formatted float value with 2 decimal places print ("The area of the triangle would be %.2f" % area) #printing the formatted number with right justified to take up 6 spaces #with leading zeros print("My favourite number is %06d !" % 42) #do the same thing with the .format syntax to include numbers our output print("the area of the triangle would be {0:f} ".format(area)) print("my favourite number is {0:d} ".format (42)) #this is an example with multiple numbers #I have added a \ to indicate the command continues onto the following line print("Here are three numbers! " + \ "The first is {0:d} The second is {1:4d} and {2:d}".format(7,8,9)) #print("I have %d cats" %6) #I have 6 cats #print("I have %3d cats" %6) #I have 6 cats #print("I have %03d cats" %6) #I have 006 cats #print("I have %f cats" %6) #I have 6.000000 cats #print("I have %.2f cats" %6) #I have 6.00 cats #print("I have {0:d} cats".format (6)) #I have 6 cats #print("I have {0:3d} cats".format (6)) #I have 6 cats #print("I have {0:03d} cats".format (6)) #I have 006 cats #print("I have {0:f} cats".format (6)) #I have 6.000000 cats #print("I have {0:.2f} cats".format (6)) #I have 6.00 cats
true
48c060953fa9f09e82f10984d20550c454334c07
ethrlrnr/python-misc
/anagrams.py
2,348
4.125
4
def are_anagrams(str1, str2): str1dict = {} str2dict = {} for i in str1: if ord(i) >= 97 and ord(i) <= 122 or (ord(i) >= 65 and ord(i) <= 90): if i.lower() not in str1dict: str1dict[i.lower()] = 0 str1dict[i.lower()] += 1 for i in str2: if ord(i) >= 97 and ord(i) <= 122 or (ord(i) >= 65 and ord(i) <= 90): if i.lower() not in str2dict: str2dict[i.lower()] = 0 str2dict[i.lower()] += 1 if len(str1dict) == len(str2dict) and len(str1dict) > 0: for i in str1dict: if i in str2dict and str1dict[i] == str2dict[i]: continue else: return False else: return False return True #This problem can also be done in multiple ways. #Firstly, because we are told not to consider spaces and capitalization #we change our input strings to lower and remove all our spaces. def are_anagrams(first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() first_word = first_word.replace(' ', '') second_word = second_word.replace(' ', '') #For me, the first thought was to store the letters of the first word #into a list and then iterate through the second word and remove the letter stored #if it existed in the list. #SO, I create an empty list called 'letters' letters = [] #I then iterate through my first word and the append all the characters for char in first_word: letters.append(char) #I then iterate through my second word and see if the letter I am currently #iterating through is in my list. #If it is in my list, then I remove that character (this avoids duplicates) #and if my current letter is not in my list then I automatically return False #since that means my second word has a letter that my first word doesn't! for char in second_word: if char not in letters: return False letters.remove(char) #At the very end when we are done iterating through, I return the boolean value #of whether my length of list is equal to 0. I do not simply return True because #there may be cases where my first word will have letters that my second letter #might not have. ie. first = hello, second = helo (list would still contain 'l') return len(letters) == 0
true
11b5e722e6ef7b7dff7ee6bb4a9422a2254bd19d
gordonlee/study_effective_python
/CH08/list_comprehension_expression.py
1,818
4.25
4
""" 8장. list comprehension 에서 표현식을 두 개 이상 쓰지 말자 flat = [x for row in matrix for x in row] 의 경우 flat = [x { for row in matrix } for x in row] 로 1차원 배열로 끊어서 보고 각 row 를 다시 반복하는 부분이 뒤에 있는 for x in row 로 이해하면 된다. """ matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 이중 for 문도 아래와 같이 돌릴 수 있다. """ flat = [x for row in matrix for x in row] 의 경우 flat = [x { for row in matrix } for x in row] 로 1차원 배열로 끊어서 보고 각 row 를 다시 반복하는 부분이 뒤에 있는 for x in row 로 이해하면 된다. """ flat = [x for row in matrix for x in row] print(flat) # 풀어쓰면 아래와 같이 풀어서 쓸 수도 있다. flat2 = [] for x in matrix: for elem in x: flat2.append(elem) print(flat2) # 각 요소에 대한 제곱수를 처리해보자 squared = [[x ** 2 for x in row] for row in matrix] print(squared) """ 위 내용 까지는 쉽게 이해할 수 있지만, 3중 포문이나 2중 포문도 조건이 복잡해지면, 코드를 읽는 사람이 따라가기가 어렵다. 그럴 땐, 풀어서 써주는 것이 가독성 상에선 더 좋다. """ # list comprehension 에서 다중 if 문 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [x for x in a if x > 4 if x % 2 == 0] c = [x for x in a if x > 4 and x % 2 == 0] assert b == c # matrix 인스턴스에서 row 의 합이 10 이상이고, 3으로 나누어 떨어지는 # 셀을 구한다고 한다면? filtered = [[x for x in row if x % 3 == 0] for row in matrix if sum(row) >= 10] print(filtered) """ 내용이 복잡해 질 수록 직관적으로 이해하기가 어려워진다. 이럴 경우는 차라리 풀어서 써주는 것이 읽는 사람 입장에선 편하다. """
false
0c84b85e0d3faa1136a2d4e53ab8c3e6e3ba55c6
LizaChelishev/031021class
/task2perek10.py
500
4.21875
4
# insert 10 positive numbers i = 1 number1 = int(input('Insert an integer number')) number2 = int(input('Insert an integer number')) while i < 9: number3 = int(input('Insert an integer number')) sum_of_numbers = number2 + number1 if sum_of_numbers == number3: print('The number you chose equals to the sum of all numbers', number3) break sum_of_numbers = sum_of_numbers+number3 number2 = number1 number3 = number2 i = i+1 if i == 9: print('Not found')
true
b9c7289e309dfc5746c4150b4fa067d4b2b80373
KhanyaI/IntrotoCS_MIT_6.00
/guttag1.py
2,109
4.5
4
# Minimum monthly payment = Minimum monthly payment rate x Balance # (Minimum monthly payment gets split into interest paid and principal paid) # Interest Paid = Annual interest rate / 12 months x Balance # Principal paid = Minimum monthly payment – Interest paid # Remaining balance = Balance – Principal paid """" ## Question 1: Write a program to calculate the credit card balance ## after one year if a person only pays the minimum monthly payment required by the credit card company each month. balance = float(input('Please enter the outstanding balance on the credit card:')) interest_rate = float(input('Please enter your annual interest rate:')) min_payment_percent = float(input('Please enter your minimum monthly payment rate:' )) for i in range(1,13): month = i print('month is:',i) min_payment = min_payment_percent * balance print('Minimum payment made:', min_payment) interest_paid = (interest_rate/12) * balance print('Out of that interest paid:', interest_paid) principal_paid = min_payment - interest_paid print('Out of that principal paid:', principal_paid) remaining_balance = balance - principal_paid print('Remaining balance:', remaining_balance) balance = remaining_balance """ ## Question 2: ##Monthly interest rate = Annual interest rate / 12.0 ##Updated balance each month = Previous balance * (1 + Monthly interest rate) – Minimum monthly payment balance = float(input('Please enter the outstanding balance on the credit card:')) interest_rate = float(input('Please enter your annual interest rate:')) money_to_be_paid = (balance * interest_rate) + balance monthly_payment = int(round(money_to_be_paid/24)) print(monthly_payment) monthly_payment = 10 monthly_rate = interest_rate/24 while balance > 0: monthly_payment = monthly_payment+10 month = 0 while month < 24 and balance > 0: month = month+1 interest = monthly_rate * balance balance = balance - monthly_payment balance = balance+interest print("Monthly payment to pay off debt in 1 year", monthly_payment) print("Number of months needed", month) print("Balance",balance)
true
ca87371efecce680cd0d5d74ad93a8b13f13981c
jonathanrussell63/furry-system
/Data Structures and Algorithms/Classes.py
1,619
4.125
4
#creates a class called coordinate with the parent class of object class Coordinate(object): # need attributes/methods here #special method called __inti__ def __init__(self, x,y): self.x=x self.y=y def distance(self, other): x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2 return (x_diff_sq+y_diff_sq)**.5 def __str__(self): return '<'+str(self.x)+','+str(self.y)+'>' class Animal(object): # using getter and setter methods def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newage): self.age = newage def set_name(self, newname=""): self.name = newname def __str__(self): return "animal:"+str(self.name)+":"+str(self.age) def __eq__(self, obj1): if (self.get_name() == obj1.get_name()) and (self.get_age() == obj1.get_age()): return True else: return False #sub-class / inheritance of animal class class Cat(Animal): def speak(self): prnit('meow') def __str__(self): return "cat:"+str(self.name)+":"+str(self.age) class Rabbit(Animal): tag=1 def __init__(self, age, parent1=None, parent2=None): Animal.__init__(self,age) self.parent1= parent1 self.parent2= parent2 self.rid = Rabbit.tag Rabbit.tag+=1 def get_rid (self): return str(self.rid).zfill(3) def get_parent1(self): return self.parent1 def get_parent2(self): return self.parent2 def __add__(self, other): return Rabbit(0, self, other) a=Rabbit(5) b = Rabbit(5) c = a+b print(a.__eq__(b))
false
1e9f3d333c3a8b9de531f0fe7a6f27ca5d1133c0
Squeeshy123/PythonBootcamp
/Chapter1/1.2.py
719
4.4375
4
# 1.2: Declaring variables and accepting input # Variables work just how they do in math. # you assign value with the '=' sign, then funny_number = 69420 print("Funny number:", funny_number) # You can do math in python too! math_number = 100 * 256 print("What is 100 * 256?", math_number) # You can even accept input with variables user_input = input("What do you want to say? ") print("You:", user_input) # but watch out! # print("You: ", user_input - 5) # This will give you an error! # Because the input function returns a string so # it thinks you are trying to subtract a number from a word! # We will fix this in 1.3 evaluated_input = eval(input("Type some equation or something: ")) print(evaluated_input)
true
86c2704f706c75b62d950ab6771880582e031dfe
daryna2002/python
/ifelse.py
317
4.125
4
value = 10 if (value == 15) : print("Yes") else: print ('No') print("Nothing") value = 23 if(value == 15): print("yes! it's 15") elif(value == 20): print("yes! it's 20") elif(value == 25): print("yes! it's 25") elif(value == 30): print("yes! it's 30") else: print("NO! This is a strange value")
true
bee97c575df16445ac12b85b03655dc9c0bc1e4b
JordanLeich/Beginner-and-Practice-Projects
/Python/Simple Timer & Stopwatch/Simple Timer & Stopwatch.py
2,386
4.125
4
# Made by Jordan Leich on 5/6/2020 """ --DESCRIPTION-- This is a very basic and simple program that is designed for a user to either create a timer of their choice or the option to create a stopwatch. """ # Imports import time import os seconds = int() minutes = int() hours = int() def begin(): userchoice1 = int(input("Would you like to make a timer(1) or a countdown stopwatch(2) or end this program(0): ")) if userchoice1 == 1: timer() if userchoice1 == 2: stopwatch() if userchoice1 == 0: forceend() else: print("Invalid Input! ") time.sleep(3) begin() def timer(): seconds = int() minutes = int() hours = int() print("Welcome to the timer! ") time.sleep(2) run = input("Enter R to start the timer! ") while run.lower() == "r": if seconds > 59: seconds = 0 minutes = minutes + 1 if minutes > 59: minutes = 0 hours = hours + 1 seconds = (seconds + 1) print(hours, ":", minutes, ":", seconds) time.sleep(1) def stopwatch(): global whentostop print("Welcome to the stopwatch!") time.sleep(2) while True: userinput = input("Enter time to countdown in seconds: ") try: whentostop = abs(int(userinput)) except KeyboardInterrupt: break except: print("Invalid Input!") time.sleep(3) stopwatch() while whentostop > 0: m, s = divmod(whentostop, 60) h, m = divmod(m, 60) time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2) print(time_left) time.sleep(1) whentostop -= 1 print("Stopwatch finished!") time.sleep(2) restart() def restart(): restartchoice = str(input("Would you like to restart this program(yes or no): ")) if restartchoice == 'yes': print("restarting program...") time.sleep(3) begin() if restartchoice == 'no': forceend() else: print("Invalid Input!") time.sleep(3) restart() def forceend(): print("ending program...") time.sleep(1) quit() begin()
true
4c4953b17c487406db178bdf119b3838aedee4c5
claudiopmaia/DataScience
/EstruturaDeDecisao/Exercicio2.py
218
4.15625
4
#Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. A = int(input("Digite um numeros ")) if A > 0: print("O numero é positivo: ") else: print("O numero é negativo: ")
false
055e76e21344d32188bf0494baa4ef734807cd35
Spacider/MyLeetcode
/DairyQue/Squares_of_a_Sorted_Array.py
711
4.15625
4
# Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. # # # # Example 1: # # Input: nums = [-4,-1,0,3,10] # Output: [0,1,9,16,100] # Explanation: After squaring, the array becomes [16,1,0,9,100]. # After sorting, it becomes [0,1,9,16,100]. class Solution(object): def sortedSquares(self, nums): """ :type nums: List[int] :rtype: List[int] """ for index in range(len(nums)): nums[index] = (nums[index] * nums[index]) return sorted(nums) if __name__ == '__main__': nums = [-4, -1, 0, 3, 10] nums = Solution.sortedSquares(nums, nums) print(nums)
true
7a3fd79250c32dcee342e17ede88e265e8784f06
ajn123/Python_Tutorial
/Python Version 2/Advanced/lamdaExpressions.py
1,459
4.65625
5
""" lambda expressions have special rules: 1) The body of a lambda expression can contain only a single line. 2) The body can only contain an expression, no statements or other elements 3) The result of the expression is automatically returned. The form of a lambda expression is: lamda arg_list: expression A lambda is essentially an anonymous function, a function without a name """ #I am now assigning this lambda to add so now add is pointing to this lambda function and can call it. add = lambda num1, num2: num2 + num1 #calling lambda function through add. print add(2,3) #prints 5. """ Another way to use lambda functions is with the map() function, it takes a function and an iterable and applies that function to all the iterables. I defined a lambda expression to square everything and map() applied that function to everything in the list. """ result = map(lambda x: x**2,[2,3,4,56]) print list(result) """ prints: 4 9 15 3136 """ """ Filters the list based on the lambda rules. """ answer = filter(lambda a:a > 2 ,[1,2,3]) print(answer)# Prints a list with only 3 [3]. from functools import reduce """ Result can apply a function across a list returning one result such as a sum or multiplication of the list. """ result = reduce(lambda a,b:a*b, [5,6,7]) print (result) #prints 210 odd = lambda x : bool(x % 2) numbers = [n for n in range(100) if odd(n)] print numbers # prints all odd numbers from 1 to 99.
true
43ffd5ab008cf3e06ba865b462904d4e0945b603
ajn123/Python_Tutorial
/Python Version 3/dictionaryExample.py
967
4.4375
4
def main(): """ Declares a dictionary of key value pairs listing it as (key):(value) """ vowels = { 1:'a',2:'b',3:'c',4:'d'} print(vowels) """ Typing does not have to be consistent across the dictionary you can store any type as a key or value. this adds a pair with value bobo and key Name """ vowels["Name"] = "bobo" """ Updating the name key with a value of 123, """ vowels["Name"] = 123 print(vowels) del vowels['Name']; # remove entry with key 'Name' #Prints outs the key and values for k, v in vowels.items(): print(k, v) #Add value to dictionary vowels[10] = "z" #Prints just the values from the dictionary for v in vowels.values(): print (v) #prints a list of keys for k in vowels.keys(): print(k) #Deletes the key value pair with 1 as a key del vowels[1] if __name__ == '__main__': main()
true
207d4efeb2d0acb68b6b3aa0f640095b80e81411
ajn123/Python_Tutorial
/Python Version 2/Advanced/fileIO.py
650
4.28125
4
""" This file exhibits file IO. """ """ Reads a file by opening with "r+" meaning you have reading properties the read line method gives back a list of each line """ def readFile(fileName): file = open(fileName,"r+") txt = file.readlines() print txt for item in txt: print item file.close() """" to write, you open the file bit give it "w+" so you have the right to write to the file The write method writes to the file just five it a string """ def writeFile(fileName): file = open(fileName,"w+") file.write("hello, world \nanother line") file.close() if __name__ == '__main__': writeFile("text.txt") readFile("text.txt")
true
0564687ca6079efe496441cffd984b7d3a34c5d5
Walter5467/2016CSP
/Computer Science/1.3/1.3.3/133.py
937
4.1875
4
from __future__ import print_function # use Python 3.0 printing def age_limit_output(age): '''Step 6a if-else example''' AGE_LIMIT = 13 #Caps for constants if age < AGE_LIMIT: print(age, 'is below the age limit.') else: print(age, 'is old enough') print('Minimum age is ', AGE_LIMIT) def report_grade(perc): if perc >= 80: print('A grade of', perc, 'is great work! Keep it up!') else: print('A grade of', perc, 'is not good work. Maybe try studying more!') def vowel(letter): vowels = 'aeiouAIOU' if letter in vowels: return True else: return False def letter_in_word(guess, word): if guess in word: return True else: return False def hint(color, secret): if color in secret: print (color, 'is in the code.') else: print ('The color', color, 'is not in the code.')
true
bd5c5cacb47b07fccbf219f2fdb96d64c7c96361
YakovenkoMaksim/Python_Learn
/Starter/5.3.py
2,292
4.34375
4
# Задание 3 # Создайте программу-калькулятор, которая поддерживает четыре операции: сложение, # вычитание, умножение, деление. Все данные должны вводиться в цикле, пока пользователь не # укажет, что хочет завершить выполнение программы. Каждая операция должна быть # реализована в виде отдельной функции. Функция деления должна проверять данные на # корректность и выдавать сообщение об ошибке в случае попытки деления на ноль. #Функция деления def division(x, y): if y != 0: div = x / y print('Деление ', x, ' на ', y, ' = ', div) print() else: print('Деление на 0 не возможно!') print() #Функция умножения def multiplication(x, y): mult = x * y print('Умножение ', x, ' на ', y, ' = ', mult) print() #Функция вычитания def subtraction(x, y): sub = x - y print('Вычитание ', x, ' из ', y, ' = ', sub) print() #Функция сложения def addition(x, y): add = x + y print('Сумма ', x, ' и ', y, ' = ', add) print() while True: x = float(input('Введи первое число: ')) y = float(input('Введи второе число: ')) print() print('Выберите, пожалуйста, операцию: ') print('1. Деление') print('2. Умножение') print('3. Вычитание') print('4. Сложение') print('0. Выйти из калькулятора') print() operation = int(input('Введите номер операции над числами: ')) print() if operation == 1: division(x ,y) continue elif operation == 2: multiplication(x, y) continue elif operation == 3: subtraction(x, y) continue elif operation == 4: addition(x, y) continue elif operation == 0: break else: print('Вы выбрали не верную операцию!') continue
false
35a6c28e30016ec3437cffc1981541b30dc48b06
JoshuaOakland/CurrentWorkSamples
/PythonSamples/speak_to_me_parser.py
653
4.125
4
""" parsing module accepts a string of characters and filters out things that are not in english words """ legal_characters = ['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',' '] def filter(inString): returnString = [] for character in inString.lower(): if character in legal_characters: returnString.append(character) return "".join(returnString) def main(): crapLine = "1231231klajsxlkfjasfa askldzxcz .c.s a.sd as.d as. das.d" filtLine = filter(crapLine) print(filtLine) print("".join(filtLine)) if __name__ == "__main__": main()
false
0c6e827de312093256b343ca1ffaf79c2b49ad31
teesamuel/Udacityproblemvsalgorithm
/problem_1.py
1,150
4.25
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number ==0 or number ==1: return number if number < 1: return 0 start = 1 end = number while (start <= end): midPoint = (start + end ) // 2 # check for perfect sQUare if (midPoint * midPoint == number): return midPoint #since we are looking for the floor, the first lowest value will be our answer if midPoint * midPoint < number: start = midPoint + 1 answer=midPoint else: end= midPoint -1 return answer print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print ("Pass" if (0 == sqrt(-1)) else "Fail") print ("Pass" if (0 == sqrt(-99)) else "Fail") print ("Pass" if (999999== sqrt(999999999999)) else "Fail")
true
81f02ae074df857225b6f1819640819aeab81d2e
michaelwoolsey/simple-prime-finder
/prime_num.py
677
4.28125
4
# borrowed some code from official documentation # just a prime number finder program to learn the basics of python def prime_num(num, print_nonprimes): num += 1 result = '' for n in range(2,num): for x in range(2,n): if n%x == 0: if print_nonprimes: result += (str(n) + ' equals ' + str(x) + ' * ' + str(n//x) + '\n') break else: result += (str(n) + ' is prime!\n') return result nonprime = False user_in = raw_input('do you want to see nonprimes in your search? ') if user_in in ('y', 'Y', 'yes', 'Yes', 'YES', 'sure'): nonprime = True user_input = int(input('what number do you want to search up to? ')) print(prime_num(user_input, nonprime))
true
858b8654e108009efa1b4cc45c830078423a7c22
oddo3o/LPTHW3
/ex18.py
689
4.5
4
def print_two(*args): # * pulls all arguments to the function into a list # 'args' is being unpacked into 'arg1' and 'arg2' arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # This one is like your scripts with argv def print_two_again(arg1, arg2): # 'arg' values in parentheses adds them to the function print(f"arg1: {arg1}, arg2: {arg2}") # That *args is actually pointless, we can just do this def print_one(arg1): print(f"arg1: {arg1}") # This just takes one argument def print_none(): print("I got nothing") # This one takes no arguments print_two("Christian", "General") print_two_again("Hello", "World") print_one("First") print_none()
true
7ba04d249d58d8bedfd5aadc7fb2554663fb7cfa
oddo3o/LPTHW3
/ex15.py
867
4.25
4
# Module import on argument variable from sys import argv # Argv assigns values to variables from command line script, filename = argv # Command open "filename" is assigned to variable txt txt = open(filename) # f-string formating filename print(f"Here's your file {filename}:") # Print variable "txt", "filename" is open / read then printed print(txt.read()) # Opening a file using user input while code is running # print("Type the filename:") # User input assigned to variable # file_again = input("> ") # txt_again is assigned command open on variable file_again # txt_again = open(file_again) # Open file_again, using function .read to read file, then print # print(txt_again.read()) # Terms command and function are interchangable # For security and consistency limit use of input() # Close open files to free up memory txt.close() # txt_again.close()
true
dcb279bb9f12903ffffc83d1f79cd896a6b27f76
shounak-26/Python-simple-projects
/Guess game.py
424
4.125
4
import random n = random.randint(0,20) chance=3 while "guess" != n: guess = int(input("Enter the guess number:")) if guess < n: print("Too low") chance = chance - 1 elif guess > n: print("Too high") chance = chance - 1 else: print("Correct") break if chance==0: print("Chances over!!! Please try again!!!") break
true
ba07caf9685f75b659b7a22cc5123eb5ca6d8b0b
santanu5670/Python
/coding/2/operator.py
687
4.28125
4
a=3 b=4 #arithmetic operator print("The value of",a,"+",b,"is",a+b) #Addition print("The value of",b,"-",a,"is",b-a) #Subtraction print("The value of",a,"*",b,"is",a*b) #Multiplication print("The value of",a,"/",b,"is",a/b) #Division print("The value of",a,"%",b,"is",a%b) #Modulus print("The value of",a,"//",b,"is",a//b) #Floor division print("The value of",a,"**",b,"is",a**b) #Floor division #comparision operator #it's return boolean c=(4>7) print(c) d=(14>7) print(d) # boolean operator bool1=True bool2= False print("The value of bool1 and bool2 is", (bool1 and bool2)) print("The value of bool1 or bool2 is",(bool1 or bool2)) print("The opposite value of bool1 is",(not bool1))
false
5d9435bdfd86f074799e57a7f38eab16e6ef412d
santanu5670/Python
/coding/List Comprehension/List_comprehension.py
260
4.28125
4
list_1=[1,2,3,15,44,45,65,66,23,33,12,54] div_by_3=list() for items in list_1: if items%3==0: div_by_3.append(items) print("Without Using List Comprehension",div_by_3) print("With Using List Comprehension",[items for items in list_1 if items%3==0])
true
21034edd578e204f8a697a2238faaa0e8ff24cc3
santanu5670/Python
/coding/11/3.py
1,089
4.1875
4
class Employee: def __init__(self,salary,increment): self.salary=salary self.increment=increment @property def salaryAfterIncrement(self): self.salary_increment=self.salary*self.increment return self.salary_increment @salaryAfterIncrement.setter def salaryAfterIncrement(self,change_increment): self.increment=change_increment salary=int(input("Enter the Salary of an Employee = ")) increment=int(input("Enter the increment of an Employee = ")) e=Employee(salary,increment) print("Print salary with increment",e.salaryAfterIncrement) ch=input("Do you want to change the increment Y/N :").upper() if ch=='Y': change_increment=int(input("Enter the new increment value = ")) print("Previous Salary with increment :",e.salaryAfterIncrement) print("Previous increment : ",e.increment) e.salaryAfterIncrement=change_increment print("New Salary with increment",e.salaryAfterIncrement) print("New increment : ",change_increment) elif ch=='N': print("Bye") else: print("Wrong cholice! Choose Y or N")
true
1ea1c25b53b6fc5b8153e0fb34bb596b54d8ccf3
webDva/KawaiiML
/kawaiiml/algorithms/simplelinearregression.py
1,035
4.15625
4
import math class SimpleLinearRegression: """Class for performing simple linear regression.""" def __init__(self, observations = None): self.observations = observations # a tuple of x-y pairs def linear_regression(self): """Function to perform simple linear regression on the SimpleLinearRegression object's observations.""" x = self.observations[0], y = self.observations[1] # First, calculate the standard deviations of each set of variables. x_standardDeviation = math.sqrt(sum((i - sum(x) / len(x))**2 for i in x) / len(x)) y_standardDeviation = math.sqrt(sum((i - sum(y) / len(y))**2 for i in y) / len(y)) # Next, calculate the correlation between the x and y variables. # Using the calculated standard deviations and correleation, calculate the slope of the regression line. # Calculate the y-intercept of the regression line. # Return the result of this algorithm as a tuple of the slope and y-intercept of the regression line.
true
fc1083f4b43666e65293088b648ede5e217a8862
HammerMeetNail/Project_Euler
/Problem 4/largest_palindrome.py
610
4.34375
4
""" Find the largest palindrome made from the product of two 3-digit numbers. """ upper = 999*999 bottom = 100*100 L = [] L2 = [] def largest_palindrome(): for e in range(bottom,upper): #Locates all palindromes e = str(e) if e[0] == e[-1] and e[1] == e[-2] and e[2] == e[-3]: e = int(e) L.append(e) for n in L: #Compiles list of all palindromes divisible by 3 digit integers for i in range(100,1000): if n % i == 0 and n/i > 99 and n/i < 1000 and n not in L2: L2.append(n) return L2[-1] print largest_palindrome()
false
84038701b4af3677c25b592008b78c5c0fc54618
sAnjali12/More_exercises
/More_exercises4.py
349
4.125
4
user_input1 = int(raw_input("enter your number")) user_input2 = int(raw_input("enter your second number")) user_input3 = int(raw_input("enter your third number")) if user_input1<user_input2 and user_input3<user_input2: print user_input2 elif user_input3>user_input1 and user_input3>user_input2: print user_input3 else: print user_input1
true
6bf7cdba4bdcb5e261043d78737764c03d46660a
Srishti-Kumar/pythonPRACTICAL3rdsem
/15.multiplymatrics.py
480
4.28125
4
# Program to multiply two matrices using nested loops # 3x2 matrix X = [[2, 4], [4, 6], [6, 8]] # 2x3 matrix Y = [[8, 6, 4], [6, 4, 8]] # resultant matrix result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] my_list = [] # iterating rows of X matrix for i in range(len(X)): # iterating columns of Y matrix for j in range(len(Y[0])): # iterating rows of Y matrix for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)
false