blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3f7e318da7c059e17a7e31761311b49123d30291
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_425.py
709
4.125
4
def main (): temp = (float (input ("What is the temperature: "))) scale = (str (input ("Please enter 'C' for Celsius or 'K' for Kelvin: "))) if (scale == 'C'): if (temp >= 100): print ("At this temperature, water is a gas.") elif (temp <= 0): print ("At this temperature, water is a frozen solid.") else: print ("At this temperature, water is a liquid.") else: if (temp >= 373.15): print ("At this temperature, water is a gas.") elif (temp <= 273.15): print ("At this temperature, water is a frozen solid.") else: print ("At this temperature, water is a liquid.") main ()
true
84504ced69b52147fdcc671ce10cd68d71e498f2
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_054.py
481
4.125
4
def main(): EVEN = 0 ODD = 1 height = int(input("Please enter starting height of the hailstorm: ")) print("Hail is currently at height" , height) while height !=1: if height % 2 == EVEN: height = height // 2 print("Hail is currently at height" , height) elif height % 2 == ODD: height = height * 3 +1 print("Hail is currently at height" , height) print("Hail stopped at height 1") main()
true
c7c6cf60781c3541d6d56ba435aa78f8f969edbc
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_029.py
775
4.125
4
def main(): temp = float(input("Please enter the temperature: ")) letter = input("Please enter 'C' for Celsius or 'K' for Kelvin: ") if temp <= 0 and letter == 'C': print("At this temperature, water is a (frozen) solid.") elif temp >= 1 and temp <= 99 and letter == 'C': print("At this temperature, water is a liquid.") elif temp >= 100 and letter == 'C': print("At this temperature, water is a gas.") elif temp >= 0 and temp <= 273 and letter == 'K': print("At this temperature, water is a (frozen) solid.") elif temp > 273 and temp <373 and letter == 'K': print("At this temperature, water is a liquid.") elif temp > 373 and letter == 'K': print("At this temperature, water is a gas.") main()
true
6ee976cc3bab4e98489059e23009ed4f722ecb8f
MAPLE-Robot-Subgoaling/IPT
/data/HW5/hw5_078.py
427
4.1875
4
width = int(input("Please enter width: ")) height = int(input("Please enter height: ")) symbol_outline = input("Please enter a symbol for the outline:") symbol_fill = input("Please enter a symbol for the fill:") def main(): forl_row = symbol_outline*width mid_row = symbol_outline+(symbol_fill*(width-2))+symbol_outline print(forl_row) for x in range(height): print(mid_row) print(forl_row) main()
true
1c5c9abdc59ed57e5213d37b8e9d541ee5b73de6
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_043.py
766
4.125
4
def main(): enterTemp = float(input("Please enter the temperature: ")) typeTemp = input("Please enter 'C' for Celsisus, or 'K' for Kelvin: ") if typeTemp == "K" and enterTemp >= 373.16: print("At this temperature, water is a gas.") elif typeTemp == "K" and enterTemp <= 273.16: print("At this temperature, water is a solid.") elif typeTemp == "K" and (enterTemp < 373.16 and enterTemp > 273.16): print("At this temperature, water is a liquid.") elif typeTemp == "C" and enterTemp >= 100: print("At this temperature, water is a gas.") elif typeTemp == "C" and enterTemp <= 0: print("At this temperature, water is a solid.") else: print("At this temperature, water is a liquid.") main()
true
dbb76edf02c9c3082671fd89df2bcdd9220a2bb6
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_028.py
790
4.125
4
def main(): unit = input("What unit are you using, enter 'C' for celcius or 'K' for Kelvin") temp = float(input("What is the temperature?")) if (temp <= 0) and (unit == "C") : print("At this temperature, water is a (frozen) solid") elif (temp >= 100) and (unit == "C") : print("At this temperature, water is a gas") elif (temp >0 and temp <100) and (unit == "C"): print("At this temperature, water is a liquid") elif (temp <= 273.15) and (unit =="K"): print ("At this temperature, water is a (frozen) solid.") elif (temp >= 373.15) and (unit == "K"): print ("At this temperature, water is a gas") elif (temp >273.15 and temp <373.15) and (unit == "K"): print("At this temperature, water is a liquid") main()
true
5991c2fbf4a1a987cde366a7a784d1db12fdffc5
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_431.py
550
4.21875
4
def main(): currentHeight = int(input("Please enter the starting height of the hailstone: ")) print("Hail is currently at height",(currentHeight)) while currentHeight != 1: if (currentHeight % 2) == 0: print("Hail is currently at height", currentHeight / 2) currentHeight = (currentHeight / 2) elif (currentHeight % 2) == 1: print("Hail is currently at height", (currentHeight * 3) + 1) currentHeight = ((currentHeight * 3) + 1) print("Hail stopped at height 1") main()
true
f6c13e0b0478f843c4ab72ff4689aaad93b24764
MAPLE-Robot-Subgoaling/IPT
/data/HW4/hw4_030.py
393
4.28125
4
STOP_HEIGHT = 1 def main (): hailHeight = int ( input ("Please enter the starting height of the hailstone: ")) while hailHeight != STOP_HEIGHT: if hailHeight % 2 == 0: print ("Hail is currently at", hailHeight) hailHeight = hailHeight // 2 else: print ("Hail is currently at", hailHeight) hailHeight = hailHeight * 3 + 1 print ("Hail stopped at height 1.") main ()
true
f20872e50a04cfe8ecf00603cd58697ca47bda6a
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_037.py
782
4.125
4
def main(): temp = float(input("Please enter your temperature: ")) scale = input("Please enter 'C' for Celsius, or 'K' for Kelvin: ") if scale == "C" and temp >= 100: print("At this temperature, the water is a gas.") elif scale == "C" and (temp <100 and temp >0): print("At this temperature, the water is a liquid.") elif scale == "C" and temp <0: print("At this temperature, the water is a solid.") if scale == "K" and temp >= 373.16: print("At this temperature, the water is a gas.") elif scale == "K" and (temp < 373.16 and temp > 273.16): print("At this temperature, the water is a liquid.") elif scale == "K" and temp < 273.16: print("At this temperature, the water is a solid.") main()
true
bab242cced1e1ad5251f1876544fa92f2c8f4c73
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_359.py
1,070
4.3125
4
temp = float(input("Please enter the temperature: ")) scale = input("Please enter 'C' for Celsius, or 'K' for Kelvin: ") MELTING_POINT_C = 32 BOILING_POINT_C = 100 MELTING_POINT_K = 273.15 BOILING_POINT_K = 373.15 def main(): if scale == "C": if temp >= 0 and temp < MELTING_POINT_C: print("At this temperature, water is a (frozen) solid.") elif temp >= MELTING_POINT_C and temp < BOILING_POINT_C: print("At this temperature, water is a liquid.") elif temp >= BOILING_POINT_C: print("At this temperature, water is a gas.") else: if temp >= 0 and temp < MELTING_POINT_K: print("At this temperature, water is a (frozen) solid.") elif temp >= MELTING_POINT_K and temp < BOILING_POINT_K: print("At this temperature, water is a liquid.") elif temp >= BOILING_POINT_K: print("At this temperature, water is a gas.") main()
true
c75d93e681c3249f20724da3ac8f6719b683021f
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_332.py
743
4.125
4
def main(): temp = float(input("What is the temperature in degrees? ")) scale = input("What is the scale: Celsius (C) or Kelvin (K)? ") if scale == "C": if temp <= 0: print("At this temperature, water is a solid.") elif (temp > 0) and (temp < 100): print("At this temperature, water is a liquid.") elif temp >= 100: print("At this temperature, water is a gas.") if scale == "K": if temp <= 273.16: print("At this temperature, water is a solid.") if (temp > 273.16) and (temp < 373.16): print("At this temperature, water is a liquid.") if temp >= 373.16: print("At this temperature, water is a gas.") main()
true
0eb4be20b6512b4652c20a39b17e828f3659b886
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_329.py
842
4.25
4
def main(): temperature = float(input("Please enter the temperature:")) units = input("Please enter 'C' for Celcius or 'K' for Kelvin:") if units == "K": ctemp = temperature - 273.2 if ctemp <= 0: print ("At this temperature, water is a (frozen) solid.") elif ctemp > 0 and ctemp < 100: print ("At this temperature, water is a liquid.") else: print ("At this temperature, water is a gas.") elif units == "C": ctemp = temperature if ctemp <= 0: print ("At this temperature, water is a (frozen) solid.") elif ctemp > 0 and ctemp < 100: print ("At this temperature, water is a liquid.") else: print ("At this temperature, water is a gas.") else: print ("Choose 'C' or 'K'") main()
true
4f63d8015f9941746f8d00760d7de222308dd31a
GMwang550146647/network
/1.networkProgramming/2.parallelProgramming/3.coroutines/2.pythonCoroutines/2.Awaitables.py
2,275
4.15625
4
""" 三种 Awaitable Objects 1.Coroutines 2.Tasks 3.Futures """ import asyncio import concurrent.futures """ 1.Coroutines async 包装的函数都会转换成一个Coroutines函数,如果没有await,函数不会调用,会返回Coroutines对象 """ def coroutines(): """用于直接运行的任务""" async def nested(): return 42 async def main(): # Nothing happens if we just call "nested()". # A coroutine object is created but not awaited, # so it *won't run at all*. print(nested()) # Let's do it differently now and await it: print(await nested()) # will print "42". asyncio.run(main()) """ 2.Tasks 用于automatically schedule的任务 """ def tasks(): async def nested(): return 42 async def main(): # Schedule nested() to run soon concurrently # with "main()". task = asyncio.create_task(nested()) # "task" can now be used to cancel "nested()", or # can simply be awaited to wait until it is complete: await task asyncio.run(main()) """ 3.Futures """ def blocking_io(): # File operations (such as logging) can block the # event loop: run them in a thread pool. with open('/dev/urandom', 'rb') as f: return f.read(100) def cpu_bound(): # CPU-bound operations will block the event loop: # in general it is preferable to run them in a # process pool. return sum(i * i for i in range(10 ** 7)) async def main(): loop = asyncio.get_running_loop() ## Options: # 1. Run in the default loop's executor: result = await loop.run_in_executor( None, blocking_io) print('default thread pool', result) # 2. Run in a custom thread pool: with concurrent.futures.ThreadPoolExecutor() as pool: result = await loop.run_in_executor( pool, blocking_io) print('custom thread pool', result) # 3. Run in a custom process pool: with concurrent.futures.ProcessPoolExecutor() as pool: result = await loop.run_in_executor( pool, cpu_bound) print('custom process pool', result) asyncio.run(main()) if __name__ == '__main__': # coroutines() # tasks() # futures() pass
true
9c93463506fcd2ddf6ba8b205ab3a7f27ebaf944
Azure-Whale/Kazuo-Leetcode
/Array/238. Product of Array Except Self.py
2,176
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @File : 238. Product of Array Except Self.py @Time : 10/21/2020 10:37 PM @Author : Kazuo @Email : azurewhale1127@gmail.com @Software: PyCharm ''' class Solution: """ The solution is to create two lists within same length as the given array, since each product consist of ele[:i] and ele[i+1:], store left product part and right product part into two created lists respectively, then using these two array, you build you a new list as your answer """ def productExceptSelf(self, nums: List[int]) -> List[int]: # The length of the input array length = len(nums) # The left and right arrays as described in the algorithm L, R, answer = [0] * length, [0] * length, [0] * length # L[i] contains the product of all the elements to the left # Note: for the element at index '0', there are no elements to the left, # so the L[0] would be 1 L[0] = 1 for i in range(1, length): # L[i - 1] already contains the product of elements to the left of 'i - 1' # Simply multiplying it with nums[i - 1] would give the product of all # elements to the left of index 'i' L[i] = nums[i - 1] * L[i - 1] # R[i] contains the product of all the elements to the right # Note: for the element at index 'length - 1', there are no elements to the right, # so the R[length - 1] would be 1 R[length - 1] = 1 for i in reversed(range(length - 1)): # R[i + 1] already contains the product of elements to the right of 'i + 1' # Simply multiplying it with nums[i + 1] would give the product of all # elements to the right of index 'i' R[i] = nums[i + 1] * R[i + 1] # Constructing the answer array for i in range(length): # For the first element, R[i] would be product except self # For the last element of the array, product except self would be L[i] # Else, multiple product of all elements to the left and to the right answer[i] = L[i] * R[i] return answer
true
ad4e5783ab8452552b9e606143057fab8bfcdf84
Hunters422/Basic-Python-Coding-Projects
/python_if.py
290
4.25
4
num1 = 12 key = True if num1 == 12: if key: print('Num1 is equal to Twelve and they have the key!') else: print('Num1 is equal to Twelve and they do no have the key!') elif num1 < 12: print('Num1 is less than Twelve!') else: print('Num1 is not eqaul to Twelve!')
true
f1b18f3fc959db741f9d42643a149d175dd1f162
zeejaykay/Python_BootCamp
/calculator.py
1,753
4.34375
4
# using while loop to continuously run the calculator till the user wants to exit while(True): print("\n Zaeem\'s Basic Calculator\n") print("Please enter two numbers on which you wish to perform calculation's and the operand\n") # displaying instructions num_1 = input("Please enter the 1st number:\n") # taking input from user # error checking for invalid number entry try: num_1 = int (num_1) except: print("Invalid number entered") continue num_2 = input("please enter the 2nd number: \n") try: num_2 = int (num_2) except: print("Invalid number entered") continue operator = input("Please enter the operator: \n") if operator != '+' and operator != '*' and operator != '-' and operator != '/': # error checking for invalid entry in operator print("Invalid operator") continue # Calculating for each operation and displaying only the operation requested by the user if operator == "+": result = num_1 + num_2 print("your calculation result is:", result, "\n") elif operator == "-": result = num_1 - num_2 print("your calculation result is: %d \n" % result) elif operator == "*": result = num_1 * num_2 print("your calculation result is: %d \n" % result) elif operator == "/": result = num_1 / num_2 print("your calculation result is %d \n" %(result)) # Asking user whether he wants to continue using calculator con=input("if you wish to continue press Y, or press N to end program:\n") if con == 'Y': continue # returns to top of loop starts calculating again else: break # Ending the program print("\n end of program")
true
88e69cba39a474480bfb14b421a2e600392199b9
TrendingTechnology/rnpfind
/website/scripts/picklify.py
1,863
4.25
4
""" Picklify is a function that works similar to memoization; it is meant for functions that return a dictionary. Often, such functions will parse a file to generate a dictionary that maps certain keys to values. To save on such overhead costs, we "picklify" them the first time they are called (save the dictionary in a pickle file), and then simply load the dictionary from the saved pickle files the next time around. """ import pickle def picklify(dict_generator, *args, **kwargs): """ Given a function that returns an object such as a dictionary (only dict fully supported), returns the dictionary generated by the function. The function is only called if it has not been "picklified" (passed as an argument to this function) before. Otherwise, its cached dictionary is returned instead. Thus getting the dicttionary by wrapping this function speeds up the dictionary creation overall. Note that this function should not be called by two different functions with the same name. :param dict_generator: the function which generates a dictionary. :param *args: Any args to pass to the dictionary :param **kwargs: Any keyword args to pass to the dictionary. :returns: dictionary returned by dict_generator(). """ # Danger! Never call picklify with functions that have the same name! pickle_path = ( "./website/output-data/pickles/" + dict_generator.__name__ + ".pickle" ) try: with open(pickle_path, 'rb') as pickle_handle: dict_to_return = pickle.load(pickle_handle) except FileNotFoundError: dict_to_return = dict_generator(*args, **kwargs) with open(pickle_path, 'wb') as pickle_handle: pickle.dump( dict_to_return, pickle_handle, protocol=pickle.HIGHEST_PROTOCOL ) return dict_to_return
true
03ce63b031ca790b622d518b4b8813642fdf46b6
Gafficus/Delta-Fall-Semester-2014
/CST-186-14FA(Intro Game Prog)/N.G.Chapter5/N.G.Project2.py
954
4.53125
5
#Created by: Nathan Gaffney #21-Sep-2014 #Chapter 5 Project 1 #This program tell the user where they would go. directions = {"north" : "Going north leads to the kitchen.", "south" : "GOing south leads to the dining room.", "east" : "Going east leads to the entry.", "west" : "Going west leads to the living room."} whereToGo = raw_input("Enter a direction \'north\', \'south\', \'east\'," + "\'west\',\'exit\'(To quit): ") while whereToGo!= "exit": if whereToGo == "north": print directions.get("north") elif whereToGo == "south": print directions.get("south") elif whereToGo == "west": print directions.get("west") elif whereToGo == "east": print directions.get("east") else: print ("Invalid data.") whereToGo = raw_input("Enter a direction \'north\', \'sout\', \'east\'," + "\'west\',\'exit\'(To quit): ")
true
dc04fb45db7a16bae44deaebf0e4c7729f46c6ca
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 10 Tuples/Code/Lab 10.6 Tuples are Comparable.py
488
4.125
4
__author__ = 'Kevin' # 08/04/2015 # Tuples are Comparable # The comparison operators work with tuples and other sequences. If the first item is equal, Python goes on to the # next element, and so on, until it finds elements that differ. print (0, 1, 2) < (5, 1, 2) # True print (0, 1, 2000000) < (0, 3, 4) # True print ( 'Jones', 'Sally' ) < ('Jones', 'Sam') # True print ( 'Jones', 'Sally') > ('Adams', 'Sam') # True print ( 'Jones', 'Sally') < ('Adams', 'Sam') # False True False
true
3a7ecaea275e0022dc6bb928872e6d9a11360ef7
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.10 Two Iteration Variables.py
844
4.28125
4
__author__ = 'Kevin' # 06/04/2015 # We loop through the key-value pairs in a dictionary using *two* iteration variables. # Each iteration, the first variable is the key and the second variable is the corresponding value for the key. jjj = {'chuck': 1, 'fred': 42, 'jan': 100} for aaa,bbb in jjj.items(): print aaa, bbb # jan 100 # chuck 1 # fred 42 # find the most common word in a text file. # /Users/Kevin/Desktop/Programming for Everybody/Week 8/Data/romeo.txt name = raw_input('Enter file:') handle = open(name) text = handle.read() words = text.split() counts = dict() for word in words: counts[word] = counts.get(word,0) + 1 print counts bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print bigword, bigcount
true
b9516444d75abd0141d923136db6dfe47c7ad99d
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.10 Building a list from scratch.py
448
4.4375
4
__author__ = 'Kevin' # 05/04/2015 # BUILDING A LIST FROM SCRATCH # We can create an empty list and then add elements using the append method stuff = list() print stuff stuff.append("book") print stuff other_stuff = [] print other_stuff other_stuff.append("other book") print other_stuff # The list stays in order and new elements are added at the end of the list stuff.append("more") other_stuff.append("junk") print stuff print other_stuff
true
18a316129cc590ba81d98d033617cd7776154603
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 7 Files/Code/Lab 7.1 Opening a File.py
849
4.125
4
__author__ = 'Kevin' # 24/03/2015 # Opening a File # Before we can read the contents of the file, we must tell Python which file we are going to work with and what we will # be doing with the file # This is done with the open() function # open() returns a 'file handle' - a variable used to perform operations on the file # Similar to 'File -> Open' in a Word Processor # Using open() # handle = open(filename, mode) # returns a handle use to manipulate the file # filename is a string # mode is optional and should be 'r' if we are planning to read the file and 'w' if we are going to write to the file # What is a Handle? fhand = open("/Users/Kevin/Desktop/Programming for Everybody/Week 7/Data/mbox-short.txt", "r") # r is read access print fhand # below will not work test = open("mbox-short.txt", "r") # r is read access print test
true
51ce3c640601771132427ca633d37b66e0d86302
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 3 Conditional/Week 3.3 Try and Except.py
340
4.25
4
# You surround a dangerous section of code with try and except # If the code in the try works - the except is skipped # If the code in the try fails - it jumps to the except section astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print "First",istr astr = '123' try: istr = int(astr) except: istr = -1 print 'Secomd',istr
true
1c323c793a58d3736ccbec00ffbccb447f7ca21c
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.8 Definite Loops and Dictionaries.py
376
4.4375
4
__author__ = 'Kevin' # 06/04/2015 # Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a # dictionary - actually it goes through all of the keys in the dictionary and looks up the values counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} for key in counts: print key, counts[key] # jan 100 # chuck 1 # fred 42
true
44df3f26086799bea3f88ec4e814ee785fba53ef
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.1 Lists Introduction.py
1,057
4.1875
4
__author__ = 'Kevin' # 01/04/2015 # A List is a kind of Collection # - A collection allows us to put many values in a single "variable" # - A collection is nice because we can carry all many values around in one convenient package. friends = ['Joseph', 'Glenn', 'Sally'] carryon = ['socks', 'shirt', 'perfume'] print friends print carryon # WHAT IS NOT A COLLECTION # Generally variables have one value in them, when we put a new value in them the olc one is overwritten # Example x = 2 x = 4 print x # LIST CONSTANTS # List constants are surrounded by square brackets and the elements in the list are separated by commas print [1, 24, 76] print ['red', 'yellow', 'blue'] # A list element can be any Python object - even another list print [1, [5, 6], 7] # A list can be empty print [] # EXAMPLE USING LISTS ALREADY for i in [1,2,3,4,5]: print i print "i dont care" # LISTS AND DEFINITE LOOPS WORK QUITE WELL TOGETHER friends = ["lads", "college", "work"] for friend in friends: print "Great bunch of lads", friend print "well done"
true
151748740604378d807b3bc5fd24e1be09c73350
kevmct90/PythonProjects
/Python-Programming for Everybody/Week 6 Strings/Code/Lab 6.15 Making everythin UPPERCASE.py
350
4.21875
4
__author__ = 'Kevin' # 23/03/2015 # You can make a copy of a string in lower case or upper case. # Often when we are searching for a string using find() - we first convert the string to lower case # so we can search a string regardless of case. greet = 'Hello Bob' nnn = greet.upper() print nnn # HELLO BOB www = greet.lower() print www # hello bob
true
4ff057f5206a6d6509d5de02f88c51b495ae9bda
ScoJoCode/ProjectEuler
/problem19/main.py
881
4.15625
4
import time start = time.time() def isLastDay(day,year,month): if day==31 and (month==1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12): return True if day==30 and (month ==4 or month == 6 or month == 9 or month == 11): return True if month == 2 and day==28: if year%4!=0 or (year%4==0 and year%100==0 and year%400!=0): return True if month == 2 and day==29: return True return False sum = 0 year = 1900 weekday = 2 monthDay = 1 month = 1 while year<2001: if monthDay==1 and weekday==1 and year >1900: sum+=1 #if monthDay>27 if isLastDay(monthDay,year,month): if month==12: month = 1 year+=1 else: month+=1 monthDay=1 else: monthDay+=1 if weekday==7: weekday=1 else: weekday+=1 end = time.time() print sum print 'time elapsed: ' + str(end-start)
true
3d698dbd2f2e42af6f8abdd40e96d43c5bcf409a
LiawKC/CS-Challenges
/GC08.py
627
4.21875
4
weight = float(input("What is your weight")) height = float(input("What is your height in m")) BMI = weight / height**2 print(BMI) if BMI < 18.5: print("Bro head to mcdonalds have a big mac or 2 you're probably anorexic") if BMI < 25 and BMI > 18.5: print("Ok, you're average but don't get fat or we will have an obesity problem and we don't need more of that") if BMI < 30 and BMI > 25: print("Bro chill you're pretty fat lay off the big macs bro get a salad") if BMI > 30: print("BRO HEAD TO THE HOSPITAL! BRO CHILL! CHILL!!! GET A DOCTOR! GET SOME OXYGEN BRO YOU HAVE TYPE 2 DIABETES")
true
ed224eb604a4783850d5dbecb0b25f0c582fcdc8
sgetme/python_turtle
/turtle_star.py
1,104
4.1875
4
# first we need to import modules import turtle from turtle import * from random import randint # Drawing shape # I prefer doing this with a function def main(): # set background color of turtle bgcolor('black') # create a variable called H H = 1 # set speed of turtle speed(0) # I prefer hiding turtle during drawing hideturtle() # NOw I have to use while loop while H < 350: # set up random rgb color to your drawing r = randint(0,255) g = randint(0,255) b = randint(0,255) # set pen color colormode(255) pencolor(r,g,b) # now pen up your turtle penup() forward(H) right(95) # pendown() forward(H) dot() H = H + 1 done() # call main test main() # now run your code using terminal or and other IDE # Look if we change the line style to dot() # Lets is change the turning angle ''' Thank you for watching ! Please subscribe my Channel '''
true
980e284b513a95820bae35101c10120b4dd1e208
MohamedNour95/Py-task1
/problem9.py
240
4.5
4
PI = 3.14 radius = float(input('Please enter the radius of the circle:')) circumference = 2 * PI * radius area = PI * radius * radius print("Circumference Of the Circle = "+ str(circumference)) print("Area Of the Circle = "+ str(area))
true
4ec65a6426dfa1e36d68db08cdeb274fca9840d3
miliart/ITC110
/nth_fibonacci_ch8.py
1,116
4.25
4
# A program to calculate the nth spot in the Fibonacci # Per assignment in the book we start at 1 instead of which is the result of 0 plus 1 # by Gabriela Milillo def main(): n= int(input("Enter a a spot in the Fibonacci sequence: "))#variable n is the user input #per the book Fibonacci sequence starts at 1, otherwise it'll be num1=0 num1=1 #first spot in the seq num2=1 #second spot in the seq #run the loop n times, n is the spot in the Fibonacci sequence for i in range(2,n): #the second spot #print for testing print("num1 = " + str(num1)) print("num2 = " + str(num2)) #assigning the sum of the next spot in the sequence sum = num1 + num2 print("sum = " + str(sum)) #the new num1 now equals num2 in the Fibonacci sequence num1=num2 print() #the new num2 now equals the sum of num1 + num2 in the Fibonacci sequence num2=sum print() #output of what the number in that spot in the Fibonacci sequence is print("the "+ str(n)+"th/nth spot in the seq. is "+ str(num2)) main()
true
10fdb82b732b524a4a9526758e8579e468f9aae0
mdhatmaker/Misc-python
/interview-prep/geeks_for_geeks/bit_magic/rotate_bits.py
1,506
4.40625
4
import sys # https://practice.geeksforgeeks.org/problems/rotate-bits/0 # https://wiki.python.org/moin/BitwiseOperators # Given an integer N and an integer D, you are required to write a program to # rotate the binary representation of the integer N by D digits to the left as well # as right and print the results in decimal values after each of the rotation. # Note: Integer N is stored using 16 bits. i.e. 12 will be stored as 0000.....001100. ############################################################################### # Print integer as binary digits (string) def bits(n): print("{0:b}".format(n)) # Assume 16-bit values when performing rotation def rotate_bits(n, d): mask = (1 << d) - 1 lowbits = n & mask mask = ((1 << (16)) - 1) ^ ((1 << 16-d) - 1) hibits = n & mask hibits = hibits >> (16-d) mask = lowbits << 16-d shift_right = (n >> d) | mask shift_left = (n << d) & 0xFFFF | hibits return (shift_left, shift_right) ############################################################################### if __name__ == "__main__": test_inputs = [] test_inputs.append( (229, 3, (1832, 40988)) ) test_inputs.append( (28, 2, (112, 7)) ) test_inputs.append( (50000, 4, (13580, 3125)) ) """ Run process on sample inputs """ for n, d, results in test_inputs: #arr = [int(s) for s in inputs.split()] print(f'{n}, {d}') rotated = rotate_bits(n, d) print(f"{rotated} expected: {results}\n")
true
9dcbb78a4064439289522558200e106eb204d665
mdhatmaker/Misc-python
/interview-prep/geeks_for_geeks/divide_and_conquer/binary_search.py
1,507
4.1875
4
import sys # https://practice.geeksforgeeks.org/problems/binary-search/1 # Given a sorted array A[](0 based index) and a key "k" you need to complete # the function bin_search to determine the position of the key if the key # is present in the array. If the key is not present then you have to return -1. # The arguments left and right denotes the left most index and right most index # of the array A[]. There are multiple test cases. For each test case, this function # will be called individually. ############################################################################### def binary_search(arr, k, l, r): if l > r: return -1 mid = int((l + r) / 2) if k < arr[mid]: return binary_search(arr, k, l, mid) elif k > arr[mid]: return binary_search(arr, k, mid+1, r) else: #k == arr[mid]: return mid # Function to call the binary search functio with the correct left (l) and right (r) parameters def search_for(arr, k): return binary_search(arr, k, 0, len(arr)-1) ############################################################################### if __name__ == "__main__": test_inputs = [] test_inputs.append( (4, "1 2 3 4 5", 3) ) test_inputs.append( (445, "11 22 33 44 55", -1) ) """ Run process on sample inputs """ for k, inputs, results in test_inputs: arr = [int(s) for s in inputs.split()] print(f'{k}, {arr}') ix = search_for(arr, k) print(f"{ix} expected: {results}\n")
true
52fa21fa353bc13fb7439569009b710fa37b6a46
mdhatmaker/Misc-python
/interview-prep/geeks_for_geeks/tree_and_bst/print_bottom_view.py
2,329
4.34375
4
import sys from BinaryTree import BinaryNode, BinaryTree from StackAndQueue import Stack, Queue # https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1 # Given a binary tree, print the bottom view from left to right. # A node is included in bottom view if it can be seen when we look at the tree from bottom. # # 20 # / \ # 8 22 # / \ \ # 5 3 25 # / \ # 10 14 # # For the above tree, the bottom view is 5 10 3 14 25. # If there are multiple bottom-most nodes for a horizontal distance from root, then # print the later one in level traversal. For example, in the below diagram, 3 and 4 # are both the bottommost nodes at horizontal distance 0, we need to print 4. # # 20 # / \ # 8 22 # / \ / \ # 5 3 4 25 # / \ # 10 14 # # For the above tree the output should be 5 10 4 14 25. ############################################################################### def traverse(node, hd = 0, hd_dict = {}): if not node: return #print(node.data, hd, end=' ') hd_dict[hd] = node traverse(node.left, hd-1, hd_dict) traverse(node.right, hd+1, hd_dict) return [n for n in hd_dict.values()] def print_bottom_view(root_node): if not root_node: return #BinaryTree.print_bt(root_node) hds = traverse(root_node) print(hds) return ############################################################################### if __name__ == "__main__": test_inputs = [] test_inputs.append( ("1 2 R 1 3 L", "3 1 2") ) test_inputs.append( ("10 20 L 10 30 R 20 40 L 20 60 R", "40 20 60 30") ) test_inputs.append( ("20 8 L 20 22 R 8 5 L 8 3 R 3 10 L 3 14 R 22 25 R", "5 10 3 14 25") ) test_inputs.append( ("20 8 L 20 22 R 8 5 L 8 3 R 3 10 L 3 14 R 22 4 L 22 25 R", "5 10 4 14 25") ) """ Run process on sample inputs """ for inputs, results in test_inputs: #arr = [s for s in inputs.split()] print(f'{inputs}') tree = BinaryTree.make_tree(inputs) print_bottom_view(tree) print(f" expected: {results}\n")
true
5c29aa549d09b85456b9ee25e5895d9aefd369dd
pi-bansal/studious-happiness
/DP_Practice/Tabulation/how_sum.py
887
4.125
4
def how_sum(target_sum, numbers): # Expected return is an array of integers that add up to target_sum if target_sum == 0: # Zero using empty array return [] # Init the table with null values sum_table = [None] * (target_sum + 1) # Seed value for 0 sum_table[0] = [] for index in range(target_sum): if sum_table[index] is not None: for num in numbers: result = num + index if result == target_sum: return sum_table[index] + [num] try: sum_table[result] = sum_table[index] + [num] except IndexError: #print('Index out of range') pass return sum_table[target_sum] print(how_sum(7, [3, 5, 4])) print(how_sum(100, [99, 3])) print(how_sum(100, [1, 2, 5, 25]))
true
d25cbf0e3769be7d5e4e4a71d2b4deaebd721052
pi-bansal/studious-happiness
/DP_Practice/memoization/how_sum_basic.py
645
4.125
4
def how_sum(target_sum, numbers): """Function that return a subset of numbers that adds up to the target_sum""" if target_sum == 0: return [] if target_sum < 0: return False for num in numbers: remainder = target_sum - num return_val = how_sum(remainder, numbers) if return_val != False: return_val.append(num) return return_val return False print(how_sum(7,[3,4,5])) print(how_sum(7,[2,4,5])) print(how_sum(300,[7, 14])) # import timeit # print(timeit.timeit('[how_sum(*args) for args in [(7,[3,4,5]),(97,[3,4,5]),(300,[7,14])]]', globals=globals()))
true
3c4a36e49bff8e952264bf32b54f59a734ef7535
vv1nn1/dsp
/python/q8_parsing.py
1,679
4.625
5
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. def read_data(filename): """Returns a list of lists representing the rows of the csv file data. Arguments: filename is the name of a csv file (as a string) Returns: list of lists of strings, where every line is split into a list of values. ex: ['Arsenal', 38, 26, 9, 3, 79, 36, 87] """ with open(filename,'r') as f: data = [row for row in csv.reader(f.read().splitlines())] return data def get_index_with_min_abs_score_difference(goals): """Returns the index of the team with the smallest difference between 'for' and 'against' goals, in terms of absolute value. Arguments: parsed_data is a list of lists of cleaned strings Returns: integer row index """ goals.pop(0) goal = [x[5] for x in goals] allow = [x[6] for x in goals] diff = [abs(float(x)-float(y)) for x,y in zip(goal,allow)] return diff.index(min(diff)) def get_team(index_value, parsed_data): """Returns the team name at a given index. Arguments: index_value is an integer row index parsed_data is the output of `read_data` above Returns: the team name """ teams = [x[0] for x in parsed_data] return teams[index_value]
true
d92f3b6c81eff37101c26324694e872272f8762c
leerobert/python-nltk-intro
/code/process.py
1,022
4.125
4
# Sample code for processing a file containing lines of raw text import nltk raw = open("reviews.txt").read() # read in the entire file as a single raw string tokens = nltk.word_tokenize(raw) # tokenizes the raw string text = nltk.Text(tokens) # generate the text object # Cleaning the text of punctuation import re clean_text = ["".join(re.split("[.,;:!?'`-]", word)) for word in text] # Generating the list of stopwords from nltk.corpus import stopwords stopwords = stopwords.words("english") important_words = [word for word in clean_text if word.lower() not in stopwords] # Adding to the list of stop words our own "black-list" more_stopwords = ["", "nt", "cyberdyne"] for word in stopwords: more_stopwords.append(word) important_words = [word for word in clean_text if word.lower() not in more_stopwords] # Lastly, we can normalize the text by lowercasing all the words lower_important_words = [word.lower() for word in important_words] # Print the list to standard out print lower_important_words
true
e8b0861e65e8dde5a5eeb13f52763988cb0ac317
szhao13/interview_prep
/stack.py
498
4.125
4
class Stack(object): def __init__(self): """Initialize an empty stack""" self.items = [] def push(self, item): """Push new item to stack""" self.items.append(item) def pop(self): """Remove and return last item""" # If the stack is empty, return None # (it would also be reasonable to throw an exception) if not self.items: return None return self.items.pop() def peek(self): """See what the last item is""" if not self.items: return None return self.items[-1]
true
2c5569c99d54e1fa5aa523b6071862f237bc6334
DemondLove/Python-Programming
/CodeFights/28. alphabetShift.py
951
4.3125
4
''' Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". Input/Output [execution time limit] 4 seconds (py3) [input] string inputString A non-empty string consisting of lowercase English characters. Guaranteed constraints: 1 ≤ inputString.length ≤ 1000. [output] string The resulting string after replacing each of its characters. ''' import string def alphabeticShift(inputString): alphabet = [x for x in string.ascii_lowercase] inputString = [x for x in inputString] for i in range(len(inputString)): alpha = alphabet.index(inputString[i]) if alpha == 25: inputString[i] = 'a' else: inputString[i] = alphabet[alpha+1] return ''.join(inputString)
true
fc2a2ca8d11b1c90f35118263132230e1b544ebb
DemondLove/Python-Programming
/CodeFights/42. Bishop and Pawn.py
1,450
4.125
4
''' Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move: Example For bishop = "a1" and pawn = "c3", the output should be bishopAndPawn(bishop, pawn) = true. For bishop = "h1" and pawn = "h3", the output should be bishopAndPawn(bishop, pawn) = false. Input/Output [execution time limit] 4 seconds (py3) [input] string bishop Coordinates of the white bishop in the chess notation. Guaranteed constraints: bishop.length = 2, 'a' ≤ bishop[0] ≤ 'h', 1 ≤ bishop[1] ≤ 8. [input] string pawn Coordinates of the black pawn in the same notation. Guaranteed constraints: pawn.length = 2, 'a' ≤ pawn[0] ≤ 'h', 1 ≤ pawn[1] ≤ 8. [output] boolean true if the bishop can capture the pawn, false otherwise. ''' def bishopAndPawn(bishop, pawn): dictRange = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8} bishopLi, pawnLi = list(bishop), list(pawn) firstValMax = max(dictRange[bishopLi[0]],dictRange[pawnLi[0]]) firstValMin = min(dictRange[bishopLi[0]],dictRange[pawnLi[0]]) secondValMax = max(int(bishopLi[1]),int(pawnLi[1])) secondValMin = min(int(bishopLi[1]),int(pawnLi[1])) return firstValMax-firstValMin == secondValMax-secondValMin
true
08cc42adae9c5077db60e1f49607b7a8c0fb9ddf
jaredscarr/data-structures
/linked_list.py
2,235
4.125
4
# -*- coding: utf-8 -*- class Node(object): """Construct Node object.""" def __init__(self, val): """Initialize node object.""" self.val = val self.next = None class LinkedList(object): """Handle creation of a linked list.""" def __init__(self, iterable=None): """Init linked list object with optioanl itterable.""" self.head = None self.iterable = iterable if iterable is not None: try: for i in iterable: self.insert(i) except TypeError: print('value is not an interable') def insert(self, val): """Insert new node at head of list.""" new_node = Node(val) new_node.next = self.head self.head = new_node def search(self, val): """Search for value and return node.""" current = self.head found = False while current and not found: if current.val == val: found = True return current current = current.next return None def pop(self): """Remove node at head and returns the value.""" current = self.head new_head = current.next self.head = new_head return current.val def remove(self, val): """Remove specific val.""" current = self.head if current.val == val: self.head = current.next else: while current.next.val != val: try: current = current.next except AttributeError: print('That node is not in the list.') current.next = current.next.next def size(self): """Return length of list.""" current = self.head counter = 0 while current is not None: counter += 1 current = current.next return counter def display(self): """Print list as tuple.""" container = [] current = self.head while current is not None: container.append(current.val) current = current.next print(tuple(container)) return tuple(container)
true
e3c870a1069eee7c09d0d2c66f7e1d7a04f8127c
jiangyu718/pythonstudy
/base/integrative.py
509
4.15625
4
listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print(listtwo) def powersum(power, *args): '''Return the sum of each argument raised to specified power.''' total = 0 for i in args: total += pow(i, power) return total exec('print(powersum(2,3,4))') exec('print(powersum(2,10))') eval('2+3*3') #去掉字符串的引号 mylist = ['item'] assert len(mylist) >= 1 mylist.pop() #assert len(mylist) >= 1 i=[] i.append('item') print(i) print(repr(i)) print(2*3)
true
3ceab3ad04a845fcf81f46c24b4b612c7d7e3dc9
booji/Exercism
/python/prime-factors/prime_factors.py
707
4.28125
4
import math def prime_factors(natural_number): factors = [] i = 2 # Find all prime '2' the remainder will be odd. while natural_number%i == 0: natural_number = natural_number // i factors.append(i) # Go up to sqrt(natural_number) as prime*prime cannot be greater then # natural_number. Increment by 2 as no more even number remaining for i in range(3,int(math.sqrt(natural_number))+1,2): while natural_number%i == 0: natural_number = natural_number // i factors.append(i) # add last value which will be prime if greater than 2 if natural_number > 2: factors.append(natural_number) return factors
true
790d11daed36af486c57a4cb4a017798b1a9dcc4
SimonCCooke/CodeWars
/SmallestInteger.py
446
4.1875
4
"""Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this kata, that the supplied array will not be empty.""" def findSmallestInt(arr): answer = arr[0] for i in range(0,len(arr)): if(answer > arr[i]): answer = arr[i] return answer
true
38f7f4defa13ac0cc35d78a54b90d7764f9e6116
kwaper/iti0102-2018
/pr08_testing/shortest_way_back.py
1,586
4.25
4
"""Find the shortest way back in a taxicab geometry.""" def shortest_way_back(path: str) -> str: """ Find the shortest way back in a taxicab geometry. :param path: string of moves, where moves are encoded as follows:. N - north - (1, 0) S - south - (-1, 0) E - east - (0, 1) W - west - (0, -1) (first coordinate indicates steps towards north, second coordinate indicates steps towards east) :return: the shortest way back encoded the same way as :param path:. """ d = {"N": (1, 0), "S": (-1, 0), "E": (0, 1), "W": (0, -1)} pos = (0, 0) back = "" for direct in path: pos = (pos[0] + d[direct][0], pos[1] + d[direct][1]) print(pos) while pos != (0, 0): if pos[0] != 0: while pos[0] > 0: pos = (pos[0] - 1, pos[1]) back += "S" while pos[0] < 0: pos = (pos[0] + 1, pos[1]) back += "N" if pos[1] != 0: while pos[1] > 0: pos = (pos[0], pos[1] - 1) back += "W" while pos[1] < 0: pos = (pos[0], pos[1] + 1) back += "E" return back if __name__ == '__main__': assert shortest_way_back("NNN") == "SSS" assert shortest_way_back("SS") == "NN" assert shortest_way_back("E") == "W" assert shortest_way_back("WWWW") == "EEEE" assert shortest_way_back("") == "" assert shortest_way_back("NESW") == "" assert shortest_way_back("NNEESEW") in ["SWW", "WSW", "WWS"]
true
17f70272ddf81483bcf5b5c36377659a43174a8d
amiraHag/Python-Basic
/basic datatypes/variables.py
584
4.4375
4
#print any text using print function print("Hello World!") """store value in variables""" x=5 y=6 z= x+y print(z) """ know the type of the variable by using type()""" print(type(z)) #make operations on numbers x= 3+4*5 print(x) # arithmatic operators four basic - + * / # ** power ()parenthesis- use to identify which operation will applied first x= (3 +4)*5 print(x) # the order of the arithmatic operators () , ** , * / , + - , if in the same level it will do left to write x = 4 / (2*1) -1 *5 +6 # x= 4/2 -1*5 +6 #x=2 -5 +6 = 3 print(x) x = ((3+5) *2) **2/16 -1 print(x)
true
d2fd5afd38c0191cdc657af4e99e62da817b7f0f
theshevon/A2-COMP30024
/adam/decision_engine.py
2,458
4.1875
4
from math import sqrt from random import randint class DecisionEngine(): """ Represents the agents 'brain' and so, decides which node to move to next. """ EXIT = (999, 999) colour = None exit_nodes = None open_node_combs = None init_node_comb = None closed_node_combs = None open_node_combs_queue = None states = None def __init__(self, colour, board): self.colour = colour self.exit_nodes = board.get_exit_nodes(colour) print("EXITS:", self.exit_nodes) def get_next_move(self, board): """ Returns a random move out of the list of valid moves. """ nodes = board.get_piece_nodes(self.colour) # generate all possible moves possible_successors = self.get_all_possible_moves(board, nodes) # no moves possible if len(possible_successors) == 0: return ("PASS", None) # pick a random move action = possible_successors[randint(0, len(possible_successors) - 1)] if action[1] == self.EXIT: return ("EXIT", action[0]) else: if board.get_dist(action[0], action[1]) <= sqrt(2): return ("MOVE", action) return ("JUMP", action) def get_all_possible_moves(self, board, nodes): """ Returns a list of all the possible nodes that can be moved to. An exit is denoted by (999, 999). """ possible_moves = [] occupied_nodes = board.get_all_piece_nodes() for node in nodes: # check if an exit is one of the possible moves if node in self.exit_nodes: possible_moves.append((node, self.EXIT)) # add neighbouring nodes to list for neighbouring_node in board.get_neighbouring_nodes(node): # if neighbouring node is occupied, look for landing spots if neighbouring_node in occupied_nodes: landing_node = board.get_landing_node(node, neighbouring_node, occupied_nodes) if (landing_node): possible_moves.append((node, landing_node)) else: possible_moves.append((node, neighbouring_node)) return possible_moves
true
8273da9ef7fb33ab57d238d677465cebd66a07b0
narokiasamy/internship1
/06-20-19/temperatureConverter.py
548
4.25
4
# temperature must be typed with corresponding temperature scale unit! (ex: 32F or 68C) temperature = str(input("temperature reading: ")) # temperature conversions if "C" in temperature: removeLetter = int(temperature.rstrip("C")) fahrenheitCalculation = (int((removeLetter * 1.8) + 32)) print (str(fahrenheitCalculation) + "F") print (temperature) elif "F" in temperature: removeLetter = int(temperature.rstrip("F")) celsiusCalculation = (int((removeLetter - 32) / 1.8)) print (str(celsiusCalculation) + "C") print (temperature)
true
260ebcd387e66bf0a17576468d5e6e1c3b6cee61
manerain/savy
/proj02/proj02_02.py
598
4.4375
4
# Name: # Date: # proj02_02: Fibonaci Sequence """ Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13...""" counter = 0 counter3 = 0 cntr2 = 1 fib = raw_input('How many fibonacci numbers do you want to generate:') fib = int(fib) while counter < fib: seq = counter3 + cntr2 seq = int(seq) print cntr2 counter3 = cntr2 cntr2 = seq counter = counter + 1
true
756807939ce427d376446b51d12d229acc3099cc
rajunrosco/PythonExperiments
/CollectionFunctions/CollectionFunctions.py
2,174
4.125
4
import os import sys from functools import reduce def FilterTest(): keylist = ["a","a|ps4","b","b|ps4","b|win64","c","c|win64"] # filter list with lambda function that returns all strings that contain "ps4" # filter() takes a function evaluates to "true", items that you want in the list # in the case below, the function is a lambda that takes and argument 'x' and returns # true if "ps4" is found in 'x'. # so, the below filter takes keylist and returns all items that are true for the lambda function myfilter = filter(lambda x : x.find("ps4")>=0, keylist) print(myfilter) # since the above returns a filter object instead of a list, make a list out of filterlist = list(filter(lambda x : x.find("ps4")>=0, keylist)) # another way to write the lambda this time looking for "win64" filterlist = list(filter(lambda y : "win64" in y, keylist)) print(filterlist) # map applies the function in the first argument to all items in the collection of the second argument. # the below lambda function takes an argument and returns the first item in a list after splitting on '|' # else it returns None keybaselist = list( map(lambda x: x.split('|')[0] if len(x.split('|'))==2 else None, keylist )) # now the list is littered with None types so filter them out keybaselist = list(filter(lambda x : x is not None, keybaselist)) # reduces a list by taking a 2 parameter function an then applying it to the list over each element # think first pair as ([0],[1]) and the second pair as ( (0,1) and (2) ) .... concatlist = reduce(lambda x,y : x +','+ y, keylist) # the lambda below has to check if the current item is a str to get len(str) or if it has already been # converted and return the number to be added to the next number. countallchars = reduce( lambda x,y : len(x) if type(x) is str else x + len(y) if type(y) is str else y, keylist) stop = 1 def Main(argv): FilterTest() # If module is executed by name using python.exe, enter script through Main() method. If it is imported as a module, Main() is never executed at it is used as a library if __name__ == "__main__": Main(sys.argv)
true
f2a5dc0eb57b10d0ccc0acc17c6b5bf3b060c585
anuragdogra2192/Data_structures_with_python3
/arrays/TwoSumII_unique_pairs.py
1,839
4.21875
4
''' Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first < second <= numbers.length. Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. Constraints: 2 <= numbers.length <= 3 * 104 -1000 <= numbers[i] <= 1000 numbers is sorted in non-decreasing order. -1000 <= target <= 1000 The tests are generated such that there is exactly one solution. ''' class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ index1 = 0; index2 = len(numbers)-1; while index1 < index2: if numbers[index1] + numbers[index2] > target: index2-=1 elif numbers[index1] + numbers[index2] < target: index1+=1 else: return [index1+1, index2+1] Sol = Solution(); L = [2,7,11,15] T = 9 print(Sol.twoSum(L, T)) L1 = [2,3,4] T1 = 6 print(Sol.twoSum(L1, T1)) L2 = [-1,0] T2 = -1 print(Sol.twoSum(L2, T2))
true
c529568c0c22bc9cbee2c64265c8c32147c310e8
anuragdogra2192/Data_structures_with_python3
/arrays/ReturnAnArrayOfPrimes/Return_array_of_primes.py
870
4.34375
4
""" Write a program that takes an integer argument and returns all the primes between 1 and that integer. For example, if the input is 18, you should return [2, 3, 5, 7, 11, 13, 17] Hint: Exclude the multiples of primes. """ #Given n, return all primes up to and including n. def generate_primes(n): primes = [] # is_prime[p] represents if p is prime or not. # Initially, set each to 'true', expecting 0 and 1. Then use sieving to eliminate nonprimes. is_prime = [False, False] + [True] * (n-1) for p in range(2, n+1): if is_prime[p]: primes.append(p) # Sieve p's multiples. for i in range(p * 2, n + 1, p): is_prime[i] = False return primes print("Input the integer: ") n = int(input()) print("The array of primes: ", generate_primes(n)) #O(nloglogn)
true
20099604968983eb02c4ec2b0f9c67600afcf002
anuragdogra2192/Data_structures_with_python3
/strings/integer_to_string.py
899
4.28125
4
""" Integer to string Built-in functions used in the code 1) ord() The ord() function returns an integer representing the Unicode character. ord('0') - 48 ord('1') - 49 : : ord('9') - 57 2) chr() Python chr() function takes integer argument and return the string representing a character at that code point. chr(48) - '0' chr(49) - '1' : : chr(57) - '9' """ def int_to_string(x): is_negative = False if x < 0: x, is_negative = -x, True s = [] while True: s.append(chr(ord('0') + x % 10)) x //= 10 if x == 0: break # Adds the negative sign back if is_negative return('-' if is_negative else '') + ''.join(reversed(s)) x = int(input("Enter the integer number to convert to string: ")) s = int_to_string(x) print("The string after the conversion: ", s, "and its type: ", type(s))
true
66ca2398e71e7faf0042e69596658d19d25a9409
anuragdogra2192/Data_structures_with_python3
/LargeAssociationItems.py
2,558
4.28125
4
""" My approach: DFS Question: In order to improve customer experience, Amazon has developed a system to provide recommendations to the customer regarding the item they can purchase. Based on historical customer purchase information, an item association can be defined as - If an item A is ordered by a customer, then item B is also likely to be ordered by the same customer (e.g. Book 1 is frequently orderered with Book 2). All items that are linked together by an item association can be considered to be in the same group. An item without any association to any other item can be considered to be in its own item association group of size 1. Given a list of item association relationships(i.e. group of items likely to be ordered together), write an algorithm that outputs the largest item association group. If two groups have the same number of items then select the group which contains the item that appears first in lexicographic order. Input The itput to the function/method consists of an argument - itemAssociation, a list containing paris of string representing the items that are ordered together. Output Return a list of strings representing the largest association group sorted lexicographically. Example Input: itemAssociation: [ [Item1, Item2], [Item3, Item4], [Item4, Item5] ] Output: [Item3, Item4, Item5] Explanation: There are two item association groups: group1: [Item1, Item2] group2: [Item3,Item4,Item5] In the available associations, group2 has the largest association. So, the output is [Item3, Item4, Item5]. """ L = [["Item1", "Item2"],["Item3", "Item4"],["Item4", "Item5"]] itemDict = {} for i in range(len(L)): if L[i][0] in itemDict: itemDict[L[i][0]].append(L[i][1]) if L[i][1] not in itemDict: itemDict[L[i][1]] = [] else: itemDict[L[i][0]] = [L[i][1]] itemDict[L[i][1]] = [] print(itemDict) def dfs(visited, graph, node): if node not in visited: #print(node) visited.add(node) for neighbour in graph[node]: dfs(visited, graph, neighbour) LargestItemAssociation = [] for i in itemDict: visited = set() #print(i) dfs(visited, itemDict, i) visited = sorted(visited) #print(type(visited)) if len(LargestItemAssociation) < len(visited): LargestItemAssociation = visited elif(len(LargestItemAssociation) == len(visited)): if(LargestItemAssociation[0] < visited[0]): LargestItemAssociation = visited #print(visited) print(LargestItemAssociation)
true
1bb0230e9ca9ae6404d40e7fd5a6091f4cbdb503
600rrchris/Python-control-flow-lab
/exercise-2.py
490
4.3125
4
# exercise-02 Length of Phrase # Write the code that: # 1. Prompts the user to enter a phrase: # Please enter a word or phrase: # 2. Print the following message: # - What you entered is xx characters long # 3. Return to step 1, unless the word 'quit' was entered. word = input('Enter "Please enter a word or phrase"') error = ('quit') x = len(word) if word in error: input('Enter "Please enter a word or phrase"') else: print(f'What you entered is {x} characters long')
true
525fa36066c159ccd4a5f921f006ad71dbc47777
saurav-singh/CS260-DataStructures
/Assignment 3/floyd.py
1,718
4.375
4
#!usr/bin/env python # # Group project: Floyd's algorithm # Date: 03/13/2019 # # It should be noted that this implementation follows the one in the textbook """{Shortest Paths Program: shortest takes an nXn matric C of arc costs and produces nXn matrix A of lengths of shortst paths and an nXn matrix P giving a point in the "middle" of each shortest path}""" def shortest(A,C,P): n = len(A) for i in range(n): for j in range(n): A[i][j] = C[i][j] P[i][j] = 0 for i in range(n): A[i][i] = 0 for k in range(n): for i in range(n): for j in range(n): if (A[i][k] + A[k][j]) < A[i][j]: A[i][j] = A[i][k] + A[k][j] P[i][j] = k #Procedure to print shortest path. def path(i,j,P): k = P[i][j] if k == 0: return path(i,k,P) print(k) path(k,j,P) #Problem 6 of review 2 test = float("inf") n = 6 C = [[test for x in range(n)] for x in range(n)] #It should be noted that compared to the review problem, the index for #everything starts at 0 C[0][1] = 4 C[0][2] = 1 C[0][3] = 5 C[0][4] = 8 C[0][5] = 10 C[2][1] = 2 C[3][4] = 2 C[4][5] = 1 A = [[test for x in range(n)] for x in range(n)] P = [[test for x in range(n)] for x in range(n)] print("\n") print("Initial Matrix C:") for node in C: print(node) shortest(A,C,P) print("\n") print("Matrix P:") for node in P: print(node) print("\n") print("Matrix A:") for node in A: print(node) print("\n") print("Resulting shortest Paths:") print("0->1") path(0,1,P) print("\n") print("0->2") path(0,2,P) print("\n") print("0->3") path(0,3,P) print("\n") print("0->4") path(0,4,P) print("\n") print("0->5") path(0,5,P)
true
0725be1066a074d73d764b67b8fe589b41b33cd7
rosewambui/NBO-Bootcamp16
/fizzbuzz.py
278
4.1875
4
"""function that checks the divisibility of 3, 5 or both""" """a number divisible by both 3 and 5 id a divisor 15, divisibility rule""" def fizz_buzz(num): if num%15==0: return "FizzBuzz" elif num%5==0: return "Buzz" elif (num%3==0): return "Fizz" else: return num
true
6b596be7dbe7be8359e78e6bec3dba581d1762c7
mhorist/FunctionPractice
/FunkyPractice06.py
246
4.3125
4
# Write a Python program to reverse a string. def strRevers(charString): rstr = '' index = len(charString) while index > 0: rstr += charString[index - 1] index = index - 1 print(rstr) strRevers("abc def ghi jkl")
true
2db7e00677625efb1119dab3fd48a6de2c3d1567
eflagg/dictionary-restaurant-ratings
/restaurant-ratings.py
1,861
4.40625
4
# your code goes here import random def alphabetize(filename): """Alphabetizes list of restaurants and ratings Takes text file and turns it into dictionary in order to print restaurant_name with its rating in alphabetical order """ username = raw_input("Hi, what's your name? ") print "Hi %s!" % (username) open_file = open(filename) restaurants = {} # loops through textfile, strips any hanging spaces, splits into a list based on ':' # Inserts restaurant name and rating into the dictionary for line in open_file: line = line.rstrip() line_as_list = line.split(":") restaurants[line_as_list[0]] = line_as_list[1] #Generates a random restaurant, asks user for rating and changes rating within the #dictionary. Does this until user types 'q' or 'Q' while True: random_restaurant_key = random.choice(restaurants.keys()) print "Let's look at a sample restaurant!" print random_restaurant_key + ": " + restaurants[random_restaurant_key] new_rating = raw_input("What should the new rating be? ") if new_rating in ['q','Q']: break else: restaurants[random_restaurant_key] = new_rating print "Success! You successfully changed the restaurant rating!" #Asks user to input another restaurant with a rating and adds to dictionary new_restaurant = raw_input("Another restaurant name? ") new_score = int(raw_input("Restaurant's rating? ")) restaurants[new_restaurant] = new_score # loops through the dictionary and sorts it based on restaurant_name and prints out # restaurant name and rating as a string for restaurant_name, rating in sorted(restaurants.iteritems()): print "%s is rated at %s." % (restaurant_name, rating) alphabetize('scores.txt')
true
8629533b3301fd37e7cd41c4cfaecbf9677efe92
boxa72/Code_In_Place
/khansoleAcademy.py
1,414
4.25
4
""" Prints out a randomly generated addition problem and checks if the user answers correctly. """ import random MIN_RANDOM = 10 # smallest random number to be generated MAX_RANDOM = 99 # largest random number to be generated THREE_CORRECT = 3 # constant for the loop def main(): math_test() def math_test(): """ function that holds the whole game """ num_correct = 0 while num_correct != THREE_CORRECT: num1 = random.randint(MIN_RANDOM, MAX_RANDOM) num2 = random.randint(MIN_RANDOM, MAX_RANDOM) print("What is " + str(num1) + ' + ' + str(num2) + '? ') user_input = int(input()) print("Your answer: " + str(user_input)) correct_answer = num1 + num2 if user_input == correct_answer: num_correct += 1 if num_correct == 1: print("Correct! You've gotten " + str(num_correct) + " correct in a row.") elif num_correct == 2: print("Correct! You've gotten " + str(num_correct) + " correct in a row.") elif num_correct == 3: print("Correct! You've gotten " + str(num_correct) + " correct in a row.") print("Congratulations! You mastered addition.") else: print("Incorrect. The expected answer is " + str(correct_answer)) num_correct = 0 if __name__ == '__main__': main()
true
30c32e1a5cd8c9468a7d3583f77524de86885683
JessicaGarson/Deduplicate_playtime
/dedupe.py
1,373
4.40625
4
# Challenge level: Beginner # Scenario: You have two files containing a list of email addresses of people who attended your events. # File 1: People who attended your Film Screening event # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt # # File 2: People who attended your Happy hour # https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt # Goal 1: You want to get a de-duplicated list of all of the people who have come to your events. #creating the function def deduplicate(list1, list2): return list(set(list1+list2)) #open up the files with open("film_screening_attendees.txt", "r") as film_people: film = film_people.read().split('\n') with open("happy_hour_attendees.txt", "r") as happy_hour_people: happy_hour = happy_hour_people.read().split('\n') #who attended print "Peeps who attended one of the events:" #print the people who attend stuff for person in deduplicate(film, happy_hour): print person print "\n" # Goal 2: Who came to *both* your Film Screening and your Happy hour? #instead of + I can use & to get both def intersect(list1, list2): return list(set(list1) & set(list2)) print "Peeps who attended both:" for person in intersect(film, happy_hour): print person print "\n"
true
3634e3d694a98a2dd178c9f431874a53ffe8cc20
0xlich/python-cracking-codes-examples
/caesar.py
1,178
4.25
4
# Caesar Cypher import pyperclip #The string to be encrypted #print ('Please enter the message: ') #message = input() message = 'fVDaOPZDPZDHTHgPUNDKVVN' # The encryption key key = 7 #Wheter the program encrypts or decrypts: mode = 'decrypt' # Set to either 'encrypt' or 'decrypt' #Every possible symbol SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' #Store the encrypted message translated = '' for symbol in message: if symbol in SYMBOLS: symbolIndex = SYMBOLS.find(symbol) #Perform encryption/decryption of message if mode == 'encrypt': translatedIndex = symbolIndex + key elif mode == 'decrypt': translatedIndex = symbolIndex - key #Handle wraparound if translatedIndex >= len(SYMBOLS): translatedIndex -= len(SYMBOLS) elif translatedIndex < 0: translatedIndex += len(SYMBOLS) translated = translated + SYMBOLS[translatedIndex] else: # Append the symbol without encrypting/decrypting translated = translated + symbol #Output the translated string: print(translated) pyperclip.copy(translated)
true
d566fbf02375e2a53983be614c73f58cfec61951
gitbrian/lpthw
/ex15.py
569
4.21875
4
#imports the argv module from sys import argv #assigns variables to the arguments in argv # script, filename = argv # print "The script running this is named %r." % script #assigns the open file to the variable 'txt' # txt = open(filename) # prints the filename of the text file # print "Here's your file %r:" % filename # prints the contents of the file # print txt.read() print "Type the filename again:" #gets the file info from the user this time while the program is running file_again = raw_input("> ") txt_again = open(file_again) print txt_again.close()
true
53fe312095c05dc9d24e255d4062b24862c2e27c
ejudd72/beginner-python
/notes/numbers.py
807
4.1875
4
from math import * print(2) # parenthesis for order of operation print(3 * (4 + 5)) # division print(3/1) # modulus operator print(10 % 3) # numbers inside variables my_num = 5 print(20 % my_num) # convert number to string (you need to do this to concatenate strings and numbers) my_num = 6 print("I have " + str(my_num) + " dogs") # common python number functions # absolute value my_neg_num = -32 print(abs(my_neg_num)) # powers, with first param number, second param is the power of print(pow(3, 2)) # print larger of two numbers print(max(my_num, my_neg_num)) # round a number print(round(4.55)) # using math functions, you need to import them e.g. in line 1 # rounds to lower integer print(floor(4.3)) # round to higher integer print(ceil(4.3)) # gives square root print(floor(sqrt(36)))
true
88acce823bf11faaf330eccb89f8a8e0f66fbbfa
Areeba-Seher04/Python-OOP
/2 INHERITANCE/2 Inheritance.py
1,036
4.28125
4
#class Person(object): class Person: #Parent class def __init__(self,name,age): self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age class Employee(Person): #Child class ''' **Child class of Person Class **can access all functions and variables of Parent class ''' pass def main(): Person_object=Person("Areeba",100) print("My name is {} and I am {} years old".format(Person_object.get_name(),Person_object.get_age())) Employee_object=Employee("Employee",200) #can access all functions and variables of Parent Class print("My name is {} and I am {} years old".format(Employee_object.get_name(),Employee_object.get_age())) print(issubclass(Employee,Person)) #is Employee ,the subclass (child) of person? print(issubclass(Employee,object)) #every class in python is the subclass of object print(issubclass(Employee,object)) main()
true
ec1451e3c75e5c1726a49298cc43beaee0ab23a8
Areeba-Seher04/Python-OOP
/3 FUNCTIONS arg,kwarg/3.arg in function call.py
421
4.28125
4
#ARG IN FUNCTION CALL #We can also use *args and **kwargs to pass arguments into functions. def some_args(arg_1, arg_2, arg_3): print("arg_1:", arg_1) print("arg_2:", arg_2) print("arg_3:", arg_3) args = ("Sammy", "Casey", "Alex") #args is a tuple some_args(*args) #pass all arguments in a function args = ("sara","yusra") some_args("Areeba",*args) args = [1,2] #we can also pass list some_args(3,*args)
true
f495dd4e59b615d52f4ecc260c5075466f2c1f8a
UrduVA/Learn-Python
/while_Infi.py
206
4.1875
4
x = 0 while x != 5: print(x) x = int(input("Enter a value or 5 to quit: ")) ##0 ##Enter a value or 5 to quit: 1 ##1 ##Enter a value or 5 to quit: 2 ##2 ##Enter a value or 5 to quit: 5
true
8d6bcffee5cdace0ddc5e79be117999ad094c349
hanchettbm/Pythonprograms
/Lab12 updated.py
2,590
4.4375
4
# 1. Name: # -Baden Hanchett- # 2. Assignment Name: # Lab 12: Prime Numbers # 3. Assignment Description: # -This program will display all the prime numbers at # or below a value given by the user. It will prompt the # user for an integer. If the integer is less than 2, # then the program will prompt the user again. # The program will then compute all the prime numbers below # (and including) the given number. When finished, the program # will display the list of prime numbers.- # 4. What was the hardest part? Be as specific as possible. # -This assignment was the most difficult for me, I had the most # troubble understanding the solution that crosssed out values with # another array of true false values. I had a sloution that worked, # but I had to reformat it to work with the lab design. The harderst # part of that was the multiple loop. I had to spend some time understanding # the range, that mutiple had to start at factor * 2 and then increase by # factor. Once I understood the range needed I was able to use it to set # the true false values correctly.- # 5. How long did it take for you to complete the assignment? # -total time in hours including reading the assignment and submitting the program was 4 Hours.- import math # Set variables and prompt user for a number, that's greater than 1. number = 0 while number < 2: number = int(input ("This program will find all the prime numbers at or below N. Select that N: ")) assert(number > 1) # Make sure code above worked and number is greater than 1. primes = [] # Fill numbers array with True values up to number. numbers = [True for index in range(number + 1 )] numbers[0] = False numbers[1] = False assert(len(numbers) == number + 1) # Check length of the array, make sure it's full. # Check each value up until the square root of the number # because nothing above that will be prime. for factor in range(2, int(math.sqrt(number)) + 1): if numbers[factor]: # Rule out every mutiple of the factor becuase mutiples are never prime. for multiple in range((factor * 2), (number + 1), factor): numbers[multiple] = False multiple = (factor * 2) assert(type(multiple) == int) # Check multpiple type. # Use the numbers array to add values to primes array. for index in range(2, (number + 1)): if numbers[index]: primes.append(index) print("The prime numbers at or below", number, "are", primes)
true
20290067dda6e0cc8d3d4661ecaaa73428186d19
guozhaoxin/mygame
/common/common.py
2,043
4.21875
4
#encoding:utf8 __author__ = 'gold' # import win32api,win32con import tkinter as tk from tkinter import filedialog,messagebox import pygame import sys def chooseFile(): ''' this method is used to let the player choose a file to continue a saved game :return: str,represent a file's absolute path the player chooses,else None ''' root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() if file_path != '': return file_path return def exitGame(): ''' when the game is closed,execute pygame.quit and sys.exit :return: ''' pygame.quit() sys.exit() def chooseExit(): return messagebox.askyesno('exit the game','exit?') def saveGame(data,method): ''' let the player decide if save the game or not. :param data: the game current data to save :param method: a function object to indicate how to save the game. :return: None ''' choice = messagebox.askyesno('save the game','save?') if choice: method(data) messagebox.Message(title = "save",message = "save success").show() def importGameData(readMethod): ''' let the player decide if import a saved game's data or not :param readMethod: a function object,used to indicate how to load a saved game data,the function accept on parameter to indicate the data's path. :return: data,the saved game data. ''' data = None while True: choice = messagebox.askyesno('choose','choose an old game?') if choice: file = chooseFile() if not file: messagebox.showerror('error','file error!') continue data = readMethod(file) if not data: messagebox.showerror('error','file error!') else: break else: break return data def init(): ''' this method is used to execute some initial for every game at the beginning. :return: ''' pygame.init() tk.Tk().withdraw()
true
c856254295dfe0dfe2e8cd40554bf127a8dfef32
UAL-AED/lab5
/aed_ds/queues/adt_queue.py
745
4.375
4
from abc import ABC, abstractmethod class Queue(ABC): @abstractmethod def is_empty(self) -> bool: ''' Returns true iff the queue contains no elements. ''' @abstractmethod def is_full(self) -> bool: ''' Returns true iff the queue cannot contain more elements. ''' @abstractmethod def size(self) -> int: ''' Returns the number of elements in the queue.''' @abstractmethod def enqueue(self, element: object) -> None: ''' Inserts the specified element at the rear of the queue. Throws FullQueueException ''' @abstractmethod def dequeue(self) -> object: ''' Removes and returns the element at the front of the queue. Throws EmptyQueueException '''
true
6f26cbdbc4352a6a01f735f41ede7dcd3cf847e8
lewie14/lists_sorting
/lists2.py
2,684
4.28125
4
list1 = range(2, 20, 2) #Find length of list1 list1_len = len(list1) print(list1_len) #Change the list range so it skips 3 instead of 2 numbers list1 = range(2, 20, 3) #Find length of list1 list1_len = len(list1) print(list1_len) print() #------------------------------------------------------ #indexes employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert'] index4 = employees[4] print(len(employees)) #print(employees[8]) --------------- Makes an error coz out of range print(employees[4]) print() #------------------------------------------------------ #Last element selection shopping_list = ['eggs', 'butter', 'milk', 'cucumbers', 'juice', 'cereal'] print(len(shopping_list)) last_element = shopping_list[-1] element5 = shopping_list[5] print(element5) print(last_element) print() #------------------------------------------------------ #Slicing lists suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books'] #print firt 4 items beginning = suitcase[0:4] print(beginning) #select middle 2 items middle = suitcase[2:4] suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books'] #Select first 3 items start = suitcase[:3] #Select last 2 items end = suitcase[-2:] print() #------------------------------------------------------ #Counting elements in a list #Mrs. Wilson's class is voting for class president. She has saved each student's vote into the list votes. #Use count to determine how many students voted for 'Jake'. Save your answer as jake_votes. votes = ['Jake', 'Jake', 'Laurie', 'Laurie', 'Laurie', 'Jake', 'Jake', 'Jake', 'Laurie', 'Cassie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie'] jake_votes = votes.count('Jake') print(jake_votes) print() #------------------------------------------------------ #Sorting elements in a list ### Exercise 1 & 2 ### addresses = ['221 B Baker St.', '42 Wallaby Way', '12 Grimmauld Place', '742 Evergreen Terrace', '1600 Pennsylvania Ave', '10 Downing St.'] # Sort addresses here: addresses.sort() print(addresses) ### Exercise 3 ### names = ['Ron', 'Hermione', 'Harry', 'Albus', 'Sirius'] names.sort() ### Exercise 4 ### cities = ['London', 'Paris', 'Rome', 'Los Angeles', 'New York'] #The print doesnt work because the sort does not return a sorted list to a variable sorted_cities = cities.sort() print(sorted_cities) print() games = ['Portal', 'Minecraft', 'Pacman', 'Tetris', 'The Sims', 'Pokemon'] #Use sorted to order games and create a new list called games_sorted games_sorted = sorted(games) #Use print to inspect games and games_sorted print(games) print(games_sorted) #------------------------------ #All together
true
5feadeba85d180dca1c7a7f0445a32692dc3b9c6
MichaelrMentele/LearnPythonTheHardWay
/ex18.py
566
4.25
4
def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) def print_one(arg1): print "arg1: %r" % arg1 def print_none(): print "I got nothin'." print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none() #Ok so if we use the *args array notation is there a limited or finite amount of args that can happen here. #So if we use the form variable = [args] for unpacking purposes we can have an unspecified amount of variables.
true
2d0c41f4f1e73659d39f318038f6bf7344d66112
durgeshiv/py-basic-scripting-learning
/com/durgesh/software/slicing.py
768
4.21875
4
x='LetsSliceThisString' # we have defined a string as above, lets try to slice it and print 'ThisString' # [] -> is the syntax for slicing # slicedString = x[9:] # Here, this starts at index 9 and : means we haven't specified end # index thus everything until end would be taken print(slicedString) # give o/p as 'ThisString # Lets try end index also print(x[9:13]) # There is a provision for step size also within slice # Lets try to print alternate alphabet from above string print(x[::2]) ## first two index-values, I have assumed to be empty which mean to start from 0 and finish at end and 2 denotes step size ############# Important ::: step can have negative value also but then; #it will start from end, and will take step size as defined print(x[::-1])
true
a3bd72a4f86653946331505e4b8157675cc3e153
irskep/mrjob_course
/solutions/wfc_job.py
1,293
4.125
4
""" Write a job that calculates the number of occurrences of individual words in the input text. The job should output one key/value pair per word where the key is the word and the value is the number of occurrences. """ from collections import Counter, defaultdict from mrjob.job import MRJob class MRWordFrequencyCountJob(MRJob): def steps(self): return [self.mr(mapper_init=self.mapper_init, mapper=self.mapper, mapper_final=self.mapper_final, combiner=self.sum_words, reducer=self.sum_words)] def mapper_init(self): #self.words = {} #self.words = defaultdict(0) #self.words = defaultdict(lambda: 0) self.words = Counter() def mapper(self, _, line): for word in line.split(): if word.strip(): #self.words.setdefault(word, 0) #if word not in words: # words[word] = 0 #self.words[word] = self.words.get(word, 0) + 1 self.words[word] += 1 def mapper_final(self): for word, count in self.words.iteritems(): yield word, count def sum_words(self, key, values): yield key, sum(values) if __name__ == '__main__': MRWordFrequencyCountJob.run()
true
98815d02b2b32a065ef7daf466ee5e503e4aed62
meghasn/py4_everyone_solution
/question9.py
255
4.34375
4
#using a while loop read from last character of a string and print backwards word=input("enter the string:") index=len(word)-1 while index>=0: a=word[index] print(a) index=index-1 #enter the string:banana #a #n #a #n #a #b
true
8020336c54f223edc92891c3689c880483e6085f
wingateep/Sprint-Challenge--Algorithms
/recursive_count_th/count_th.py
894
4.28125
4
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): # TBC #base case count = 0 # sets count to 0 to start th_occurences = "th" # setting up to find the occurences of "th" indx = word.find(th_occurences) #set up index to find the "th" occurances #if "th" is found set to 0 and increase count if indx >=0: count +=1 # increase count by 1 word = word[indx + len(th_occurences):] #changes word to next given/not including first case count += count_th(word) # recursively starts func until word is finished # and no more "th" is found return count #return count #pass
true
9cc9fa08a66e0d79b46790ed5232c66f934933f0
rachelmccormack/PythonRevision-Tutoring
/Homework/Solutions/furtherFileReading.py
875
4.15625
4
""" A list of words is given in a file words.txt For this file, please give the number of times each word appears, in the form {word:number} Please display the longest word How many words are in the list? (Don't peek) What percentage of the words are unique? """ file = open("words.txt") words = file.readlines() file.close() longestWordLength = 0 longestWord = "" wordFrequency = {} for i in words: i = i.replace("\n", "") if i not in wordFrequency.keys(): wordFrequency[i] = 1 else: wordFrequency[i] = wordFrequency[i] + 1 if len(i) > longestWordLength: longestWordLength = len(i) longestWord = i totalDictLength = len(words) uniqueWords = 0 for key, value in wordFrequency.items(): if value == 1: uniqueWords = uniqueWords + 1 print(wordFrequency) print(longestWord) print((uniqueWords/totalDictLength)*100)
true
ac0792f282322dc080a62a79f83b57aad55a4d38
rachelmccormack/PythonRevision-Tutoring
/Homework/shoppinglist.py
795
4.21875
4
# Fill out Shopping List Program print("Welcome to the shopping list program...") shoppingList = [] finalise = False def finaliseList(): print("Your final list is: ") for item in shoppingList: print(item) print("Thank you!") return True """ Here we need functions for adding to the list and for removing from the list. """ while finalise == False: print("The current shopping list contains: ") for item in shoppingList: print(item) option = int(input("To add an item, press 1\nTo remove an item, press 2\nTo finalise the list press 3: ")) """ We need to tell the program what to do when 1 and 2 are pressed """ if option == 3: finalise = finaliseList() """ What should we do if a user types 4? """
true
0d68551843d403dfe1ba8f923220c70937532eb0
paradoxal/3.-linkedlist
/linkedlist MALLI.py
2,810
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ :File: linkedlist.py :Author: <Your email> :Date: <The date> """ class LinkedList: """ A doubly linked list object class. The implementation makes use of a `ListNode` class that is used to store the references from each node to its predecessor and follower and to the data object associated with the node. Note: The position of a node can be defined with a value `n` which equals the number of nodes between it and the head of the linked list. In other words: The node that immediately follows the head guardian node is at position 0, its follower at position 1, and so on. """ class ListNode: """ A doubly linked list node object class. List nodes are ment to act as list element(/item) containers that wrap the objects inserted into the linked list. Attributes: obj (object): Any object that need to be stored follower (ListNode): The node that follows this (self) in the linked list predecessor (ListNode): The node that precedes this (self) in the linked list """ def __init__(self, obj): """Initialize a list node object.""" self.obj = obj self.follower = None self.predecessor = None def addAfter(self, node): """Adds node `node` as the follower.""" tmp = self.follower self.follower = node node.predecessor = self node.follower = tmp if tmp: tmp.predecessor = node def removeAfter(self): """Removes the follower.""" if self.follower: self.follower = self.follower.follower if self.follower: self.follower.predecessor = self def __init__(self): """Initialize the linked list.""" # Does this seem reasonable? self.h = self.ListNode(None) # Left guardian (head) self.z = self.ListNode(None) # Right guardian (tail) self.h.addAfter(self.z) def _get_at(self, n): """Return the node at position `n`.""" raise NotImplementedError('Fixme!') def addFirst(self, obj): """Add the object `obj` as the first element.""" raise NotImplementedError('Fixme!') def addLast(self, obj): """Add the object `obj` as the last element.""" raise NotImplementedError('Fixme!') def addPosition(self, n, obj): """Insert the object `obj` as the `n`th element.""" raise NotImplementedError('Fixme!') def removePosition(self, n): """Remove the object at the `n`th position.""" predecessor = self._get_at(n).predecessor if predecessor: predecessor.removeAfter() def getPosition(self, n): """Return the object at the `n`th position.""" return self._get_at(n).obj def getSize(self): """Return the number of objects in the list.""" raise NotImplementedError('Fixme!') # EOF
true
81fe36735b80677a69cd5f1b229ba777cb0dcdf9
santosh-srm/srm-pylearn
/28_max_of_three_numbers.py
917
4.40625
4
"""28_max_of_three_numbers.py""" print("----Finding max of 3 numbers----") num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) num3 = int(input("Enter the third number: ")) if (num1 > num2): if (num1 > num3): print(f'The max number is {num1}') else: print(f'The max number is {num3}') else: if (num2 > num3): print(f'The max number is {num2}') else: print(f'The max number is {num3}') """ Output ----Finding max of 3 numbers---- Enter the first number: 2 Enter the second number: 3 Enter the third number: 4 The max number is 4 PS C:\akademize\W01D01> & C:/Users/santosh/AppData/Local/Programs/Python/Python39/python.exe c:/akademize/W01D01/srm-pylearn/28_max_of_three_numbers.py ----Finding max of 3 numbers---- Enter the first number: 4 Enter the second number: 3 Enter the third number: 5 The max number is 5 """
true
8a8b90655fc27a1434364c3581fdb48792f07658
dlenwell/interview-prep-notes
/code-samples/python/inverting_trees/invert.py
1,913
4.25
4
""" Tree inversion: """ from tree import Node, Tree from collections import deque class InvertTree(Tree): """ InvertTree Tree class extends the base Tree class and just adds the invert functions. This class includes a recursive and an iterative version of the function. """ def invert_aux(self, node): """ invert tree """ # entry point if node is None: return(None) # invert my children node.left, node.right = \ self.invert_aux(node.right), self.invert_aux(node.left) return(node) def recursive_invert(self): """ invert tree """ self.invert_aux(self.root) def invert_iterative(self): """ iterative function to invert the binary tree using a queue """ queue = deque() queue.append(self.root) while queue: current = queue.popleft() current.left, current.right = current.right, current.left if current.left is not None: queue.append(current.left) if current.right is not None: queue.append(current.right) def main(): """ main exercise run through... """ import random tree = InvertTree() unsorted_node_values = [] print('generating tree with 100 nodes with random values between 1 and 999') # add 100 random values to the tree for i in range(12): value = random.randint(1,999) unsorted_node_values.append(value) tree.add(value) print() tree.print() print() print('Inverting tree with recursion:') tree.recursive_invert() print() tree.print() print() print('Inverting tree with iterative style:') tree.invert_iterative() print() tree.print() print() print() if __name__ == "__main__": main()
true
3110b65f4b971f4a2c2967f250e3a22afd73e8f0
ajerit/python-projects
/sorting/binary.py
451
4.15625
4
# # Adolfo Jeritson # Binary search implementation # 2016 # # inputs: A: Array of elements # x: Target element # returns None if the element is not found # the position in the array if the element is found def binarySearch(A, x): start = 0 end = len(A) while start < end: mid = end + (start-end) / 2 if A[mid] == x: return mid elif A[mid] < x: start = mid + 1 else: end = mid - 1 return start if A[start] == x else None
true
ea30d850e5f06ac21da9ef24a9f1e4d6cade3401
Anupama-Regi/python_lab
/24-color1_not_in_color2.py
235
4.1875
4
print("Program that prints out all colors from color-list1 not contained in color-list2") l=input("Enter list1 of colors : ") l2=input("Enter list2 of colors : ") a=l.split() b=l2.split() l3=[i for i in a if i not in b] print(l3)
true
674392160a40f2309d6542271f2325d25bd5abc8
Anupama-Regi/python_lab
/28-remove_even_numbers.py
315
4.21875
4
print("*Program to create a list removing even numbers from a list of integers.*") n=input("Enter the list of integers : ") l=list(map(int,n.split())) print("List of numbers : ",l) #l2=[i for i in l if i%2!=0] #print(l2) for i in l: if(i%2==0): l.remove(i) print("List after removing even numbers : ",l)
true
7f902eb622852e3435c85d96ab00338b215a3f1e
Anupama-Regi/python_lab
/Cycle_3-python-Anupama_Regi/15-factorial_using_function.py
209
4.4375
4
print("Program to find factorial using function") def factorial(n): f=1 for i in range(1,n+1): f=f*i print("Factorial is ",f) n=int(input("Enter the number to find factorial : ")) factorial(n)
true
3bf050700ee59e70d6fa1b5f41b4829a1b033df9
horia94ro/python_fdm_26februarie
/day_2_part_1.py
1,981
4.25
4
print(7 >= 10) print(10 != 12) print(15 > 10) a = 32 if (a >= 25 and a <= 30): print("Number in the interval") else: if (a < 25): print("Number is smaller than 25") else: print("Number is bigger than 30") if a >= 25 and a <= 30: print("Number in the interval") elif a < 25: print("Number is smaller than 25") elif a > 30: print("Number is bigger than 30") else: print("The default case") season = input("Enter the value: ").lower() if season == "summer": print("HOT :D") else: if season == "winter": print("COLD :(") else: if season == "fall" or season == "spring": print("RAIN") else: print("Invalid value for season") if season == "summer": print("HOT :D") elif season == "winter": print("COLD :(") elif season == "fall" or season == "spring": print("RAIN :(") else: print("Invalid value") hour = input("Enter the hour: ") if hour.isnumeric(): hour = int(hour) if hour > 0 and hour <= 23: if hour >= 6 and hour < 12: print("Good morning!") elif hour >= 12 and hour < 17: print("Good afternoon!") elif hour >= 17 and hour <= 22: print("Good evening!") else: print("You should be sleeping") else: print("Value is not on the clock!") else: print("The value is not correct.") if 123: print(":)") if "non empty string": print(":)") a = 100 while a > 5: print(a, end = "\t") a -= 8 print("\ninstruction after the loop") count = 15 while count: #count > 0 count -= 1 print(count, end = " ") if count == 10: print("Execution of loop will now stop") break #Break will stop the whole while loop, not just the current iteration print("Instruction after the loop") count = 10 while count: if count == 5: count -= 1 continue print(count, end=" ") count -= 1
true
ac3ef1b204dc2e5be36f08d323737db025865c55
Woodforfood/learn_how_to_code
/Codewars/7kyu/Find_the_capitals.py
260
4.125
4
# Write a function that takes a single string (word) as argument. # The function must return an ordered list containing the indexes of all capital letters in the string. def capitals(word): return [i for i, letter in enumerate(word) if letter.isupper()]
true
7a63e23ebafcc8275fa1307cfa41aa79050538ba
aslishemesh/Exercises
/exercise1.py
692
4.125
4
# Exercise1 - training. def check_div_even(num, check): if num % check == 0: return True else: return False num = input("Please enter a number: ") if check_div_even(num, 4): print "The number %d can be divided by 4" % num elif check_div_even(num, 2): print "The number %d is an even number but not a multiple of 4" % num else: print "The number %d is an odd number and therefor cannot be divided by 2 or 4" % num check = input("please enter a number to check (as a divider): ") if check_div_even(num, check): print "The number %d can be divided by %d" % (num, check) else: print "The number %d cannot be divided by %d" % (num, check)
true
9f1157b501791c4cac209b2ebacefaf0c04da0aa
benfield97/info-validator
/info_validator.py
1,041
4.1875
4
import pyinputplus as pyip import datetime import re while True: name = pyip.inputStr("What is your name? ") if all(x.isalpha() or x.isspace() for x in name): name_len = name.split() if len(name_len) < 2: print("Please enter both a first and last name") continue else: break else: print("Name Invalid: Please only use letters") continue birthday = pyip.inputDate(prompt="Please enter your date of birth (example: 4 Jan 2001) ", formats=['%d %b %Y']) # will need to check address with a regex expression while True: pattern = re.compile(r'\d+\s[A-z]+\s[A-z]+,\s(VIC|NSW|TAS|ACT|NT|SA|WA)', re.IGNORECASE) address = input('Enter you address (Example: 4 Example St, VIC) ') result = pattern.search(address) if result: break else: print('Address Invalid') goals = input("What are your goals? ") print(f"Name: {name}") print(f"Birthday: {birthday}") print(f"Address: {address}") print(f"Goals: {goals}")
true
a4e828ffddc57348328a53dae0208e7be7044902
nerdycheetah/lessons
/recursion_practice.py
339
4.28125
4
''' Recursion Practice 10/17/2020 Example: Let's make a function that takes in a number and recursively adds to the total until the number reaches 1 ''' def recursive_total(n:int) -> int: if n == 1: return n else: print(f'n is currently: {n}') return recursive_total(n - 1) + n print(recursive_total(10))
true
edcab377fe47ccda40631e5c4a906446972c0ca3
nicowjy/practice
/Leetcode/101对称二叉树.py
753
4.15625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # 对称二叉树 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def helper(root1, root2): if not root1 and not root2: return True if (not root1 and root2) or (not root2 and root1): return False if root1.val != root2.val: return False return helper(root1.left, root2.right) and helper(root1.right, root2.left) return helper(root, root)
true
1daf2db78044c8a1fcd44d918f5156a06ea9c75d
KartikKannapur/Algorithms
/00_Code/01_LeetCode/559_MaximumDepthofN-aryTree.py
1,385
4.25
4
""" Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. """ """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ """ Method 1: Recursion """ # if not root: # return 0 # if not root.children: # return 1 # return max(self.maxDepth(node) for node in root.children) + 1 """ Method 2: BFS """ if not root: return 0 if not root.children: return 1 max_depth = 0 queue = [root, 'X'] while queue: node = queue.pop(0) if node == 'X': max_depth += 1 if queue: queue.append('X') elif node and node.children: for ele in node.children: queue.append(ele) # print([ele.val if ele != 'X' else ele for ele in queue]) return max_depth
true
b4f0f0a2746fe03ceebd1007794f815f4d5c36a1
KartikKannapur/Algorithms
/00_Code/01_LeetCode/557_ReverseWordsinaStringIII.py
704
4.21875
4
# #Given a string, you need to reverse the order of characters # #in each word within a sentence while still preserving whitespace # #and initial word order. # #Example 1: # #Input: "Let's take LeetCode contest" # #Output: "s'teL ekat edoCteeL tsetnoc" # #Note: In the string, each word is separated by single space and # #there will not be any extra space in the string. # #Your runtime beats 91.64 % of python submissions. class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ # #Method 1 return " ".join([var_word[::-1] for var_word in s.split(" ")]) # #Method 2 return ' '.join(s.split()[::-1])[::-1]
true
2f883b3bd4645908e4b77ed0ae0669be10e283be
KartikKannapur/Algorithms
/00_Code/01_LeetCode/876_MiddleoftheLinkedList.py
1,440
4.1875
4
""" Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ """ Method 1: Traverse with slowPtr and fastPtr * Assign slowPtr and fastPtr to head * Update the slowPtr by 1 and the fastPtr by 2 * When the fastPtr reaches the end, the slowPtr should have reached the middle of the Linked List. Your runtime beats 70.93 % of python3 submissions. """ slowPtr = fastPtr = head while fastPtr and fastPtr.next: slowPtr = slowPtr.next fastPtr = fastPtr.next.next return slowPtr
true
7b60b68b7fb1f6e0f71f016fee6c1a5fa25289a3
KartikKannapur/Algorithms
/00_Code/01_LeetCode/239_SlidingWindowMaximum.py
1,155
4.28125
4
""" Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example: Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Note: You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array. Follow up: Could you solve it in linear time? """ class Solution(): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ """ Method 1: O(nk) Your runtime beats 19.88 % of python submissions. """ if nums: return [max(nums[i:i + k]) for i in range(0, len(nums) - k + 1)] return []
true
cd1d5ae088fc786391b2a0ff3c27dd874420d13f
KartikKannapur/Algorithms
/00_Code/01_LeetCode/332_ReconstructItinerary.py
1,832
4.5625
5
""" Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] Example 2: Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. """ class Solution: def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ """ Reference: Discussion Forum """ d = {} for ticket in tickets: if ticket[0] not in d: d[ticket[0]] = [ticket[1]] else: d[ticket[0]].append(ticket[1]) for ticket in d: d[ticket].sort() res = ['JFK'] end = [] while d: if res[-1] not in d: end.append(res[-1]) res.pop() continue fr, to = res[-1], d[res[-1]].pop(0) res.append(to) if len(d[fr]) == 0: d.pop(fr) if end: res += end[::-1] return res
true
0a1b65a184da3df85610fbe3760ae972c2834db1
KartikKannapur/Algorithms
/00_Code/01_LeetCode/883_ProjectionAreaof3DShapes.py
2,987
4.5
4
""" On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). Now we view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane. Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections. Example 1: Input: [[2]] Output: 5 Example 2: Input: [[1,2],[3,4]] Output: 17 Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane. Example 3: Input: [[1,0],[0,2]] Output: 8 Example 4: Input: [[1,1,1],[1,0,1],[1,1,1]] Output: 14 Example 5: Input: [[2,2,2],[2,1,2],[2,2,2]] Output: 21 Note: 1 <= grid.length = grid[0].length <= 50 0 <= grid[i][j] <= 50 """ class Solution(object): def projectionArea(self, grid): """ :type grid: List[List[int]] :rtype: int """ """ Algorithm: From the top, the shadow made by the shape will be 1 square for each non-zero value. From the side, the shadow made by the shape will be the largest value for each row in the grid. From the front, the shadow made by the shape will be the largest value for each column in the grid. --------------------------------------------------------------- The first iteration of my solution was O(n^2) + O(n^2) + O(n^2) # #Checking for non-zero values var_x = sum([1 for ele in grid for sub_ele in ele if sub_ele]) # #Checking for values in each column var_y = 0 for index in range(len(grid)): var_y += max([grid[ele][index] for ele in range(len(grid))]) # #Checking for values in each row var_z = sum([max(ele) for ele in grid]) return var_x+var_y+var_z --------------------------------------------------------------- --------------------------------------------------------------- Can we do this with one pass? Code below Time complexity: O(n^2) Space complexity: O(1) --------------------------------------------------------------- Your runtime beats 100.00 % of python submissions. """ res = 0 for i in range(len(grid)): max_row_wise = 0 max_col_wise = 0 for j in range(len(grid)): # #Check for non-zero values for the # #view from the top if grid[i][j]: res += 1 # #Find the maximum row_wise and col_wise # #acorss all the lists in the list of lists max_row_wise = max(max_row_wise, grid[i][j]) max_col_wise = max(max_col_wise, grid[j][i]) res += (max_row_wise + max_col_wise) return res
true
24ea31762444a62ad6d997c484bf624da5cdd2a5
KartikKannapur/Algorithms
/02_Coursera_Algorithmic_Toolbox/Week_01_MaximumPairwiseProduct.py
991
4.1875
4
# Uses python3 __author__ = "Kartik Kannapur" # #Import Libraries import sys # #Algorithm: # #Essentially we need to pick the 2 largest elements from the array # #Method 1: Sort the array and select the two largest elements - Very expensive # #Method 2: Scan the entire array twice by maintaining two indexes - Max1 and Max 2 - # #Can this be reduced to one operation? # #Method 3: Scan the array once, keeping a track of the largest element and the second largest # #while looping through the array itself. arr_len = int(sys.stdin.readline()) arr_vals = sys.stdin.readline() arr = [int(elem) for elem in arr_vals.split()] max_one = arr[0] max_two = arr[0] # #Linear Search if len(arr) == 2: max_one = arr[0] max_two = arr[1] if len(arr) > 2: for element in arr: if element >= max_one: max_two = max_one max_one = element if (element > max_two) and (element < max_one): max_two = element # print(max_one, max_two, "Product:", (max_one*max_two)) print((max_one*max_two))
true
950e019702f534105369ef8d70380546c910e1dc
testmywork77/WorkspaceAbhi
/Year 8/Casting.py
812
4.28125
4
name = "Bruce" age = "42" height = 1.86 highscore = 128 # For this activity you will need to use casting as appropriate. # Using the data stored in the above variables: # 1. Use concatenation to output the sentence - "Bruce is 1.86m tall." print(name + " is " + str(1.86) + "m tall.") # 2. Use concatenation to output the sentence - "Bruce is 42 years old." print(name + " is " + age + " years old.") # 3. Use concatenation to output the sentence - "Bruce has a high score of 128." print(name + " has a highscore of " + str(128) + ".") # 4. Create a new variable called half _age and store in it the result of 42/2 as an integer half_age = int(42/2) print("half_age: " + str(half_age)) # 5. Use concatenation to output the sentence - "Half Bruce's age is 21." print("Half " + name + "'s age is " + str(half_age))
true