blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
23c498871baaf75458fb1f6180d7aa9aaa5bf7f0
premkumar0/30DayOfPython
/Day-12/day_12_Premkumar.py
648
4.28125
4
def linearSearch(n, k, arr): """ This function takes k as the key value and linear search for it if the value is found it returns the index of the key value else it will return -1 Example:- n, k = 4, 5 arr = [2, 4, 5, 8] returns 2 """ for i in range(n): if arr[i] == k: return i else: return -1 if __name__ == "__main__": n = int(input("Enter number of elements you want \n")) arr = [float(num) for num in input("Enter space seperated {} numbers for array \n".format(n)).split()] k = float(input("Enter the search key \n")) print("index of the search key is {}".format(linearSearch(n, k, arr)))
true
699f261fc02664f070af9158f6a1d158d28f70cc
KuroCharmander/Turtle-Crossing
/player.py
602
4.15625
4
from turtle import Turtle STARTING_POSITION = (0, -280) MOVE_DISTANCE = 10 FINISH_LINE_Y = 280 class Player(Turtle): """The turtle in the Turtle Crossing game.""" def __init__(self): """Initialize the turtle player.""" super(Player, self).__init__("turtle") self.penup() self.setheading(90) self.reset_start() def move(self): """Move the turtle up.""" self.forward(MOVE_DISTANCE) def reset_start(self): """Reset the turtle to the starting position at the bottom of the screen.""" self.goto(STARTING_POSITION)
true
ddd53c5798d033ce7d85b51b3805aeca263a2ad8
d1l0var86/Dilovar
/classes/cars.py
2,200
4.5
4
class Car(): """This is class to represent a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.color = 'White' self.odometer_reading = 0 # getter and setter def get_description(self): msg = f"Your car: \nmanufacture: {self.make},\nmodel: {self.model}\nYear: {self.year}\nColor: {self.color}" return msg def set_color(self, new_color): print(f"Changing the color {self.color} to {new_color}") self.color = new_color def read_odometer(self): """Get the odometr miles of the car.""" msg = f"Car has {self.odometer_reading} miles on it." return msg def set_odometer(self, new_miles): if new_miles >= self.odometer_reading: print(f"Setting odometer reading from {self.odometer_reading} to {new_miles}") self.odometer_reading = new_miles else: print(f"You can not roll back odometer from {self.odometer_reading} to {new_miles}.") def increment_odometer(self, miles): """:param miles to odometer_reading""" # self.odometer_reading = self.odometer_reading + miles if miles > 0: print(f"Incrementing odometer with more {miles} miles") self.odometer_reading += miles else: print(f"Negative value cannot be passed to odometer : {miles}") class ElectricCar(Car): """Represents Electric car , inherits all features of Car.""" def __init__(self, make,model,year): """child class constructor , Overriding the parent constructor""" super().__init__(make,model,year) # calling the constructor of parent class self.battery_size =80 def get_description(self): msg = f"Your car: \n\tmanufacture: {self.make},\n\tmodel: {self.model}\n\tYear: {self.year}"\ f"\n\tColor: {self.color}\n\tBattery size: {self.battery_size}" return msg def test_method(self): print(self.get_description()) # current class get_description() method, with battery_size print(super().get_description()) # parent class get_description() method
true
66c2a539db2169fc48436f2faff1ff287765d0ff
JagadishJ4661/Mypython
/Numbers.py
759
4.25
4
'''Take 2 numbers from the user, Print which number is 2 digit number and which number is 3 digit number If it neither, then print the number as it is''' def entry(): num1 = input("Select any number that you wish.") num1 = int(num1) num2 = input("select any number that you wish again.") num2 = int(num2) print(num1, num2) if num1>=10 and num1<100: print(num1,"is a two digit number") if num2>=10 and num2<100: print(num2, "is a two digit number") if num1>=100 and num2<1000: print(num1,"is a three digit number") if num2>=100 and num2<1000: print(num2,"is a two digit number") if num1<10 and num1>=1000: print(num1) if num2<10 and num2>=1000: print(num2) entry()
true
0911c018b5024d7dc525ebc285e67ba1d2e2663b
p-ambre/Python_Coding_Challenges
/125_Leetcode_ValidPalindrome.py
821
4.25
4
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false """ class Solution: def isPalindrome(self, s: str) -> bool: letters = [c for c in s if c.isalpha() or c.isdigit()] new = [] for letter in letters: if letter.isupper(): new.append(letter.lower()) else: new.append(letter) val = "".join(new) i = 0 j = len(val)-1 while i < j: if val[i] != val[j]: return False i += 1 j -= 1 return True
true
2e74ccb9169f92530d7e4eaac320b0786e94bf5c
p-ambre/Python_Coding_Challenges
/M_6_Leetcode_ZigZagConversion.py
1,712
4.40625
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I ALGORITHM- 1) Create an array of n strings, arr[n] 2) Initialize direction as "down" and row as 0. The direction indicates whether we need to move up or down in rows. 3) Traverse the input string, do following for every character. a) Append current character to string of current row. b) If row number is n-1, then change direction to 'up' c) If row number is 0, then change direction to 'down' d) If direction is 'down', do row++. Else do row--. 4) One by one print all strings of arr[]. """ class Solution: def convert(self, word: str, numRows: int) -> str: if numRows == 1: return(word) len_word = len(word) arr = ["" for x in range(len_word)] row = 0 for i in range(len_word): arr[row] += word[i] if row == 0: down = True elif row == numRows - 1: down = False if down: row += 1 else: row -= 1 return(''.join([arr[i] for i in range(len_word)])) """ Time complexity: O(len of the string) """
true
8c09eac5594829eb922e78688f3d91a6378cdd68
graag/practicepython_kt
/exercise_9.py
888
4.25
4
import random takes = 0 print("Type 'exit' to end game.") outer_loop_flag = True while outer_loop_flag: #Generate number number = random.randint(1,9) print('Try to guess my number!') takes = 0 while True: user_input = input("Type your guess: ") try: user_input = int(user_input) except ValueError: if user_input == 'exit': outer_loop_flag = False break else: print(user_input + " is not a valid input.") else: takes += 1 if user_input > number: print("My number is lower.") elif user_input < number: print('My number is higher.') else: print('Congrats! You have guessed my number in ' + str(takes) +' takes! Let\'s do it again!') break
true
aa88db0d81a38fb2d62e01e69d460c166aa2b22e
pranshu798/Python-programs
/Data Types/Strings/accessing characters in string.py
277
4.1875
4
#Python Program to Access characters of string String = "PranshuPython" print("Initial String: ") print(String) #Printing first character print("\nFirst character of String: ") print(String[0]) #Printing last character print("\nLast character of String: ") print(String[-1])
true
8e4d2c3b574445d7e36dfb1e6b3726551f7ec4d8
pranshu798/Python-programs
/Data Types/Strings/string slicing.py
368
4.53125
5
#Python program to demonstrate string slicing #Creating a string String = "PranshuPython" print("Initial String: ") print(String) #Printing 3rd to 12th character print("\nSlicing characters from 3-12: ") print(String[3:12]) #Printing characters between 3rd and 2nd last character print("\nSlicing characters between 3rd and 2nd last character: ") print(String[3:-2])
true
7c4808931b9f3a7524eee2d16e53b85d69db4a67
pranshu798/Python-programs
/Data Types/Sets/Adding elements using add() method.py
417
4.65625
5
#Python program to demonstrate Addition of elements in a Set #Creating a Set set1 = set() print("Initial blank set: ") print(set1) #Adding elements and tuple to the Set set1.add(8) set1.add(9) set1.add((6,7)) print("\nSet after Addition of Three elements: ") print(set1) #Adding elements to the Set using Iterator for i in range(1,6): set1.add(i) print("\nSet after Addition of elements from 1-5: ") print(set1)
true
673bda4cbb55311159f64da91f523a3558a430b8
pranshu798/Python-programs
/Data Types/Sets/Removing elements using pop() method.py
275
4.3125
4
#Python program to demonstrate Deletion of elements in a Set #Creating a Set set1 = set([1,2,3,4,5,6,7,8,9,10,11,12]) print("Initial Set: ") print(set1) #Removing element from the Set using the pop() method set1.pop() print("\nSet after popping an element: ") print(set1)
true
c61d200009259fbad763fe8583a8345ed949d31e
pranshu798/Python-programs
/Functions/Python classes and objects/Functions can be passed as arguments to other functions.py
358
4.3125
4
# Python program to illustrate functions # can be passed as arguments to other functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func("Hi, I am created by a function passed as an argument.") print(greeting) greet(shout) greet(whisper)
true
5bcbac676259b19faa8e8f5144105840ceac6c68
muftring/iu-python
/module-04/Question3.py
640
4.125
4
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 4, Question 3 # # Write a program that calculates the numeric value of a single name # provided as input. This will be accomplished by summing up the values # of the letters of the name where ’a’ is 1, ’b’ is 2, ’c’ is 3 etc., # up to ’z’ being 26. # base = ord("a")-1 def main(): print("Compute the numeric value of a word!") sum = 0 name = input("Enter any name in lower case: ") for letter in name: sum += (ord(letter) - base) print("The numeric value of entered name is", sum) main()
true
0ec8e80b01fbf1ec69a3b8afe1086415c13ecb23
muftring/iu-python
/module-03/Question2_2.py
633
4.53125
5
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 3, Question 2.2 # # Given the length of two sides of a right triangle: the hypotenuse, and adjacent; # compute and display the angle between them. # import math def main(): print("Angle between hypotenuse and adjacent side computer!") b = eval(input("Enter the length of the adjacent side: ")) c = eval(input("Enter the length of the hypotenuse: ")) radians = math.acos(b/c) degrees = radians * 180 / math.pi print("The angle in radians is", radians) print("The angle in degrees is", degrees) main()
true
932a6b227d1127dbdfa2b4517c92b0b7873a8bed
muftring/iu-python
/module-04/Question1.py
519
4.5625
5
#!/usr/bin/env python # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 4, Question 1 # # Write a program that takes an input string from the user and prints # the string in a reverse order. # def main(): print("Print a string in reverse!") forward = input("Please enter a string: ") reverse = "" for i in range(1, len(forward)+1, 1): reverse += forward[-1*i] print("You typed a string:", forward) print("The string in reverse order is:", reverse) main()
true
da8f74d891428c8fd90e7a68b7037c3cf5c8ab4c
muftring/iu-python
/module-07/Question4.py
1,647
4.28125
4
#!/usr/bin/env python3 # # Michael Uftring, Indiana University # I590 - Python, Summer 2017 # # Assignment 7, Question 4 # # Display the sequence of prime numbers within upper and lower bounds. # import math # """ isPrime(n): checks whether `n` is prime using trial division approach (unoptimized)""" # def isPrime(n): if n <= 1: return False sqrt = int(math.sqrt(n)) for i in range(2,sqrt+1,1): if n % i == 0: return False return True # """ printPrime(lowerLimit, upperLimit): display the sequence of prime numbers between the lower and upper limits""" # def printPrime(lowerLimit, upperLimit): print("The sequence of prime numbers in the given interval:") for n in range(lowerLimit, upperLimit+1, 1): if isPrime(n): print(n) def main(): try: lowerLimit = int(input("Enter the lower limit of the range: ")) except ValueError: print("Error - Invalid input: lower limit should be a positive integer") return if lowerLimit <= 0: print("Error - Invalid input: lower limit should be a positive integer") return try: upperLimit = int(input("Enter the upper limit of the range: ")) except ValueError: print("Error - Invalid input: lower limit should be a positive integer") return if upperLimit <= 0: print("Error - Invalid input: upper limit should be a positive integer") return if upperLimit < lowerLimit: print("Error - Invalid input: the upper limit is less than the lower limit") return printPrime(int(lowerLimit), int(upperLimit)) if __name__ == '__main__': main()
true
13e22b088fcf09564ac82f25c775564f106310d6
Dadsh/PY4E
/py4e_08.1.py
555
4.5625
5
# 8.4 Open the file romeo.txt and read it line by line. For each line, split the # line into a list of words using the split() method. The program should build a # list of words. For each word on each line check to see if the word is already # in the list and if not append it to the list. When the program completes, sort # and print the resulting words in alphabetical order. # You can download the sample data at http://www.py4e.com/code3/romeo.txt fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: print(line.rstrip())
true
620bdd6eaeea894aaaf0abc6b716309a907ae181
Dadsh/PY4E
/py4e_13.9.py
2,565
4.34375
4
# Calling a JSON API # In this assignment you will write a Python program somewhat similar to # http://www.py4e.com/code3/geojson.py. The program will prompt for a location, # contact a web service and retrieve JSON for the web service and parse that # data, and retrieve the first place_id from the JSON. A place ID is a textual # identifier that uniquely identifies a place as within Google Maps. # API End Points # To complete this assignment, you should use this API endpoint that has a # static subset of the Google Data: # http://py4e-data.dr-chuck.net/geojson? # This API uses the same parameter (address) as the Google API. This API also # has no rate limit so you can test as often as you like. If you visit the URL # with no parameters, you get a list of all of the address values which can be # used with this API. # To call the API, you need to provide address that you are requesting as the # address= parameter that is properly URL encoded using the urllib.urlencode() # fuction as shown in http://www.py4e.com/code3/geojson.py # Test Data / Sample Execution # You can test to see if your program is working with a location of # "South Federal University" which will have a place_id of # "ChIJJ8oO7_B_bIcR2AlhC8nKlok". # $ python3 solution.py # Enter location: South Federal UniversityRetrieving http://... # Retrieved 2101 characters # Place id ChIJJ8oO7_B_bIcR2AlhC8nKlok # Turn In # Please run your program to find the place_id for this location: # Zagazig University # Make sure to enter the name and case exactly as above and enter the place_id # and your Python code below. Hint: The first seven characters of the place_id # are "ChIJmW7 ..." # Make sure to retreive the data from the URL specified above and not the # normal Google API. Your program should work with the Google API - but the # place_id may not match for this assignment. import urllib.request, urllib.parse, urllib.error import json serviceurl = 'http://py4e-data.dr-chuck.net/geojson?' while True: address = input('Enter location: ') if len(address) < 1: break url = serviceurl + urllib.parse.urlencode( {'address': address}) print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read().decode() print('Retrieved', len(data), 'characters') try: js = json.loads(data) except: js = None if not js or 'status' not in js or js['status'] != 'OK': print('==== Failure To Retrieve ====') print(data) continue location = js['results'][0]['place_id'] print(location)
true
0c078d889ed24a1de6b020b99ebd2456814c2de6
RobertoGuzmanJr/PythonToolsAndExercises
/Algorithms/KthLargest.py
1,391
4.125
4
""" This is an interview question. Suppose you have a list of integers and you want to return the kth largest. That is, if k is 0, you want to return the largest element in the list. If k is the length of the list minus 1, it means that you want to return the smallest element. In this exercise, we want to do this in less than quadratic time (O(n^2)). Our first approach will sort the data and then select the index of the kth largest. This is O(n*lg(n)) since it involves a sort and that is known to done in O(n*lg(n)) time with mergeSort or QuickSort. Our second approach will solve the same problem, but will do so using a specified amount of extra space, S. """ import heapq import math def kthLargest_SortApproach(arr,k): if k >= len(arr): return None arr.sort() return arr[len(arr)-1-k] def kthLargest_FixedSpace(arr,k): if k > len(arr): return None heap = arr[0:k+1] heapq.heapify(heap) for i in range(k+1,len(arr)): if arr[i] >= heap[0]: heap[0] = arr[i] heapq.heapify(heap) return heap[0] arr = [6,3,0,3,2,7,5,6,78,12,21] print(kthLargest_FixedSpace(arr,6)) print(kthLargest_FixedSpace(arr,0)) print(kthLargest_FixedSpace(arr,10)) print(kthLargest_SortApproach(arr,6)) print(kthLargest_SortApproach(arr,0)) print(kthLargest_SortApproach(arr,10))
true
2760af375842734ef59a5ae070565cf624444ac7
viethien/misc
/add_digits.py
513
4.21875
4
#!/usr/bin/python3 def main(): print ("Hello this program will add the digits of an integer until a singular digit is obtained") print ('For example 38 -> 3+8 = 11 -> 1+1 = 2. 2 will be returned') number = input('Enter an integer value: ') print (number + ' will reduce to ' + str(addDigits(number))) def addDigits(num): sum_of_num = 0 if len(num) == 1: return num else: for n in str(num): sum_of_num += int(n) return addDigits(str(sum_of_num)) if __name__ == '__main__': main()
true
9a2195053cd1dc6597b060e070c10db9a81f67ca
titanspeed/PDX-Code-Guild-Labs
/Python/frilab.py
2,639
4.21875
4
phonebook = { 'daniels': {'name': 'Chase Daniels', 'phone':'520.275.0004'}, 'jones': {'name': 'Chris Jones', 'phone': '503.294.7094'} } def pn(dic, name): print(phonebook[name]['name']) print(phonebook[name]['phone']) def delete(): correct_name = True while correct_name == True: delete_name = input('Enter the last name of the person you wish to delete from the phonebook: ') if delete_name in phonebook: del phonebook[delete_name] correct_name = False else: print(phonebook) print('Name not in phonebook. Try again.') def add_entry(): new_name = True while new_name == True: key_name = input('What is the last name, in lower case, of the person you wish you add?: ') full_name = input('What is the first and last name, upper case, of the person you wish to add?:') phone = input('What is the phone number of the person you wish to add?: ') if key_name not in phonebook: phonebook[key_name] = {'name': full_name, 'phone': phone} new_name = False else: print('Name is already in the phonebook: ') def edit_entry(): fix_name = True while fix_name == True: k_name = input('Last name: ') n_name = input('Replacement last name: ') f_name = input('Replacement First and Last name: ') fone = input('Replacement Phone Number: ') if k_name in phonebook: del phonebook[k_name] phonebook[n_name] = {'name': f_name, 'phone': fone} fix_name = False def lookup(): look_name = input('Enter the last name of the person you are looking for: ') if look_name in phonebook: pn('name', look_name) else: print('That name does not exist in this phonebook.') print(''' Welcome to the phonebook. You can do one of the following: -> To view the phonebook, enter "V". -> To edit an entry, enter "E". -> Look up a name in the phonebook, enter "L". -> Delete a name in the phonebook, enter "D". -> Or add a new name to the phonebook, enter "N". -> To quit the program, enter "Q".''') # print(phonebook) # lookup # delete_name() # add_entry() program_running = True while program_running == True: decision = input('What would you like to do?: ') if decision == 'V': print(phonebook) elif decision == 'L': lookup() elif decision == 'D': delete() elif decision == 'E': edit_entry( ) elif decision == 'N': add_entry() elif decision == 'Q': quit() else: print('That\'s not a valid entry. Try again, minion.')
true
805efe0ecd2da5e8e225c295f2a34d0902ebcd27
thepavlop/code-me-up
/shapes.py
1,362
4.28125
4
""" This program calculates the area and perimeter of a given shape. Shapes: 'rectangle', 'triangle'. """ shape = input("Enter a shape (rectangle/triangle): ") # User input is 'rectangle': if shape == 'rectangle': # Ask user for a height and width of the rectangle i1 = input ('Enter the width of the rectangle: ') i1 = int(i1) i2 = input ('Enter the height of the rectangle: ') i2 = int (i2) # Check that the height and the width are positive while i1 < 0: i1 = int(input('Enter the width of the rectangle: ')) while i2 < 0: i2 = int(input('Enter the height of the rectangle: ')) # Calculate area and perimeter: x = i1 * i2 y = i1 + i1 + i2 + i2 print ('The area of the rectangle is:', x) print ('The perimeter of the rectangle is:', y) elif shape == 'triangle': i3 = input ("enter an int ") i3= int(i3) i4 = input ("enter an int ") i4= int (i4) i5=input ("enter an int ") i5= int (i5) while i3 < 0: i3 = int(input('enter an int ')) while i4 < 0: i4 = int(input('enter an int ')) while i5 < 0: i5 = int(input('enter an int ')) l= (i3 * i4) / 2 e= i3+ i4+ i5 print('the area is:', l) print('the perimeter is:', e)
true
a344c5d1b7a3457d5c63bf45306f8d0106031a60
hpisme/Python-Projects
/100-Days-of-Python/Day-3/notes.py
380
4.4375
4
"""Conditionals / Flow Control""" #If statement if 2 > 1: print('2 is greater than 1') #Adding an else statement if 3 < 2: print('This won\'t print') else: print('This will print!') #Adding an elif statement x = 0 if x == 1: print('This will print if x is 1.') elif x == 2: print('This will print if x is 2.') else: print('This will print if x is not 1 or 2.')
true
bd07ed2c24d4cea71914d5ff91109bd3d0c8bd7e
mohitkh7/DS-Algo
/Assignment1/1divisible.py
319
4.3125
4
# 1.WAP to check the divisibilty def isDivisible(a,b): #To check whether a is divisible by b or not if a%b==0: return True; #Divisible else: return False; #Non Divisible num=int(input("Enter Any Number : ")) div=int(input("Enter Number with which divisibilty is to check : ")) print(isDivisible(num,div));
true
29fad1f70a64fb15378c74e16b1bade6f3b12a7e
Wil10w/Beginner-Library-2
/Exam/Check Code.py
1,262
4.21875
4
#Write a function called product_code_check. product_code_check #should take as input a single string. It should return a boolean: #True if the product code is a valid code according to the rules #below, False if it is not. # #A string is a valid product code if it meets ALL the following #conditions: # # - It must be at least 8 characters long. # - It must contain at least one character from each of the # following categories: capital letters, lower-case letters, # and numbers. # - It may not contain any punctuation marks, spaces, or other # characters. #Add your code here! def product_code_check(code): count = 0 for num in code: count += 1 if count >= 8: if code.isdigit(): if code.islower(); if code.isupper(): #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: True, True, False, False, False print(product_code_check("g00dlONGproductCODE")) print(product_code_check("fRV53FwSXX663cCd")) print(product_code_check("2shOrt")) print(product_code_check("alll0wercase")) print(product_code_check("inv4l1d CH4R4CTERS~"))
true
41a221f4719dc573f0e7949b0b9b8e8d0ee7e250
Wil10w/Beginner-Library-2
/Loops/if-if-else movie ratings.py
542
4.3125
4
rating = "PG" age = 8 if rating == 'G': print('You may see that movie!') if rating == "PG": if age >= 8: print("You may see that movie!") else: print("You may not see that movie!") if rating == "PG-13": if age >= 13: print("You may see that movie!") else: print('You may not see that movie!') if rating == 'R': if age >= 17: print('You may see that movie!') else: print('You may not see that movie!') if rating == 'NC-17': if age < 18: print('You may not see that movie!') else: print('You may see that movie!')
true
2da45f99244731fc4207270d95c5ed11a7a604b3
Wil10w/Beginner-Library-2
/Practice Exam/Release Date.py
2,414
4.375
4
#Write a function called valid_release_date. The function #should have two parameters: a date and a string. The #string will represent a type of media release: "Game", #"Movie", "Album", "Show", and "Play". # #valid_release_date should check to see if the date is #a valid date to release that type of media according to #the following rules: # # - Albums should be released on Mondays. # - Games should be released on Tuesdays. # - Shows should be released on Wednesdays or Sundays. # - Movies should be released on Fridays. # - Plays should be released on Saturdays. # #valid_release_date should return True if the date is #valid, False if it's not. # #The date will be an instance of Python's date class. If #you have an instance of date called a_date, you can #access an integer representing the day of the week with #a_date.weekday(). a_date.weekday() will return 0 if the #day is Monday, 1 if it's Tuesday, 2 if it's Wednesday, #up to 6 if it's Sunday. # #If the type of release is not one of these strings, #the release date is automatically invalid, so return #False. from datetime import date #Write your function here! def valid_release_date(the_date, the_string): dayOfTheWeek = the_date.weekday() if dayOfTheWeek == 0: if the_string == 'Album': return True else: return False if dayOfTheWeek == 1: if the_string == 'Game': return True else: return False if dayOfTheWeek == 2: if the_string == 'Show': return True else: return False if dayOfTheWeek == 4: if the_string == 'Movie': return True else: return False if dayOfTheWeek == 5: if the_string == 'Play': return True else: return False if dayOfTheWeek == 6: if the_string == 'Show': return True else: return False else: return False #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: True, False, False, each on their own line. print(valid_release_date(date(2018, 7, 12), "Show")) print(valid_release_date(date(2018, 7, 11), "Movie")) print(valid_release_date(date(2018, 7, 11), "Pancake"))
true
cf730580af6dc9754abfcb9a1e58d63ded705689
HarryBMorgan/Special_Relativity_Programmes
/gamma.py
776
4.1875
4
#Calculation of gamma factor in soecial relativity. from math import sqrt #Define a global variable. c = 299792458.0 #Define speed of light in m/s. #Define a function to calculate gamma. def gamma(v): if v < 0.1 * c: #If v is not in order of c, assume it's a decimal and * c. v *= c return 1 / sqrt(1 - (v**2.0 / c**2.0)) def gamma_inverse(gamma): #Returns beta = v/c. return sqrt(1 - (1 / gamma**2)) #__Main__ if __name__ == "__main__": #Import useful libraries. from fractions import Fraction #ask for input of velocity. v = float(input("Input the velocity as a decimal of c:")) #Call gamma fuction. gamma = gamma(v) #Print value to user. print("The gamma value =", Fraction(gamma), "=", '%.5f' %gamma)
true
b6182a34f51f0393626723f33cd60cfedfef5e5a
nagaprashanth0006/code
/python/remove_duplicate_chars_from_string.py
1,131
4.125
4
from collections import Counter str1 = "Application Development using Python" # Constraints: # Capital letters will be present only at the beginning of words. # Donot remove from start and end of any word. # Duplicate char should match across whole string. # Remove not only the duplicate char but also all of its occurances. # Remove only small case letters. # OP: "Acan Dvmt usg Pyhn" words = str1.split() # Collect the words from the given string. final = "" # Final output string will be collected here. count = Counter(str1) # Count the occurances for each char in given string str1. for word in words: uniq = [ char for char in word[1:-2] if count[char] == 1] # Skip the start and end chars of each word and collect other non repeating chars. final += word[0] + "".join(uniq) + word[-1] + " " # Join the uniq chars along with first and last chars. print final # The output. #### Same thing can also be written using list comprehensions in a single line like this: print " ".join([ word[0] + "".join([char for char in word[1:-2] if count[char] == 1]) + word[-1] for word in words])
true
88d3b4710b222d0787a96f7f4d8216f38e02f8fd
pablocorbalann/codewars-python
/5kyu/convert-pascal-to-snake.py
442
4.21875
4
# Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. # Lowercase characters can be numbers. If method gets number, it should return string. def to_underscore(string): s = '' for i, letter in enumerate(str(string)): if letter != letter.lower(): s += '{0}{1}'.format('_' if i!=0 else '', letter.lower()) else: s += letter return s
true
69be0a9c8b24ae5882c636d363481f7a9be43775
jonahp1/simple-bill-splitter
/Mainguy.py
1,480
4.3125
4
attendees = int(input("How many people are splitting the bill? : ")) bill_total = float(input("How much is the bill total (before tax)? (DO NOT INCLUDE $) : ")) tax_total = float(input("How much is the Tax total? (DO NOT INCLUDE $) : ")) tax_percentage = (tax_total / bill_total) # useful for math effective_tax_percentage = (tax_total / bill_total) * 100 # useful for human beings to look at print("Effective Tax percentage is " + str(effective_tax_percentage)) for person in range(attendees): person += 1 # this is done so the count does not start at 0. (ie. so nobody is referred to as "Name 0" but rather Name 1 - Name [numb(attendees)] name = input("\nName of customer " + str(person) + ": ") cost = float(input("What was " + name + "'s cost as shown on the right hand side of check? (DO NOT INCLUDE $) : ")) plus_tax = cost + (cost * tax_percentage) total_cost = plus_tax # this line is "theoretically unnecessary" but changing the variable name to "total cost" makes me feel better tipped = total_cost * .2 # some tip on tax, others do not. I usually do because worst case, you're giving more money to a person who literally just served you food. Algorithms should be grateful too tipped_total = tipped + total_cost print("\n" + name + "'s total cost after tax is $" + str(total_cost)+ "\n20% tip suggested at $" + str(tipped) + " tip. \n\nTotal for " + name + " INCLUDING tip: " + str(tipped_total) + "\n") running_total = total_cost
true
fafeba6ba874c5d7475aa7bf616d2843036d0915
lappazos/Intro_Ex_11_Backtracking
/ex11_sudoku.py
2,894
4.1875
4
################################################################## # FILE : ex11_sudoku.py # WRITERS : Lior Paz,lioraryepaz,206240996 # EXERCISE : intro2cs ex11 2017-2018 # DESCRIPTION : solves sudoku board game with general backtracking ################################################################## from math import floor from ex11_backtrack import general_backtracking def print_board(board, board_size=9): """ prints a sudoku board to the screen --- board should be implemented as a dictionary that points from a location to a number {(row,col):num} """ for row in range(board_size): if row % 3 == 0: print('-------------') toPrint = '' for col in range(board_size): if col % 3 == 0: toPrint += '|' toPrint += str(board[(row, col)]) toPrint += '|' print(toPrint) print('-------------') def load_game(sudoku_file): """ parsing input file into sudoku dict :param sudoku_file: input file location :return: dict {board coordinate: current value} """ with open(sudoku_file, 'r') as sudoku: sudoku_dict = {} sudoku = sudoku.readlines() for line in range(len(sudoku)): for index in range(0, 18, 2): sudoku_dict[(line, index / 2)] = int(sudoku[line][index]) return sudoku_dict def check_board(board, x, *args): """ legal_assignment_func :param board: dict {board coordinate: current value} :param x: item to check :param args: unused - needed for fitting other general backtracking functions :return: True if assignment is legal, False otherwise """ # row & column check for i in range(0, 9): if (board[(x[0], i)] == board[x]) and (i != x[1]): return False if (board[(i, x[1])] == board[x]) and (i != x[0]): return False # square check factor = (floor(x[0] / 3), floor(x[1] / 3)) for i in range(3): for j in range(3): index = (factor[0] * 3 + i, factor[1] * 3 + j) if (board[index] == board[x]) and (index != x): return False else: return True def run_game(sudoku_file, print_mode=False): """ :param sudoku_file: input file location :param print_mode: should we print in case of solution :return: True if there is a solution, False otherwise """ board = load_game(sudoku_file) list_of_items = [] for key in board.keys(): if board[key] == 0: list_of_items.append(key) set_of_assignments = range(1, 10) legal_assignment_func = check_board if general_backtracking(list_of_items, board, 0, set_of_assignments, legal_assignment_func): if print_mode: print_board(board) return True else: return False
true
640dbf5ad0fd5c12bc351f06cdf91bbe1555969b
Fainman/intro-python
/random_rolls.py
860
4.125
4
""" Program to simulate 6000 rolls of a die (1-6) """ import random import statistics def roll_die(num): """ Random roll of a die :param num: number of rolls :return: a list of frequencies Index 0 maps to 1 . . . Index 5 maps to 6 """ frequency = [0] * 6 # Initial values to 0 for i in range(6000): roll = random.randint(1, 6) frequency[roll - 1] += 1 return frequency def main(): """ Test function :return: """ num = int(input("How many times do you need to roll? ")) result = roll_die(num) print(result) for roll, total in enumerate(result): print(roll+1, total) mean = sum(result)/len(result) print("Average = {}".format(mean)) print("Mean = {}".format(statistics.mean(result))) if __name__ == "__main__": main() exit(0)
true
7051a6b21b2b930fb09b50df114bc9d66607c7c7
shaunakgalvankar/itStartedInGithub
/ceaserCipher.py
1,287
4.375
4
#this program is a ceaser cipher print("This is the ceaser cipher.\nDo You want to encode a message or decode a message") print("To encode your message press e to decode a messge press d") mode=raw_input() if mode=="e": #this is the ceaser cipher encoder original=raw_input("Enter the message you want to encode:") encrypted="" print("enter a number between 0 & 26 including 0 & 26 which will be the encryption key") key=input() i=0 while i<len(original): #to handle the wraping around if ord(original[i])>len(original): Ascii=ord(original[i])+key-len(original) elif ord(original[i])<0: Ascii=ord(original[i])+key+len(original) else: Ascii=ord(original[i])+key encrypted = encrypted + chr(Ascii) i=i+1 print(encrypted) elif mode=='d': #this is the ceaser cipher decoder encrypted=raw_input("Enter the message that you want to decode:") decrypted="" print("Enter the key according to which you want to decode your text") key=input() i=0 while i<len(encrypted): #to handle the wraping around if ord(encrypted[i])>len(encrypted): Ascii=ord(encrypted[i])-key-len(encrypted) elif ord(encrypted[i])<0: Ascii=ord(encrypted[i])-key+len(encrypted) else: Ascii=ord(encrypted[i])-key encrypted = encrypted + chr(Ascii) i=i+1 print(decrypted)
true
f5936be33f6ea652325db7c9b8c688b11a8e9e53
imclab/DailyProgrammer
/Python_Solutions/115_easy.py
1,220
4.40625
4
# (Easy) Guess-that-number game! # Author : Jared Smith #A "guess-that-number" game is exactly what it sounds like: a number is guessed at #random by the computer, and you must guess that number to win! The only thing the #computer tells you is if your guess is below or above the number. #Your goal is to write a program that, upon initialization, guesses a number #between 1 and 100 (inclusive), and asks you for your guess. If you type a number, #the program must either tell you if you won (you guessed the computer's number), #or if your guess was below the computer's number, or if your guess was above the #computer's number. If the user ever types "exit", the program must terminate. import random def play_game(): answer = random.randrange(1,100) print "Welcome to guess-that-numbers game! I have already picked a number in [1, 100]. Please make a guess. Type \"exit\" to quit. \n" guess = raw_input() while guess != 'exit': if int(guess) < answer: print "Guess higher..." guess = raw_input() continue elif int(guess) > answer: print "Guess lower..." guess = raw_input() continue elif int(guess) == answer: print "Correct! That is my number, you win!" break play_game()
true
3c443065b603371a6cb3733b5c2bcf52f1ab0c5a
NickAlicaya/Graphs
/projects/graph/interview.py
1,441
4.5
4
# Print out all of the strings in the following array in alphabetical order, each on a separate line. # ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # The expected output is: # 'Cha Cha' # 'Foxtrot' # 'Jive' # 'Paso Doble' # 'Rumba' # 'Samba' # 'Tango' # 'Viennese Waltz' # 'Waltz' # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process. array = ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # sort array # do a for loop for all items # print each item in array array.sort() for i in array: print(i) # Print out all of the strings in the following array in alphabetical order sorted by the middle letter of each string, each on a separate line. If the word has an even number of letters, choose the later letter, i.e. the one closer to the end of the string. # ['Waltz', 'Tango', 'Viennese Waltz', 'Foxtrot', 'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive'] # The expected output is: # 'Cha Cha' # 'Paso Doble' # 'Viennese Waltz' # 'Waltz' # 'Samba' # 'Rumba' # 'Tango' # 'Foxtrot' # 'Jive' # You may use whatever programming language you'd like. # Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
true
8b7bbd9cc3d0dbb4ccddab9ff8865866f5d03aa0
kochsj/python-data-structures-and-algorithms
/challenges/insertion_sort/insertion_sort.py
416
4.34375
4
def insertion_sort(list_of_ints): """Sorts a list of integers 'in-place' from least to greatest""" for i in range(1, len(list_of_ints)): # starting outer loop at index 1 j = (i - 1) int_to_insert = list_of_ints[i] while j >= 0 and int_to_insert < list_of_ints[j]: list_of_ints[j + 1] = list_of_ints[j] j -= 1 list_of_ints[j + 1] = int_to_insert
true
4e1d46b1dd5b16f5e316dfbaedc8fbf5ab674464
kochsj/python-data-structures-and-algorithms
/challenges/quick_sort/quick_sort.py
1,301
4.34375
4
def quick_sort(arr, left_index, right_index): if left_index < right_index: # Partition the array by setting the position of the pivot value position = partition(arr, left_index, right_index) # Sort the left_index quick_sort(arr, left_index, position - 1) # Sort the right_index quick_sort(arr, position + 1, right_index) def partition(arr, left_index, right_index): """ By selecting a pivot value, the partition reorganizes the array with the pivot in the middle index values to the left are lesser values to the right are greater """ # set a pivot value as a point of reference pivot = arr[right_index] # create a variable to track the largest index of numbers lower than the defined pivot low_index = left_index - 1 for i in range(left_index, right_index): if arr[i] <= pivot: low_index += 1 swap(arr, i, low_index) # place the value of the pivot location in the middle. # all numbers smaller than the pivot are on the left_index, larger on the right_index. swap(arr, right_index, low_index + 1) # return the pivot index point return low_index + 1 def swap(arr, i, low_index): temp = arr[i] arr[i] = arr[low_index] arr[low_index] = temp
true
1eda04501f801072b4c16c2f2450cbcc50765a61
sdmiller93/Summ2
/Zed/27-30/ex29studydrills.py
468
4.5625
5
# 1. The if prints the included statement if returned True. # 2. The code needs to be indented to make it known that the print statement is included with that if statement, it's a part of it. # 3. If it's not indented, it isn't included with the if statement and will print regardless of the truth of the if statement. # 4. people = 20 cats = 30 dogs = 15 if people != cats: print("People aren\'t cats") # 5. it will change the truth of the arguments.
true
de260d1be0cecc69226b792d1ff4d9bf96f5dd8b
sdmiller93/Summ2
/Zed/04-07/ex6.py
1,015
4.5625
5
# strings are pieces of text you want to export out of the program # assign variables types_of_people = 10 x = f"There are {types_of_people} types of people." # assign more variables binary = "binary" do_not = "don't" # write string with embedded variables y = f"Those who know {binary} and those who {do_not}" # printing strings/variables print(x) print(y) # produce f string print(f"I said: {x}") print(f"I also said: '{y}'") # set marker to false hilarious = False # {} at end of string allows for embedding of second variable in print further down joke_evaluation = "Isn't that joke so funny?! {}" # print statements print(joke_evaluation.format(hilarious)) # set variables w = "This is the left side of..." e = "a string with a right side." # print showing how to piece together two variables in one single string # variable + variable = longer single variable because you are adding two pieces of text together on a single line the computer views it as just x and y (or w and e here) print(w + e)
true
b7edfa22328e165b825e5834edf64fe96df04701
mateuszkanabrocki/LPTHW
/ex19.py
1,071
4.125
4
# defining a function with 2 arguments def cheese_and_crackers(chesse_count, boxes_of_crackers): #print(">>> START chesse_count=:", chesse_count, "boxes_of_crackers:", boxes_of_crackers) print(f"You have {chesse_count} cheeses.") print(f"You have {boxes_of_crackers} boxes of crackers.") print("Man, that's enough for a party!") print("Get a blanket.\n") #print("<<< END") print("We can just give the function numbers directly:") # function with number arguments cheese_and_crackers(20, 10) print("OR, we can use variables from our script:") # defining variables amount_of_cheese = 24 amount_of_crackers = 31 # function with given 2 arguments - variables cheese_and_crackers(amount_of_cheese, amount_of_crackers) print("We can even do math inside too") # function with given two arguments - mathematic operations cheese_and_crackers(10+20, 3+13) print("We can combine the two, variables and math:") # function with given 2 arguments - math operations on variables and numbers cheese_and_crackers(amount_of_cheese + 2, amount_of_crackers + 9)
true
a57b8ccb2942c7c26903d406f6d8343ba0db2ebe
mateuszkanabrocki/LPTHW
/ex16.py
1,071
4.25
4
# import the argv feature from the system module from sys import argv # assign the input values to the variables (strings) script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that hit Ctrl-C (^C).") print("If you do want that hit RETURN.") input("?") print("Opening the file...") # open the file "filename" for writing (assign the file - it's coordinates in file object - "target" variable) target = open(filename, "w") print("Truncating the file. Goodbye!") # removing the contents of the file # target.truncate() # don't have to do it, already truncated the file by opening it in "w" mode print("Now I'm going to ask you for three lines.") # assign 3 input lines to 3 variables line1 = input("line1:\n") line2 = input("line2:\n") line3 = input("line3:\n") print("I'm going to write these to the file.") # write the inputs to the file target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") # close the file target.close()
true
5003672f108deea087e056411ee5a08de4cd2f54
Nakshatra-Paliwal/Shining-Star
/Area of the Triangle.py
229
4.15625
4
Base = float(input("Please enter the value of Base of the Triangle : ")) Height = float(input("Please enter the value of Height of the Triangle : ")) Area = (1/2 * Base * Height) print("Area of the Triangle is " + str(Area))
true
38df5b7ab5326cbedddc379d8d931d7ddb1c43b5
Nakshatra-Paliwal/Shining-Star
/Calculate Area of Two Triangles and Compare the Smaller One.py
849
4.25
4
""" Write a code to calculate Area of two triangles. And compare these areas, and print which triangle has the greater area Note : Take input from the user as Base and Height values for two triangles """ Base1 = float(input("Please enter the value of Base of the 1st Triangle : ")) Height1 = float(input("Please enter the value of Height of the 1st Triangle : ")) Base2 = float(input("Please enter the value of Base of the 2nd Triangle : ")) Height2 = float(input("Please enter the value of Height of the 2nd Triangle : ")) Area1 = (1/2 * Base1 * Height1) Area2 = (1/2 * Base2 * Height2) print("Area of the 1st Triangle is " + str(Area1)) print("Area of the 2nd Triangle is " + str(Area2)) if Area1<Area2: print("Area of the 1st Triangle is smaller. ") else: print("Area of the 2nd Triangle is smaller. ")
true
0a45277982cb8bdf9f34b437b34ed5c017ece3d4
Nakshatra-Paliwal/Shining-Star
/Take two Numbers as Input and Print Their Addition.py
252
4.1875
4
#Write a code to take two numbers as input and print their Addition num1 = int(input("Write a Number 1 : ")) num2 = int(input("Write a Number 2 : ")) Multiply = num1 + num2 print() print("The Addition of Both the Number is " + str(Multiply))
true
186b27c411a681ee1a704dc53d5ecc23ed2746bf
Nakshatra-Paliwal/Shining-Star
/Voice Chatbot about sports input by text.py
2,142
4.28125
4
""" Create a Voice Chatbot about sports. Ask the user to type the name of any sport. The Chatbot then speaks about interesting information about that specific sport. """ import pyttsx3 engine=pyttsx3.init() print("Welcome !! This is a Voice Chatbot about sports.") print("Please choose the Operation:") print("1. Cricket") print("2. Football") print("3. Hockey") print("4. Basketball") choice = int(input("Please Enter your choice in Numbers : ")) if choice==1: engine.setProperty("RATE",100) engine.say("Cricket is a bat-and-ball game played between two teams of eleven players on a field at the centre of which is a 22-yard (20-metre) pitch with a wicket at each end, each comprising two bails balanced on three stumps.") engine.runAndWait() if choice==2: engine.setProperty("RATE",100) engine.say("Football, also called association football or soccer, is a game involving two teams of 11 players who try to maneuver the ball into the other team's goal without using their hands or arms. The team that scores more goals wins. Football is the world's most popular ball game in numbers of participants and spectators.") engine.runAndWait() if choice==3: engine.setProperty("RATE",100) engine.say("hockey, also called Field hockey, outdoor game played by two opposing teams of 11 players each who use sticks curved at the striking end to hit a small, hard ball into their opponent's goal. It is called field hockey to distinguish it from the similar game played on ice.") engine.runAndWait() if choice==4: engine.setProperty("RATE",100) engine.say("Basketball is a team sport in which two teams, most commonly of five players each, opposing one another on a rectangular court, compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter) through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard at each end of the court) while preventing the opposing team from shooting through their own hoop.") engine.runAndWait()
true
16dd605a3f9efc51f76e2accb45470bcfdb9f767
Nakshatra-Paliwal/Shining-Star
/Write a program for unit converter..py
1,166
4.40625
4
""" Write a program for unit converter. A menu of operations is displayed to the user as: a. Meter-Cm b. Kg-Grams c. Liter-Ml Ask the user to enter the choice about which conversion to be done. Ask user to enter the quantity to be converted and show the result after conversion. Ask user whether he wish to continue conversion or quit. Repeat the operations till the user wish to continue """ print("Display Menu of Unit Converters :-") print("a. Meter-Cm") print("b. Kg-Grams") print("c. Litre-Ml ") response = 'y' while response == 'y': choice = (input("Enter the Conversion you want to Perform: ")) Quan = int(input("Enter the Number: ")) cm = (Quan * 100) kg = (Quan * 1000) ml = (Quan * 1000) print() if choice==("a"): print("Conversion of" + str(Quan) + "m to cm is :" + str(cm)) if choice=="b": print("Conversion of" + str(Quan) + "m to cm is :" + str(kg)) if choice=="c": print("Conversion of" + str(Quan) + "m to cm is :" + str(ml)) response = input ("Do you wish to continue ? y/n : ") print() print ("Thank you for interacting with me!!")
true
3fe609269efbfddd1c814b1ab0091b868ddb73d2
Nakshatra-Paliwal/Shining-Star
/Create a 'guess the password' game (3 attempts).py
410
4.4375
4
""" Create a 'guess the password' game , the user is given 3 attempts to guess the password. Set the Password as “TechClub!!” """ attempt=1 while(attempt<=3): password=input("Enter the Password : ") if password=="TechClub!!": print("You are Authenticated!!") break else: attempt=attempt+1 if attempt > 3: print("Your Attempts are Over!!")
true
bfe2ac7fb508f2fcca6192a35c893a453f2053f4
brgyfx/Dice-Simulator
/DiceRollSimNew.py
425
4.15625
4
#DiceRollingSimulator import random import time dice = random.randint(0,9) count = 0 count_to = 10 response = input("Would you like to roll a dice? ") if response == "yes": times = int(input("How many times would you like to roll a dice? ")) count_to = times while response == "yes" and count < count_to: print("You rolled a {}!".format(random.randint(0,9))) count = count + 1 time.sleep(1)
true
1738b878939eabefdeb29a0c0be498d6c2b9981a
mridulpant2010/leetcode_solution
/OOAD/ss_function_injection.py
797
4.1875
4
''' 1- creating function 2- understanding static function more on static-method: 1- static-method are more bound towards a class rather than its object. 2- they can access the properties of a class 3- it is a utility function that doesn't need access any properties of a class but makes sense that it belong to a class,we use static functions. ''' class Person: def __init__(self,name): self.name=name def __str__(self): return 'Person Object {}'.format(self.name) @staticmethod def stat_method(): a=10 print('bro, I am a static method and please don"t try to access me from an instance ') print(a) if __name__=='__main__': p =Person('mridul') print(p) p.stat_method() Person.stat_method()
true
a41a38938250fe4514ee0db952f31f953422694f
mridulpant2010/leetcode_solution
/tree/right_view_tree.py
1,102
4.125
4
''' given a tree you need to print its right view ''' from collections import deque from typing import List class TreeNode: def __init__(self, val, left=None, right=None): self.val=val self.left=left self.right=right def tree_right_view(root): res=[] q=deque() q.append(root) while q: depthsize=len(q) for i in range(depthsize): currentNode=q.popleft() if i==depthsize-1: res.append(currentNode.val) if currentNode.left: q.append(currentNode.left) if currentNode.right: q.append(currentNode.right) return res if __name__ == '__main__': root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(9) root.right.left = TreeNode(10) root.right.right = TreeNode(5) root.left.left.left = TreeNode(3) result = tree_right_view(root) print("Tree right view: ") for node in result: print(str(node) + " ", end='')
true
a9a2ae4248ac36eb0af0b21b924967595f412b0b
deloschang/project-euler
/005/problem5.py
782
4.125
4
#!/usr/bin/env python # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def factorize(x): # < 11 don't need to be checked because 12-20 implicitly checks them i = 380 # because 19*2, 19*3 ... 19*19 not divis by 20 # so increment by 380 as well solved = False while not solved: solved = i % 11 == 0 and i % 12 == 0 and i % 13 == 0 and \ i % 14 == 0 and i % 15 == 0 and i % 16 == 0 and \ i % 17 == 0 and i % 18 == 0 and i % 19 == 0 and \ i % 20 == 0 if not solved: i += 380 return i print factorize(20)
true
f0236977e3d6ad99197048b5dc077bbb9263d30d
ssw1991/Python-Practice
/Module 1 - Shilo Wilson/Level 1.4 - Shilo Wilson/1.4.2.py
891
4.15625
4
# coding=utf-8 """ Name: Shilo S Wilson Exercise: 1.4.2 Find the length of each list in part b of the previous exercise. Then, verify that the lengths of all three lists indeed add up to the length of the full list in part a. """ import numpy as np def Mortgages(N): """ A function that returns an unsorted list of mortgage amounts :param N: :return: """ return list(np.random.random_integers(100,1000,size = N)) def main(): print('============= Exercise 1.4.2 =============\n\n\n') mortgages = Mortgages(1000) miniMortgages = filter(lambda x: x<200,mortgages) standardMortgages = filter(lambda x: 200<=x<=467,mortgages) jumboMortgages = filter(lambda x: x>467,mortgages) full_list = len(mortgages) print full_list == (len(miniMortgages + standardMortgages + jumboMortgages)) if __name__ == '__main__': main()
true
7a156ad4ed677a8315993eb17d0d5f2ccef94f4b
ssw1991/Python-Practice
/Module 3 - Shilo Wilson/Level 3.2/3.2.1 and 3.2.2/main.py
590
4.34375
4
""" Author: Shilo Wilson Create a list of 1000 numbers. Convert the list to an iterable and iterate through it. The instructions are a bit confusing, as a list is already an iterable. Is the intention to create an iterator to iterate through the list? """ def main(): print('========== Exercise 3.2.1 and 3.2.2 ==========') mylist = range(1000) myiterator = iter(mylist) myreverse = reversed(mylist) for i in range(len(mylist)): print myiterator.next() for i in range(len(mylist)): print myreverse.next() if __name__ == '__main__': main()
true
3d617c48812fd4612ea2a082478efb76ab1b129f
ssw1991/Python-Practice
/Module 3 - Shilo Wilson/Level 3.1/3.1.3/main.py
1,542
4.65625
5
""" Author: Shilo Wilson Create a regular function (called reconcileLists) that takes two separate lists as its parameters. In this example, List 1 represents risk valuations per trade (i.e. Delta) from Risk System A and List 2 has the same from Risk System B. The purpose of this function is to reconcile the two lists and report the differences between the two systems. To this end, it should return a list of True or False values, corresponding to each value in the lists (True means they match at index, False means they don't match at index). Test the reconcileLists function with different lists of values ( lists should be of at least length ten). Note that the assumption is that both lists are the same length (report an error otherwise). """ def reconcileList(l1, l2): """ Returns a list of booleans indicating whether l1[n] = l2[n] If l1 and l2 are different lengths, raises an exception :param l1: List :param l2: List :return: List """ if len(l1) != len(l2): raise Exception('The length of the input arguments do not match!') return map(lambda (x, y): x == y, zip(l1, l2)) def main(): print('========== Exercise 3.1.3 ==========') l1 = [1, 3, 5, 6, 3, 4, 5, 7, 5, 2, 3, 5] l2 = [1, 4, 5, 6, 9, 4, 5, 7, 5, 2, 3, 5] l3 = [1, 4, 5] try: print reconcileList(l1, l2) except Exception as e: print e.args try: print reconcileList(l1, l3) except Exception as e: print e.args if __name__ == '__main__': main()
true
8abf8fd8b5e06481ed24e75fa6bcbc24cd641f0f
chi42/problems
/hackerrank/is_binary_search_tree.py
1,167
4.125
4
#!/usr/bin/python # # https://www.hackerrank.com/challenges/ctci-is-binary-search-tree?h_r=next-challenge&h_v=zen class node: def __init__(self, data): self.data = data self.left = None self.right = None def is_valid(data, max_data, min_data): if max_data and data >= max_data: return False if min_data and data <= min_data: return False return True def check_binary_search_tree_(root): stack = [(root, None, None)] while len(stack) > 0: cur, max_data, min_data = stack.pop() if not is_valid(cur.data, max_data, min_data): return False if cur.left: stack.append((cur.left, cur.data, min_data)) if cur.right: stack.append((cur.right, max_data, cur.data)) return True # if you traverse a tree inorder and the tree is sorted, you print # the sorted elements def check_binary_search_tree_2(root): is_first = True prev_value = None stack = [] cur = root while len(stack) > 0 or cur: if cur: stack.append(cur) cur = cur.left else: cur = stack.pop() if not is_first: if cur.data <= prev_value: return False else: is_first = False prev_value = cur.data cur = cur.right return True
true
72ee90d35585f110e01e929cbfdd27115f14aa49
ztwilliams197/ENGR-133
/Python/Python 2/Post Activity/Py2_PA_Task1_will2051.py
2,595
4.28125
4
#!/usr/bin/env python3 ''' =============================================================================== ENGR 133 Program Description Takes inputs for theta1 and n1 and outputs calculated values for theta2 d3 and critTheta Assignment Information Assignment: Py2_PA Task 1 Author: Zach Williams, will2051@purdue.edu Team ID: 001-01 (e.g. 001-14 for section 1 team 14) Contributor: Name, login@purdue [repeat for each] My contributor(s) helped me: [ ] understand the assignment expectations without telling me how they will approach it. [ ] understand different ways to think about a solution without helping me plan my solution. [ ] think through the meaning of a specific error or bug present in my code without looking at my code. Note that if you helped somebody else with their code, you have to list that person as a contributor here as well. =============================================================================== ''' import math as ma theta1 = float(input("Input incoming angle [degrees]: ")) n1 = float(input("Input refractive index medium 1 [unitless]: ")) n2 = 1.3 d1 = 5.3 d2 = 7.6 # Calculates leaving angle using indices of refraction and incoming angle def calcTheta2(n1, n2, theta1): return ma.degrees(ma.asin(n1 * ma.sin(ma.radians(theta1)) / n2)) # Calculates ending distance of light ray using d1, d2, and angles def calcD3(d1, theta1, d2, theta2): return d1 * ma.tan(ma.radians(theta1)) + d2 * ma.tan(ma.radians(theta2)) # Calculates critical angle using indices of refraction def calcCritTheta(n1, n2): if(n1 > n2): return ma.degrees(ma.asin(n2 / n1)) else: return ma.degrees(ma.asin(n1 / n2)) # Calls functions to calculate theta2, d3, and critTheta theta2 = calcTheta2(n1,n2,theta1) d3 = calcD3(d1,theta1,d2,theta2) critTheta = calcCritTheta(n1,n2) # Outputs theta2, d3, and critTheta print(f"There is a refraction with a leaving angle of {theta2:.1f} degrees.") print(f"The ending distance for the light ray is {d3:.1f}cm.") print(f"For these two media, the critical angle is {critTheta:.1f} degrees.") ''' =============================================================================== ACADEMIC INTEGRITY STATEMENT I have not used source code obtained from any other unauthorized source, either modified or unmodified. Neither have I provided access to my code to another. The project I am submitting is my own original work. =============================================================================== '''
true
7b56a008f94895e31074dd7fc25a5ca111e70c02
adrientalbot/lab-refactoring
/your_code/Guess_the_number.py
1,986
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import random import sys # In[100]: def condition_to_play_the_game(string="Choose any integer between 1 and 100. Your number is "): your_number = input(string) if your_number.isdigit(): your_number = int(your_number) if your_number > 100: print('Your number exceeds 100. Please play again. ') sys.exit(1) print(" Your number is an integer and we can continue! ") return your_number else: print("You have not entered an integer. Please play again. ") sys.exit(1) def guess_the_number(): Number_of_guesses_left = 8 your_number = condition_to_play_the_game() random_number = random.randint(1,100) if your_number == random_number: print("YOU WIN WITH FIRST TRY, OMG!!") while your_number != random_number: if your_number > random_number: Number_of_guesses_left -= 1 print(f' Your number of guesses left is {Number_of_guesses_left}') your_number = condition_to_play_the_game("Choose lower number. Your number is ") if Number_of_guesses_left == 0: break elif your_number < random_number: Number_of_guesses_left -= 1 print(f' Your number of guesses left is {Number_of_guesses_left}') your_number = condition_to_play_the_game("Choose higher number. Your number is ") if Number_of_guesses_left == 0: break elif your_number == random_number: print("You win!") if Number_of_guesses_left == 0: print("YOU LOOSE!") print(f' The random number was {random_number}') guess_the_number() if Number_of_guesses_left > 0: print("YOU WIN!") print(f' The random number was {random_number}') guess_the_number() # In[ ]: # add choice of range # In[ ]: # add level of difficulty
true
aa3410e31edc7ce603dbf85bff00a80195b619d1
pcmason/Automate-the-Boring-Stuff-in-Python
/Chapter 4 - Lists/charPicGrid.py
1,077
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 30 01:58:47 2021 @author: paulmason """ #print out a grid of characters with a function called charPrinter #create the that prints out every element in a 2D list def charPrinter(givenChar): #loop through the column for y in range(len(givenChar[0])): #loop through each element in each column for x in range(len(givenChar)): #print out the character at the given location print(givenChar[x][y], end = '') #print a newline so that all of the characters look like a 2D array print() #example grid to use grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] #call the charPrinter function sith the example grid charPrinter(grid)
true
473b2d32e7aca4f9b4f5850ce767331190f1ab47
pcmason/Automate-the-Boring-Stuff-in-Python
/Chapter 7 - Pattern Matching with Regular Expressions/dateDetection.py
2,067
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 2 17:27:33 2021 @author: paulmason program that detects valid dates in the format of DD/MM/YYYY """ #first import the regex module import re #create the date regex dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)') #search for a regex object mo = dateRegex.search('31/06/2304') #create an example for a correct leap year leapYear = dateRegex.search('29/02/2400') #create an incorrect example unrealDay = dateRegex.search('29/02/2015') #print the found regex date #print(mo.group()) #create a list for each date dates = [mo, leapYear, unrealDay] #create function to check if the date is valid def validDate(d, m, y): #if there are more than 31 days or less than 1 days this is not valid if d < 1 or d > 31: return False #if there are more than 12 months or less than 1 month than this is not valid if m < 1 or m > 12: return False #year is between 1000 to 2999 if y < 1000 or y > 2999: return False #April June September and November have only 30 days if (m == 4 or 6 or 9 or 11) and (d > 30): return False #February has 28 days except during leap years if m == 2 and y % 4 == 0 and (y % 400 == 0 or y % 100 != 0): #a leap year if d > 29: return False elif m == 2 and (y % 4 != 0 or y % 100 == 0): #not a leap year if d > 28: return False #if made it this far return true return True #call validDate on day, month and year #assign the groups to variable they represent by looping through dates for date in dates: day = int(date.group(1)) month = int(date.group(2)) year = int(date.group(3)) #debug printout, useful to see each group #print(day) #print(month) #print(year) #call validDate in the print statement below to determine if the date is valid (results: F, T, F) print('The date\'s ' + date.group() + ' validity is: ' + str(validDate(day, month, year)))
true
065bb60114d3f78139202df70c4e4ca23ddde974
saikatsengupta89/PracPy
/BreakContinuePass.py
667
4.125
4
#to showcase break statement x= int(input("How many candies you want? ")) available_candies=5 i=1 while (i<=x): print ("Candy") i=i+1 if (i>available_candies): print("There were only 5 candies available") break print("Bye") #print all values from 1 to 100 but skip those are divisible by 3 #to showcase continue statement for i in range(1,101): if (i%3==0): continue; print (str(i)+" ", end="") print() #print all values from 1 to 100 but not the odd numbers #to showcase pass statement for i in range(1,100): if (i%2==0): print (str(i)+" ", end="") else: pass print()
true
e4af094f69a9d508f26145e5d56913c88d8e86ad
saikatsengupta89/PracPy
/class_inherit_constructor.py
1,420
4.46875
4
# IF YOU CREATE OBJECT OF SUB CLASS IT EILL FIRST TRY TO FIND INIT OF SUB CLASS # IF IT IS NOT FOUND THEN IT WILL CALL INIT OF SUPER CLASS # class A: def __init__(self): print ("This is from constructor A") def feature1(self): print ("Feature1A is working fine") def feature2(self): print ("Feature2 is working fine") class B: def __init__(self): print ("This is from constructor B") def feature1(self): print ("Feature1B is working fine") def feature3(self): print ("Feature3 is working fine") def feature4(self): print ("Feature4 is working fine") class C (A,B): def __init__(self): super().__init__() #calling the init of super class print ("This is from constructor C") #calling method of super class from subclass def feature(self): super().feature2() # by default the below statement will create an instance for class B and will call the constructor of class A # if there is no constructor defined for class B b= B() #below instance creation will call the __init__ of super class A and not B. This is due to MRO (Method Resolution Order) #whenever you have multiple class inheritance, the child class will always look up to that parent class which comes left #it will always start from left to right. c=C() c.feature1() c.feature()
true
8119dc127f1f9b1a05bb1890769527bb08f40d46
m-tranter/cathedral
/python/Y8/hangman.py
1,442
4.125
4
# hangman.py - simple hangman game from random import * def main(): WORDS = ['acorn', 'apple', 'apricot', 'grape', 'grapefruit', 'kiwi', 'lemon', 'mango', 'melon', 'orange', 'peach', 'pear', 'pineapple', 'raspberry', 'satsuma'] # pick a word randomly word = choice(WORDS) guessed, lWord = '', len(word) print("*** Hangman ***") print("\nThe word is {} letters long.".format(lWord)) print("_ " * lWord) for i in range(5): letter = input("\nGuess a letter: ").lower() if len(letter) == 1: if letter in word: temp = "\nYes, the word contains " guessed += letter else: temp = "\nNo, it doesn't contain " output = ' '.join(x if x in guessed else '_' for x in word) print("{0} '{1}'.\n{2}".format(temp, letter, output)) else: print("Just one letter for now please!") print("\nThat's all your letter guesses used up.") if input("\nNow guess the word: ") == word: print("\nWell done, you got it.") else: print("\nSorry, wrong. It was: \"{}\".".format(word)) if __name__ == "__main__": main()
true
28572191a4f31cf43fd927dca3e721ce4aff03d6
kevmo/pyalgo
/guttag/031.py
618
4.21875
4
# INSTRUCTIONS # input: integer # output: root and power such that 0 < pwr < 6 and # root**pwr = integer from sys import argv user_number = int(argv[1]) def find_root_and_power(num): """ Input: num Returns a root, power such that power is 2 and 5, inclusive, and root**power = num. """ root = 0 for pwr in range(2, 6): while root**pwr < num: root += 1 if root**pwr == num: return root, pwr else: root = 0 print "There is no root, power pair for {}.".format(num) return None print find_root_and_power(user_number)
true
4c5e94f7469efc1849249ab4c47050a2ff62bbf3
moayadalhaj/data-structures-and-algorithms401
/challenges/stack-queue-pseudo/stack_queue_pseudo/stack_queue_pseudo.py
2,378
4.40625
4
class Node: def __init__(self, value): self.value = value self.next = None class Stack: """ create a stack class that containes three methods push: to add a new node at the top of stack pop: to delete the top node in the stack peek: to return the value of top node if it exist """ def __init__(self): self.top = None def push(self, value): """ push: to add a new node at the top of stack """ node = Node(value) node.next = self.top self.top = node def pop(self): """ pop: to delete the top node in the stack """ if self.top == None: raise Exception("This stack is empty") temp=self.top self.top=self.top.next temp.next=None return temp.value def peek(self): """ peek: to return the value of top node if it exist """ try: return self.top.value except: return "This stack is empty" class PseudoQueue: """ PseudoQueue class that implement a standard queue interface which containes two methods enqueue: which inserts value into the PseudoQueue, using a first-in, first-out approach. dequeue: which extracts a value from the PseudoQueue, using a first-in, first-out approach. """ def __init__(self): self.front = Stack() self.rear = Stack() def enqueue(self, value): """ enqueue: which inserts value into the PseudoQueue, using a first-in, first-out approach. """ node = Node(value) if not self.rear.top: self.front.top = node self.rear.top = node else: temp = self.rear.top self.rear.push(value) self.rear.top.next = None temp.next = self.rear.top def dequeue(self): """ dequeue: which extracts a value from the PseudoQueue, using a first-in, first-out approach. """ try: temp = self.front.pop() return temp except: return 'This queue is empty' if __name__ == '__main__': a = PseudoQueue() a.enqueue(5) a.enqueue(6) a.enqueue(7) print(a.dequeue()) print(a.dequeue()) print(a.dequeue()) print(a.dequeue())
true
022ac59fc09a1e47b58038fc2b2c081da84ec48a
maniiii2/PSP-LAB-PYTHON-
/python/condition_demo.py
367
4.1875
4
#Conditional statements #using if statement find the largest among two numbers x=int(input("enter first number")) print("x=",x) print(type(x)) y=int(input("enter second number")) print("y=",y) print(type(y)) if x>y: print("x is greater than y") elif x==y: print("x is equal to y") else: print("y is greater than x") z=x+y print("Z",z)
true
ec9d5a106d1b21e409890b52b34f0c233f17c2e5
thtay/Algorithms_and_DataStructure
/CrackingCodingInterview_Python/Arrays_and_Strings/stringComp.py
1,251
4.1875
4
''' String compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaa would be a2b1c5a3. If the "compressed" string would not become smaller than the orignal string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). ''' ''' let's iterate through the word: two pointer appraoch would work here aaabbbcccaakk ^^ if if i and f are the same increment only f and count another aaabbbcccaakk ^ ^ i f same as above aaabbbcccaakk ^ ^ i f not the same. so append i and the counter and move i to f and increment f by 1 ''' def stringComp(word): ans = "" forward = 1 i = 0 counter = 1 while forward < len(word): if word[i] == word[forward]: counter += 1 forward += 1 else: ans += word[i] ans += str(counter) i = forward forward += 1 counter = 1 if forward + 1 > len(word): ans += word[i] ans += str(counter) if len(ans) >= len(word): return word return ans ''' Test Cases ''' print(stringComp('aaabbbcccaakk')) print(stringComp('aabbbcccaakkc')) print(stringComp('abcnfjdk')) print(stringComp('aabbbcccaakkc')) print(stringComp('aabbbcccaaaakkcb'))
true
d74ddb75db7228a67bdab656e47e54523277ac5d
kagomesakura/palindrome
/pal.py
291
4.21875
4
def check_palindrome(string): half_len = len(string) // 2 #loop through half the string for i in range(half_len): if string[i] != string[len(string)-1-i]: return False return True user_input = input('what is your word? ') print(check_palindrome(user_input))
true
23a92b7be84aea5b82f891cc5eb99f807c3f0e49
dhilanb/snakifywork
/Unit 1 and 2 Quiz/Problem5.py
280
4.125
4
A= int(input("How many feet does a nail go up during the day? ")) B= int(input("How many feet does the snail fall at night? ")) H= int(input("How high would you like the snail to go up? ")) days= H/(A-B) print("It will take the snail "+str(days)+" days to go up "+str(H)+" feet.")
true
fe732b17a297b599562ad04b0f19832c1e2fdeaf
carlita98/MapReduce-Programming
/1.Distributed greed/P1_mapper.py
569
4.1875
4
#!/usr/bin/python # Filtering parttern: It evaluates each line separately and decides, # based on whether or not it contains a given word if it should stay or go. # In particular this is the Distributed Grep example. # Mapper: print a line only if it contains a given word import sys import re searchedWord = sys.argv[1] for line in sys.stdin: line = re.sub( r'^\W+|\W+$', '', line ) words = re.split(r'\s' , line) words = [item.lower() for item in words] if searchedWord.lower() in words: print( "" + '\t' + line )
true
0b070f64a2cb7dfa6e30f39dd56909c8161f7b85
ajaymonga20/Projects2016-2017
/question2.py
1,698
4.53125
5
# AJAY MONGA -- QUESTION 2 -- COM SCI TEST -- FEBRUARY 14, 2017 # imports # Nothing to Import # Functions def caught_speeding(speed, birthday): if (speed <= 60) and (birthday == False): # Returns 0 if the speed is less than 60 return 0 elif (speed >= 61) and (speed <= 80) and (birthday == False): # If the speed is in the range of 61-80 and it is not their birthday, it returns a 1 return 1 elif (speed > 81) and (birthday == False): # If the speed is any integer larger than 81 and not their birthday, then it returns 2 return 2 elif (birthday == True) and (speed <= 65): # If it is their birthday and their seed is 65 or lower then it returns 0 return 0 elif (birthday == True) and (speed >= 66) and (speed <= 85): # If it is their birthday and they are between 66-85, then it returns 1 return 1 elif (birthday == True) and (speed >= 86): # If it is their birthday, but are going any faster than 86 then it returns 2 return 2 def input_string(birthday): # This small function tells the system that if user answers "yes" to the promt, then to convert that to True or False for the caught_speeding function def input_string(birthday): if (birthday == "yes") return True elif (birthday == "no"): return False # Main Code speed = input("what is your speed? ") # This asks for the speed, it is input for integers birthday = raw_input("Is it your birthday? answer: yes or no ") # This asks for if it is your birthday or not, this is raw_input for strings input_string(birthday) # This calls the function to convert the "yes" or "no" to True or False print caught_speeding(speed, birthday) # This prints the result from the caught_speeding function
true
f050bb18b1a8914af117e64b15d22d2e2b06a422
nsatterfield2019/Notes
/Week 8_Plotting.py
651
4.25
4
# PLOTTING (withmathploitlib) import matplotlib.pyplot as plt plt.figure(1) # creates a new window plt.plot([1, 2, 3, 4]) # if there is no x axis, it just gives index 0, 1, 2... plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.figure(2, facecolor ='limegreen') # opens up a new window/figure x = [x for x in range(10)] y = [y**2 for y in range(10)] # plot.plt takes kwarg (keyword arguments) plt.plot(x,y, color='violet', marker='o', markersize=10, linestyle="--", alpha=0.5) plt.xlabel('time (days)') plt.ylabel('excitement level (yays)', color = 'red') plt.title('Example Plot', color = 'blue', fontsize=30) plt.axis([1, 10, 10, 100]) plt.show()
true
da762ad4794c151ea8f9d3c9133d336b974da541
matt-ankerson/ads
/queues/supermarket_model_1.py
2,103
4.1875
4
from queue import Queue from customer import Customer import random as r # Author: Matt Ankerson # Date: 15 August 2015 # This script models queue behaviour at a supermarket. # The scenario is: 10 checkouts, a customer selects a checkout at random. class SuperMarket(object): def __init__(self): r.seed() self.n_customers = 0 self.done = False self.time_taken = 0 self.checkouts = [] for k in range(10): # build list of checkout queues q = Queue() self.checkouts.append(q) def add_customer(self): # randomly assign a new customer to a queue c = Customer(r.randint(1, 5)) self.checkouts[r.randint(0, 9)].enqueue(c) self.n_customers += 1 # increment n_customers def clock_a_minute(self): self.time_taken += 1 # add a customer every two minutes. if self.n_customers <= 1000 and self.time_taken % 2 == 0: self.add_customer() # decrement time required for the people at the head of each queue for checkout in self.checkouts: if not checkout.is_empty(): # decrement time left for the first customer checkout.first().checkout_time -= 1 if checkout.first().checkout_time <= 0: # if the customer has finished, pull them off the queue checkout.dequeue() # assess whether or not we have customers left to deal with self.done = self.queues_empty() def queues_empty(self): # check to ensure that we've still got customers to deal with empty = True if self.n_customers < 1000: empty = False else: for checkout in self.checkouts: if not checkout.is_empty(): empty = False return empty if __name__ == "__main__": print("Random Queue Assignment: ") soup = SuperMarket() while not soup.done: soup.clock_a_minute() print("Time taken: " + str(soup.time_taken))
true
e6eb97080ddf47dda39b56673e6d47b390fe705a
GiovanniSinosini/cycle_condictions
/area_peri.py
269
4.375
4
pi = 3.1415 # Calculator perimeter and area radius = float(input("Enter radius value (in centimeters): ")) area = pi * (radius **2) perimeter = 2 * pi * radius print("The area value is:{:.2f}".format(area)) print( "The perimeter value is:{:.2f}".format(perimeter))
true
b844861db93e2d99d345d5b0e83ef01a88622fb2
mwharmon1/UnitTestStudentClass
/test/test_student.py
1,875
4.28125
4
""" Author: Michael Harmon Last Date Modified: 10/28/2019 Description: These unit tests will test the Student class constructors and functionality """ import unittest from class_definitions import student as s class MyTestCase(unittest.TestCase): def setUp(self): self.student = s.Student('Harmon', 'Michael', 'BIS') def tearDown(self): del self.student def test_object_created_required_attributes(self): student = s.Student('Harmon', 'Michael', 'BIS') assert student.last_name == 'Harmon' assert student.first_name == 'Michael' assert student.major == 'BIS' def test_object_created_all_attributes(self): student = s.Student('Harmon', 'Michael', 'BIS', 4.0) assert student.last_name == 'Harmon' assert student.first_name == 'Michael' assert student.major == 'BIS' assert student.gpa == 4.0 def test_student_str(self): self.assertEqual(str(self.student), "Harmon, Michael has major BIS with gpa: 0.0") def test_object_not_created_error_last_name(self): with self.assertRaises(ValueError): student = s.Student('100', 'Michael', 'BIS') def test_object_not_created_error_first_name(self): with self.assertRaises(ValueError): student = s.Student('Harmon', '200', 'BIS') def test_object_not_created_error_major(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', '12345') def test_object_not_created_error_gpa(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', 'BIS', 'Bad GPA') def test_object_not_created_error_gpa_not_in_range(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', 'BIS', 5.0) if __name__ == '__main__': unittest.main()
true
08e693a2fbd53015bf7834908ee32ce141e8db99
SaneStreet/challenge-100
/challenge105/challenge105.py
896
4.1875
4
""" To use the python script in Command Prompt: Write 'python your_file_name.py' Example: 'python challenge101.py' """ # imports the 'month_name' functionality from the calendar module from calendar import month_name # function with int as parameter def MonthName(number): # variable holding the name of the month from 'number' monthName = month_name[number] # if number is less than 1 if(number < 1): # prompt the user with a message print("Number is below 1. Must be between 1 - 12.") # else if number is more than 12 elif(number > 12): # prompt the user with a message print("Number is above 12. Must be between 1 - 12.") # if everything above is False else: # print the name of the month print(monthName) # function calls with arguments (must be a number between 1 - 12) MonthName(1) MonthName(4) MonthName(12)
true
2a53348c85e88768fd75baa03fa1b7232a4906d7
yjthay/Leetcode
/63.py
1,835
4.375
4
''' 63. Unique Paths II Medium 862 120 Favorite Share A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Note: m and n will be at most 100. ''' import copy class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ paths = copy.deepcopy(obstacleGrid) rows = len(obstacleGrid) cols = len(obstacleGrid[0]) for row in range(rows): for col in range(cols): if obstacleGrid[row][col] == 1: paths[row][col] = 0 else: if row == 0 and col == 0: paths[row][col] = 1 elif row == 0: paths[row][col] = paths[row][col - 1] elif col == 0: paths[row][col] = paths[row - 1][col] else: paths[row][col] = paths[row - 1][col] + paths[row][col - 1] # if obstacleGrid[row-1][col]==1: # paths[row][col] = paths[row][col-1] # elif obstacleGrid[row][col-1]==1: # paths[row][col] = paths[row-1][col] # else: # paths[row][col] = paths[row-1][col]+paths[row][col-1] # print(paths) return paths[rows - 1][cols - 1]
true
169c8d5734e4b1e190cc3af9e7c1c47f9e00111a
alimulyukov/Course_Work_2021
/ConVolCylStep4.py
1,218
4.1875
4
import math print("\n\tThe volume of a Cylinder is:") print("\n\t\t\tV = \u03C0 \u00D7 radius\u00B2 \u00D7 height") print("\n\tThis program will take as input the radius and height") print("\tand print the volume.") file = open("data.txt","a") #w,r,a name = input("\n\tWhat is your name: ") radius = 1 height = 1 while (radius != 0 or height != 0): try: radius = input("\n\tInput radius (cm): ") radius = int(radius) height = input("\n\tInput height (cm): ") height = int(height) except: print("\n\t\tNumeric Type Required") height = -1 radius = -1 if (radius >= 0 and height >= 0): volume = math.pi * radius * radius * height volume = round(volume,2) print("\n\t\tHi "+name+"!") print("\n\t\tGive a cylinder with:") print("\t\tRadius = "+str(radius)) print("\t\tHeight = "+str(height)) print("\t\tThe volume is: "+str(volume)+"\n") file.write(str(volume)+"\n") else: print("\n\t\tYou have entered an invalid value") print("END PROGRAM") file.close() ''' 1) User a try except structure to account for String inputs try: <try code block> <try code block> <try code block> except: <except code block> 2) Write information to file to be accessed later. '''
true
a82fa240bd47e700230e5798dfdb882f29888208
eldadpuzach/MyPythonProjects
/Functions/Display Calendar.py
303
4.46875
4
# Python program to display calendar of given month of the year # import module import calendar yy = 2018 mm = 10 # To ask month and year from the user # yy = int(input("Enter year: ")) # mm = int(input("Enter month: ")) # display the calendar for i in range(1, 13): print(calendar.month(yy, i))
true
874eb33018e94ed35c455f77dec7e86842d4351a
lilliansun/cssi_2018_intro
/python/python-testing/fizzbuzz.py
570
4.34375
4
"""my implementation of fizzbuzz""" def fizz_buzz(num): """Prints different words for certain natural numbers This function prints out fizz when a number is divisible by 3, buzz when divisible by 5, and fizzbuzz when divisible by both. Args: num: (int) The number to convert based on fizzbuzz rules. """ if ((num%3 == 0) and (num%5 == 0)): print("fizzbuzz") elif num%3 == 0: print("fizz") elif num%5 == 0: print("buzz") else: print(num) for this in range(1, 100): fizz_buzz(this)
true
582b693640f4e32601b7b1a7f34049218cbba291
sreehari333/pdf-no-3
/to check male or female.py
379
4.40625
4
gender = input("Please enter your Gender : ") if (gender == "M" or gender == "m" or gender == "Male" or gender == "male"): print("The gender in Male") elif (gender == "F" or gender == "f" or gender == "FeMale" or gender == "Female" or gender == "feMale" or gender == "female"): print("The gender is Female") else: print("Please provide an appropriate format")
true
6d78a8beb5805d430f4470b07415f09a6d713753
naresh3736-eng/python-interview-problems
/trees/binaryTree_is_fullBinaryTree.py
2,056
4.1875
4
class Node: def __init__(self, key): self.key = key self.leftchild = None self.rightchild = None # using recursion def isFullBT_recursion(root): if root is None: return None if root.leftchild is None and root.rightchild is None: return True if root.leftchild is not None and root.rightchild is not None: return isFullBT_recursion(root.leftchild) and isFullBT_recursion(root.rightchild) return False root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40); root.left.left = Node(50); root.right.left = Node(60); root.right.right = Node(70); root.left.left.left = Node(80); root.left.left.right = Node(90); root.left.right.left = Node(80); root.left.right.right = Node(90); root.right.left.left = Node(80); root.right.left.right = Node(90); root.right.right.left = Node(80); root.right.right.right = Node(90); if isFullBT_recursion(root): print "The Binary tree is full" else: print "Binary tree is not full" # using iterative approach def isFullBT_iterative(root): if root is None: return None queue = [] queue.append(root) while len(queue) >=1: node = queue[0] queue.pop(0) if node.leftchild is None and node.rightchild is None: continue if node.leftchild is not None or node.rightchild is not None: return False queue.append(node.leftchild) queue.append(node.rightchild) return True root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40); root.left.left = Node(50); root.right.left = Node(60); root.right.right = Node(70); root.left.left.left = Node(80); root.left.left.right = Node(90); root.left.right.left = Node(80); root.left.right.right = Node(90); root.right.left.left = Node(80); root.right.left.right = Node(90); root.right.right.left = Node(80); root.right.right.right = Node(90); if isFullBT_iterative(root): print "The Binary tree is full" else: print "Binary tree is not full"
true
62ebadffa4205282a3fb81a7ddd679bf8da0dc94
snekhasri/spring.py
/spring.py
832
4.34375
4
import turtle as t #importing the module as "t" t.bgcolor("green") def spiral_shape(p,c): #creating a function with parameters "p" and "c" if p > 0: #if the p is less than 0, t.forward(p) #moving the turtle forward at p units t.right(c) #setting the turtle right at an angle of c spiral_shape(p-5,c) #calling the function with the arguments as given t.shape('classic') #setting the shape of the turtle as "classic" t.reset() #resetting the turtle t.pen(speed=25) #setting the speed of the pen to 25 length = 400 #declaring a variable "length" to 400 turn_by = 121 #declaring a varibale "turn_by" to 121 t.penup() #the drawing is not ready t.setpos(-length/2, length/2) #setting the position as given t.pendown() #starting to draw spiral_shape(length, turn_by) #calling the function with the given arguments
true
c5a328137b59adfa9e23b295e695a2d53026e7e6
Naveen8282/python-code
/palyndrome.py
230
4.15625
4
def IsPalyndrome(input1): txt = input1[::-1] if txt == input1: return "yes" else: return "no" str1=str(input("enter the string: ")) print ("is the string %s Palyndrome? %s" % (str1,IsPalyndrome(str1)))
true
5b8b60e383c8ad3b9597a0774b7c55706fcc0497
acbahr/Python-Practice-Projects
/magic_8_ball_gui.py
1,524
4.3125
4
# 1. Simulate a magic 8-ball. # 2. Allow the user to enter their question. # 3. Display an in progress message(i.e. "thinking"). # 4. Create 20 responses, and show a random response. # 5. Allow the user to ask another question or quit. # Bonus: # - Add a gui. # - It must have box for users to enter the question. # - It must have at least 4 buttons: # - ask # - clear (the text box) # - play again # - quit (this must close the window) # Basic text in TKinter is called a label import random import tkinter as tk """ def magic_8ball(): root = tk.Tk() # constructor class in TKinter. Creates a blank window active = True responses = ['Yes', 'No', 'Maybe', 'Try Again', "It's Possible", 'It is in the stars', 'Ask me another time', 'I am not sure', 'Ask your mother', 'Ask your father', 'Only if you Live Bearded'] while active: label1 = tk.Label(text='What would you like to ask?') label1.pack() entry = tk.Entry(width=75) entry.pack() question = entry.get() if question != 'n' or question != 'N': thinking = tk.Label(text='thinking....') thinking.pack() return random.choice(responses) else: print('thinking...') print(random.choice(responses)) try_again = input('Would you like to try again? y/n: ') if try_again.lower() == 'n': active = False root.mainloop() # mainloop keeps running the window until closed by user magic_8ball() """
true
37c3e583c372fc2adbec60ca23e524fa9d4de0fc
dfrog3/pythonClass
/python/week 1/three_sort_david.py
1,772
4.1875
4
print("Hello, I will sort three integers for you.\nPlease enter the first integer now") firstNumber = int(input()) print("Thank you.\nPlease enter the second integer.") secondNumber = int(input()) print("Thank you.\n please eneter the last integer.") thirdNumber = int(input()) #fills starting variables if firstNumber < secondNumber and firstNumber < thirdNumber: smallestNumber = firstNumber elif firstNumber < secondNumber and firstNumber > thirdNumber: middleNumber = firstNumber elif firstNumber > secondNumber and firstNumber < thirdNumber: middleNumber = firstNumber elif firstNumber > secondNumber and firstNumber > thirdNumber: largestNumber = firstNumber else: print("error in first sort block") #first number sorting code block if secondNumber < firstNumber and secondNumber < thirdNumber: smallestNumber = secondNumber elif secondNumber < firstNumber and secondNumber > thirdNumber: middleNumber = secondNumber elif secondNumber > firstNumber and secondNumber < thirdNumber: middleNumber = secondNumber elif secondNumber > firstNumber and secondNumber > thirdNumber: largestNumber = secondNumber else: print("error in second sort block") #second number sorting code block if thirdNumber < secondNumber and thirdNumber < firstNumber: smallestNumber = thirdNumber elif thirdNumber < secondNumber and thirdNumber > firstNumber: middleNumber = thirdNumber elif thirdNumber > secondNumber and thirdNumber < firstNumber: middleNumber = thirdNumber elif thirdNumber > secondNumber and thirdNumber > firstNumber: largestNumber = thirdNumber else: print("error in third sort block") #third number sorting code block print("The results are in.\n", smallestNumber , middleNumber , largestNumber)
true
1e04b2e77b982dbea75275781f2ed4937dbdca86
k-unker/codewars_katas
/where_is_my_parent.py
1,351
4.21875
4
#!/usr/bin/env python3 ''' Mothers arranged dance party for children in school. On that party there are only mothers and their children. All are having great fun on dancing floor when suddenly all lights went out.Its dark night and no one can see eachother.But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want. Legend: -Uppercase letters stands for mothers,lowercase stand for their children. I.E "A" mothers children are "aaaa". -Function input:String contain only letters,Uppercase letters are unique. Task: Place all people in alphabetical order where Mothers are followed by their children.I.E "aAbaBb" => "AaaBbb". ''' def find_children(dancing_brigade): myarr = [] dancing_brigade = sorted(dancing_brigade) for i in range(len(dancing_brigade)): if dancing_brigade[i].lower() in dancing_brigade or dancing_brigade[i].upper() in dancing_brigade: myarr.append(dancing_brigade[i]) mysmall = dancing_brigade[i].lower() mylarge = dancing_brigade[i].upper() mycounter = dancing_brigade.count(mysmall) - dancing_brigade.count(mylarge) a = 0 while a <= mycounter: myarr.append(dancing_brigade[i].lower()) a += 1 return ''.join(myarr)[:len(dancing_brigade)]
true
0fd5a273d72beb9bf7cbc4c663f13410a4aeb881
prkapadnis/Python
/Programs/eighth.py
440
4.21875
4
""" Reverse a number """ number = int(input("Enter the number:")) reverse = 0 if number < 0: number = number * (-1) while number != 0: remainder = number % 10 reverse = reverse * 10 + remainder number = number // 10 print(-reverse) else : while number != 0: remainder = number % 10 reverse = reverse * 10 + remainder number = number // 10 print(-reverse) print(2**31)
true
b3ed3b8ea862043d0d89d77bc1fceb90325acabe
prkapadnis/Python
/Set.py
620
4.1875
4
myset = set() print(type(myset)) myset = {1,2,3,4,5} print(myset) #built in function myset.add(2)# This does not made any change because set don't allow the duplicate values print(myset) myset.remove(2) print("After removing 2:", myset) # print("Using pop() function: ",myset.pop()) print(myset) second_set = {3,4,5,6} unioun_set = myset.union(second_set) print("The Union of set is:",unioun_set) print("The Intersection of set is:", myset.intersection(second_set)) print("The Difference of set is:", myset.difference(second_set)) print("The Symmetric Difference of set is:", myset.symmetric_difference(second_set))
true
c553606397136f91a2ad94d3c48c0f5d0f999a5b
prkapadnis/Python
/OOP/Class_var.py
1,797
4.25
4
""" Difference between class variable and Instance variable Instance Variable: -The Instance variable is unique for each instance -If we changed the class variable for specific instance then it will create a new instance variable for that instance Class Variable: The class variable is shared among all instance of class - cannot be changed by instance - It is also known as static variable Note : 1].__dict__ : It will return a dictionary that contains the attribute of instance """ class Student: branch = "Computer Engineering" pratik = Student() ajit = Student() #For Pratik instance pratik.name = "Pratik" # This name is a instance variable of pratik pratik.rollNum = 69 #For Ajit intance ajit.name = "Ajit" # This name is instance variable of Ajit ajit.rollNum = 50 print(f"The Name {pratik.name} and Roll number {pratik.rollNum} and branch is {pratik.branch}") print(f"The Name {ajit.name} and Roll number {ajit.rollNum} and branch is {ajit.branch}") print("All the instance variable of Pratik:",pratik.__dict__) print("All the instance variable of ajit:",ajit.__dict__) # If we have to change the branch for specific instance ajit.branch = "Civil Enginnering" print("After changing the branch") print(f"The Name {pratik.name} and Roll number {pratik.rollNum} and branch is {pratik.branch}") print(f"The Name {ajit.name} and Roll number {ajit.rollNum} and branch is {ajit.branch}") #If we change the branch of specific instance then it creates a new instance variable # for that instance and it does not affect the class variable print("After chaging the class variable for specific instance:",ajit.__dict__) #And We can access it by clas name print("The class variable is:",Student.branch)
true
4c55155e0f66164f9f1512cb51c007b23234a1be
prkapadnis/Python
/Data Structure/Linked List/SinglyLinkedList.py
2,746
4.15625
4
class Node: def __init__(self, data): # defination of Node self.data = data self.next_node = None class LinkedList: def __init__(self): self.head = None self.size = 0 def reverse(self): privious = None current = self.head next = None while current!= None: next = current.next_node current.next_node = privious privious = current current = next self.head = privious print("The linked list is reversed!!") def get_size(self): return self.size def display(self): current = self.head print("The Data: ",end="") while current: print(current.data, end=" ") current = current.next_node #Insertion Operation def insert_at_first(self, data): new_node = Node(data) self.size+=1 if self.head is None: self.head = new_node else: new_node.next_node = self.head self.head = new_node def insert_at_middle(self, data, position): new_node = Node(data) self.size += 1 current = self.head for i in range(1, position-1): current = current.next_node new_node.next_node = current.next_node current.next_node = new_node def insert_at_last(self, data): new_node = Node(data) self.size += 1 current = self.head while current.next_node: current = current.next_node current.next_node = new_node #deleting Operations the nodes def delete_first(self): delete_node = self.head self.head = self.head.next_node del delete_node print("The first node Deleted!!") def delete_middle(self, position): delete_node = self.head.next_node temp_node = self.head for i in range(1, position-1): delete_node = delete_node.next_node temp_node = temp_node.next_node temp_node.next_node = delete_node.next_node del delete_node print(f"{position}th node deleted!!") def delete_last(self): current = self.head.next_node last_second_node = self.head while current.next_node: current = current.next_node last_second_node = last_second_node.next_node last_second_node.next_node = None del current list = LinkedList() list.insert_at_first(10) list.insert_at_last(20) list.insert_at_last(30) list.insert_at_middle(25, 3) list.display() print() print("The size is:",list.get_size()) list.delete_first() list.delete_last() list.delete_middle(2) list.reverse() list.display()
true
48db87ee9b1285a6b269caba3b64b40f9ea89035
prkapadnis/Python
/File/second.py
896
4.40625
4
""" write() function: - The Write function writes the specified text into the file. - Where the specified text is inserted is depends on the file mode and stram position. - if 'a' is a file mode then it well be inserted at the stream position and default is end of the file. - if 'w' is a file mode then it will override the file and insert it at the begining. """ with open("Python/File/my_data2.txt", mode="w", encoding="utf-8") as myFile: myFile.write("Some Random Text \nand more random text \nand more and more and more random text") with open("Python/File/my_data2.txt", encoding="utf-8") as myFile: print(myFile.read()) print() with open("Python/File/my_data2.txt", mode="w", encoding="utf-8") as myFile: myFile.write("Name: pratik Rajendra Kapadnis") with open("Python/File/my_data2.txt", encoding="utf-8") as myFile: print(myFile.read())
true
7ca93f1f2fdf8f757c2206e747681e600453d93b
prkapadnis/Python
/Iterables/Iterable.py
1,178
4.34375
4
""" Iterable : Iterable are objects that are capable of returning their member one at a time means in short anything we can liip over is an iterable. Iterator : Iterable are objects which are representing the stream of data that is iterable. iterator creates something iterator pool which allows us to loop over an item in iterable using thetwo methods that is __iter__() and __next__(). __iter__(): The __iter__() method returns the iterator of an iterable. __next__():The __next__() method returns the next element of an iterator Key points: - The difference between Iterable and Iterator is that the __next__() method is only accessible to the Iterator. The Iterable only have __iter__() method. - Iterator also have __iter__() method because iterators are also iterables but not vice versa. """ sample = [1, 2, 3] it = iter(sample) print(next(it)) print(next(it)) print(next(it)) # If overshoot the limit the number of times we call the next() method. then an exception # is occur which is called StopIteration Exception. # print(next(it))
true
2a06954878ad58139831283b2ec6ec0a6cb9ec74
marciniakdaw/Python-Udemy
/BMI calculator.py
519
4.25
4
height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) BMI_score=round(weight/height**2) if BMI_score<19: print(f"Your BMI is {BMI_score}, you are underweight.") elif BMI_score<25: print(f"Your BMI is {BMI_score}, you have a normal weight.") elif BMI_score<30: print(f"Your BMI is {BMI_score}, you are slightly overweight.") elif BMI_score<35: print(f"Your BMI is {BMI_score}, you are obese.") else: print(f"Your BMI is {BMI_score}, you are clinically obese.")
true
4b3f73baf3fbd69d6bf149be403396cea9222ab5
j-tanner/Python.Assignments
/Assignment_8.4.py
240
4.1875
4
filename = input("Enter file name: ") filehandle = open(filename) wordlist = list() for line in filehandle: for words in line.split(): if words not in wordlist: wordlist.append(words) wordlist.sort() print(wordlist)
true
ab72ffcb3709b58a3f84c1d70833507f67fbd8da
courses-learning/python-crash-course
/4-1_pizzas.py
225
4.3125
4
# Make a list of 3x types of pizza and use a for loop to print pizzas = ['peperoni', 'hawian', 'meat feast'] for pizza in pizzas: print(f"I like {pizza} pizza.") print('I like pizza takeaway nearly as much as Indian!!!')
true
9bfc0342386bc8efdc7be6ac1f7988ae91ee022c
sacktock/practicals
/adspractical17extra.py
2,981
4.34375
4
#adspractical17extra.py #algorithms and data structures practical week 17 #matthew johnson 22 february 2013, last revised 15 february 2018 ##################################################### """an extra question that has nothing to do with the algorithms from the lectures, but gives some practice on thinking about graph algorithms""" #define an example tree using adjacency lists V = "ABCDEFGHIJKLM" E = {'A': 'BCD', 'C': 'AGH', 'B': 'AEF', 'E': 'BIJK', 'D': 'A', 'G': 'C', 'F': 'BL', 'I': 'E', 'H': 'C', 'K': 'EM', 'J': 'E', 'M': 'K', 'L': 'F'} T = (V, E) """ in a tree, there is a unique path between each pair of vertices; the diameter of a tree is the longest such path (the diameter of the example tree above is 6); write a function that takes a tree and returns its diameter the function should be recursive; first, what is the diameter of a tree on 1 vertex? what if the tree has more vertices and you remove one of them and split the tree into many smaller trees; what do you need to know about the smaller trees to find the diameter of the larger tree? """ def tree_diameter(T): """given a tree as a pair, the vertex set and adjacency lists, return the diameter of the tree""" V, E = T #complete the function here #uncomplete root = '' for v in V: if len(E[v]) == 2: root = v break lDiameter = 1 + tree_diameter(rT) rDiameter = 1 + tree_diameter(lT) return max(max(rDiameter,lDiameter),) ################################################### #the following function might prove useful def print_lists(G): """takes a graph with adjacency list representation and prints the lists""" V, E = G for vertex in V: n = "" for neighbour in E[vertex]: n += neighbour + ", " print (vertex[0] + ": " + n[:-2]) ################################################### #tests V1 = "A" E1 = {'A': ''} T1 = (V1, E1) V2 = "AB" E2 = {'A': 'B', 'B': 'A'} T2 = (V2, E2) V3 = "ABC" E3 = {'A': 'B', 'C': 'B', 'B': 'AC'} T3 = (V3, E3) V4 = "ABCD" E4 = {'A': 'B', 'C': 'BD', 'B': 'AC', 'D': 'C'} T4 = (V4, E4) E4a = {'A': 'B', 'C': 'B', 'B': 'ACD', 'D': 'B'} T4a = (V4, E4a) V5 = "ABCDEFGHIJKLMNOPQR" E5 = {'A': 'B', 'C': 'BD', 'B': 'AC', 'E': 'DF', 'D': 'CE', 'G': 'FH', 'F': 'EG', 'I': 'HJ', 'H': 'GI', 'K': 'JL', 'J': 'IK', 'M': 'LN', 'L': 'KM', 'O': 'NP', 'N': 'MO', 'Q': 'PR', 'P': 'OQ', 'R': 'Q'} T5 = (V5, E5) E5a = {'A': 'B', 'C': 'BD', 'B': 'ACG', 'E': 'DF', 'D': 'CE', 'G': 'BH', 'F': 'E', 'I': 'HJ', 'H': 'GI', 'K': 'JL', 'J': 'IK', 'M': 'LN', 'L': 'KM', 'O': 'NP', 'N': 'MO', 'Q': 'PR', 'P': 'OQ', 'R': 'Q'} T5a = (V5, E5a) def test(): assert tree_diameter(T) == 6 assert tree_diameter(T1) == 0 assert tree_diameter(T2) == 1 assert tree_diameter(T3) == 2 assert tree_diameter(T4) == 3 assert tree_diameter(T4a) == 2 assert tree_diameter(T5) == 17 assert tree_diameter(T5a) == 16 print ("all tests passed")
true
65264cc2e04a26029120617c562595610d3062eb
4RCAN3/PyAlgo
/pyalgo/maths/prime.py
413
4.21875
4
''' module for checking whether a given number is prime or not ''' def prime(n: int): ''' Checking if the number has any factors in the range [2, sqrt(n)] else it is prime ''' if (n == 2): return True result = True for i in range (2, int(n ** 0.5)): if (n % i == 0): result = False break return result ''' PyAlgo Devansh Singh, 2021 '''
true
29c43a96ac935c7f9da7b2bfbc227507d74fd02c
4RCAN3/PyAlgo
/pyalgo/graph/bfs.py
977
4.21875
4
''' module for implementation of breadth first search ''' def bfs(graph: list, start: int): """ Here 'graph' represents the adjacency list of the graph, and 'start' represents the node from which to start """ visited, queue = set(), [start] while (queue): vertex = queue.pop(0) if (vertex not in visited): visited.add(vertex) queue.extend(graph[vertex] - visited) return visited def bfs_paths(graph: list, start: int, goal: int): """ Returns all possible paths between a start vertex and a goal vertex, where the first path is the shortest path """ queue = [(start, [start])] while (queue): (vertex, path) = queue.pop(0) for next in (graph[vertex] - set(path)): if (next == goal): yield path + [next] else: queue.append((next, path + [next])) return queue ''' PyAlgo Devansh Singh, 2021 '''
true
800dc205db1402fb2c155c6d4ac5af0de549988d
niranjan2822/List
/Key Lists Summations.py
1,147
4.21875
4
# Key Lists Summations # Sometimes, while working with Python Dictionaries, we can have problem in which we need to perform the replace of # key with values with sum of all keys in values ''' Input : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]} output : {‘gfg’: 18, ‘is’: 19, ‘best’: 15} ''' # Method #1 : Using sum() + loop # This is one of the ways in which this task can be performed. In this, we perform the summation using sum, and # iteration to each key is done in brute way using loop. # Python3 code to demonstrate working of # Key Values Summations # Using sum() + loop # initializing dictionary test_dict = {'gfg': [4, 6, 8], 'is': [9, 8, 2], 'best': [10, 3, 2]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Key Values Summations # Using sum() + loop for key, value in test_dict.items(): test_dict[key] = sum(value) # printing result print("The summation keys are : " + str(test_dict)) # output : The original dictionary is : {'gfg': [4, 6, 8], 'is': [9, 8, 2], 'best': [10, 3, 2]} # The summation keys are : {'gfg': 18, 'is': 19, 'best': 15}
true