blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5590896e3fea9979a561dd276bdf685e3d878f7f
OrdinaryCoder00/CODE-WARS-PROBLEMS-SOLUTIONS
/8Kyu - Return the day.py
262
4.1875
4
def whatday(num): # Put your code here days = {'1':'Sunday','2':'Monday','3':'Tuesday','4':'Wednesday','5':'Thursday', '6':'Friday','7':'Saturday'} return days[str(num)] if (num<=7 and num>0) else 'Wrong, please enter a number between 1 and 7'
false
aba1e928602d0d71bd126ed989397d86505c6181
QAMilestoneAcademy/PythonForBeginners
/datatype_complex/dict_learn.py
2,106
4.3125
4
# # # empty dictionary # my_dict = {} # # # # dictionary with integer keys # my_dict = {1: 'apple', 2: 'ball'} # # # # # dictionary with mixed keys # my_dict = {'name': 'John', 1: [2, 4, 3]} # # # # # using dict() # # my_dict = dict({1:'apple', 2:'ball'}) # # # # # from sequence having each item as a pair # # my_dict = dict([(1,'apple'), (2,'ball')]) # # # #Access element # student_grade={"anu":7,"mahi":8,"aarav":10,"anay":9} # print(student_grade["mahi"]) # # # # get vs [] for retrieving elements # person_detail = {'name': 'Jack', 'age': 26,'city':"Dubai"} # # # Output: Jack # print(person_detail['name']) # print(person_detail['age']) # print(person_detail['city']) # # # person_detail['age']=27 # print(person_detail) # # #remove element # student_grade={"anu":7,"mahi":8,"aarav":10,"anay":9} # print(student_grade.pop("anay")) # print(student_grade) # # ##add key value pair to the dictionary # country_capital_dict={} # country_capital_dict.update({"India":"Delhi"}) # print(country_capital_dict) # country_capital_dict.update({"UAE":"Abudhabi"}) # print(country_capital_dict) # #Find if key is in the dictionary # d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} # # if 3 in d: # print('Key is present in the dictionary') # else: # print('Key is not present in the dictionary') # student_grade={"anu":7,"mahi":8,"aarav":10,"anay":9} # if "anu" in student_grade: # print('Key is present in the dictionary') # else: # print('Key is not present in the dictionary') # # Iterate over dictionaries using for loops d = {'x': 10, 'y': 20, 'z': 30} # d = {'x': 10, 'y': 20, 'z': 30} for element in d.items(): print(element) # # for dict_key, dict_value in d.items(): # print(dict_key,'->',dict_value) # # # Generate and print a dictionary that contains a number in the form (x, x*x) # n=int(input("Input a number ")) # d = dict() # # for x in range(1,n+1): # d[x]=x*x # # print("dictionary for first {} number & squares".format(n),d) # # # Python Program to multiply all the items in a dictionary. # # d={'A':10,'B':10,'C':239} # tot=1 # for i in d: # tot=tot*d[i] # print(tot)
false
973a2594be321dc49ee9c174ec27d14f06a9c0c9
QAMilestoneAcademy/PythonForBeginners
/ProgramFlow/while_learn.py
1,855
4.3125
4
# An if statement is run once if its condition evaluates to True, and never if it evaluates to False. # A while statement is similar, except that it can be run more than once. The statements inside it are repeatedly executed, as long as the condition holds. Once it evaluates to False, the next section of code is executed. # a=0 # while a<=5: # print("hello") # a+=1 # print("I am not in loop") # How many numbers does this code print? # i = 3 # while i>=0: # print(i) # i = i - 1 # The infinite loop is a special kind of while loop; it never stops running. Its condition always remains True. # An example of an infinite loop: # while 1 == 1: # print("In the loop") #Fill in the blanks to create a loop that increments the value of x by 2 and prints the even values. # # x = 0 # while x <= 20: # print(x) # x += 2 # To end a while loop prematurely, the break statement can be used. # When encountered inside a loop, the break statement causes the loop to finish immediately # i = 0 # while 1==1: # print(i) # i = i + 1 # if i >= 5: # print("Breaking") # break # print("Finished") #EXample: # while True: # name=input("Enter your name: ") # print("hello" + name) # # if(name==""): # print("bye! I need name") # break # How many numbers does this code print? # i = 5 # while True: # print(i) # i = i - 1 # if i <= 2: # break # Another statement that can be used within loops is continue. # Unlike break, continue jumps back to the top of the loop, rather than stopping it i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") i=0 while i<=5: print("hello") i+=1 while True: num1 = int(input("enter num")) if num1==0: break print("hi")
true
50dcafa138fdee36c30bd9a1b49bd3698ec2683b
syedahmedullah14/Python-programming-examples
/Dictionary_programs_2/binary_anagram_dict.py
803
4.125
4
# Q. Python Dictionary | Check if binary representations of two numbers are anagram '''Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No''' from collections import Counter def binary_anagram(n1,n2): bin1=bin(n1)[2:] bin2=bin(n2)[2:] #taking absolute value in variable using abs() function, for example -2 will be 2 zeros=abs(len(bin1)-len(bin2)) if len(bin1)>len(bin2): bin2=zeros*'0'+bin2 else: bin1=zeros*'0'+bin1 #converting into dictionaries x=Counter(bin1) y=Counter(bin2) if x==y: return 'Yes' else: return 'No' n1,n2 = 1,4 print(binary_anagram(n1,n2))
true
3c932bf81c2924091f2f93ee74e10e7295ffb8bb
syedahmedullah14/Python-programming-examples
/List_programs/cumulative_sum_of_list.py
433
4.15625
4
# Q.Python program to find Cumulative sum of a list ''' The problem statement asks to produce a new list whose i^{th} element will be equal to the sum of the (i + 1) elements. Examples : Input : list = [10, 20, 30, 40, 50] Output : [10, 30, 60, 100, 150] Input : list = [4, 10, 15, 18, 20] Output : [4, 14, 29, 47, 67] ''' list1 =[10, 20, 30, 40, 50] list2=[] total=0 for i in list1: total+=i total.append(list2) print(list2)
true
63cb58b0a209390e04043a0f757afd053bfc8ad0
syedahmedullah14/Python-programming-examples
/Dictionary_programs_2/largest_subset_of_anagram_words.py
964
4.3125
4
# Q. Python Counter to find the size of largest subset of anagram words '''Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan gnamate Output: 3 Explanation Anagram strings(1) - ant, tan Anagram strings(2) - magenta, magnate, gnamate Thus, only second subset have largest size i.e., 3 ''' from collections import Counter def anagrams(str1): dict={} str1=str1.split(' ') for i in range(0,len(str1)): str1[i]=''.join(sorted(str1[i])) dict2=Counter(str1) for value in dict2.values(): return (max(dict2.values())) break # or return (max(dict2.values())) str1='ant magenta magnate tan gnamate' print(anagrams(str1))
true
d7969938e3171222e63267fdb3f46e03cd6d7969
syedahmedullah14/Python-programming-examples
/Dictionary_programs/sort_list_of_dict_using_lamda.py.py
984
4.53125
5
# Q. Ways to sort list of dictionaries by values in Python – Using lambda function # Python code demonstrate the working of sorted() # and lambda function # Initializing list of dictionaries lis = [{ "name" : "Sara", "age" : 22}, { "name" : "Ahmed", "age" : 19 }, { "name" : "Yousuf" , "age" : 20 }, { "name" : "Ankita" , "age" : 20}] # using sorted and itemgetter to print list sorted by age print ("The list printed sorting by age: ") print (sorted(lis, key= lambda i:i['age']) ) print ("\r") # using sorted and itemgetter to print list sorted by both age and name # notice that "Manjeet" now comes before "Nandini" print ("The list printed sorting by age and name: ") print (sorted(lis, key = lambda i: (i['age'], i['name'])) ) print ("\r") # using sorted and itemgetter to print list sorted by age in descending order print ("The list printed sorting by age in descending order: ") print (sorted(lis, key=lambda i: i['age'],reverse = True) )
true
53977387be4bbe96451e7990646efe4a9f06ff39
syedahmedullah14/Python-programming-examples
/Dictionary_programs/sort_list_of_dict_using_itemgetter.py
1,049
4.46875
4
# Q. Ways to sort list of dictionaries by values in Python – Using itemgetter # Python code demonstrate the working of sorted() # and itemgetter # importing "operator" for implementing itemgetter from operator import itemgetter # Initializing list of dictionaries lis = [{ "name" : "Sara", "age" : 22}, { "name" : "Ahmed", "age" : 19 }, { "name" : "Yousuf" , "age" : 20 }, { "name" : "Ankita" , "age" : 20}] # using sorted and itemgetter to print list sorted by age print ("The list printed sorting by age: ") print (sorted(lis, key=itemgetter('age')) ) print ("\r") # using sorted and itemgetter to print list sorted by both age and name # notice that "Manjeet" now comes before "Nandini" print ("The list printed sorting by age and name: ") print (sorted(lis, key=itemgetter('age', 'name')) ) print ("\r") # using sorted and itemgetter to print list sorted by age in descending order print ("The list printed sorting by age in descending order: ") print (sorted(lis, key=itemgetter('age'),reverse = True) )
true
e9abeeea63e4084b07aaa04b2ea7476fc4f536a9
syedahmedullah14/Python-programming-examples
/Dictionary_programs/common_elements_in_array_by_dict.py
988
4.46875
4
# Q. Python | Find common elements in three sorted arrays by dictionary intersection ''' Given three arrays sorted in non-decreasing order, print all common elements in these arrays. Examples: Input: ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] Output: [80, 20] Input: ar1 = [1, 5, 5] ar2 = [3, 4, 5, 5, 10] ar3 = [5, 5, 10, 20] Output: [5, 5] ''' from collections import Counter def common(ar1,ar2,ar3): #converting arrays into dictionaries ar1 = Counter(ar1) ar2 = Counter(ar2) ar3 = Counter(ar3) result=dict(ar1.items() & ar2.items() & ar3.items()) com_arr=[] #the below statement will print dictionary but we only need keys to print print(result) for key, value in result.items(): for i in range(value): #printing keys com_arr.append(key) return com_arr ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] print(common(ar1,ar2,ar3))
true
40eab18e0256ea5a4ca22527534be3eb1c6cbbee
syedahmedullah14/Python-programming-examples
/String_programs/split_and_join_string.py
225
4.15625
4
# Q. Python program to split and join a string ''' Examples : Split the string into list of strings Input : Geeks for Geeks Output : ['Geeks', 'for', 'Geeks'] ''' n='we are anonymous' a=n.split(' ') b='-'.join(a) print(b)
true
36b40d750794b3cd00c697ab991a348e99681a93
pauld4/Portfolio
/python/tree.py
2,164
4.21875
4
# Paul Dziedzic # August 22, 2019 # Last update August 26, 2019 # tree.py # This program creates a binary tree class and a class to hold the tree and alter it class tree: def __init__(self,leaf): self.leaf = leaf self.leaf_count = 0 def printInorder(self,leaf): # The next 3 functions display the nodes in 3 different ways if leaf: self.printInorder(leaf.left) print(leaf.val) self.printInorder(leaf.right) def printPostorder(self,leaf): if leaf: self.printPostorder(leaf.left) self.printPostorder(leaf.right) print(leaf.val) def printPreorder(self,leaf): if leaf: print(leaf.val) self.printPreorder(leaf.left) self.printPreorder(leaf.right) def searchLeaf(self,leaf,number): # Returns the node that was searched for try: if leaf.val == number: return leaf elif number < leaf.val: return self.searchLeaf(leaf.left,number) return self.searchLeaf(leaf.right, number) except: print("error") def addLeaf(self,leaf,number): # Adds node to the tree. Does not balance yet if leaf: if leaf.val == number: print("{} already exists in this tree".format(number)) elif leaf.val > number: leaf.left = self.addLeaf(leaf.left,number) else: leaf.right = self.addLeaf(leaf.right,number) return leaf else: return node(number) def loopLeaf(self,leaf): # Goes through each node and adds it to a total count if leaf: self.loopLeaf(leaf.left) self.loopLeaf(leaf.right) self.leaf_count += 1 def countLeaf(self,leaf): # Starts the counting of the nodes self.leaf_count = 0 self.loopLeaf(leaf) # Count the nodes return self.leaf_count # Return the count class node: def __init__(self,key): self.left = None self.right = None self.val = key root = node(5) # Create the tree with any number of roots root.left = node(3) root.right = node(12) root.left.left = node(1) root.right.left = node(9) root.right.right = node(14) oak = tree(root) # Add the BST to the tree class oak.addLeaf(oak.leaf,4) # Add a node oak.printPreorder(oak.leaf) # Print the tree nodes print("There are {} leaves".format(oak.countLeaf(oak.leaf))) # Display the amount of nodes
true
a811fda18e280c56b966c1fe1c243b829206e962
c-okelly/Programming-1-Python
/Lab 13/P13P2.py
627
4.21875
4
__author__ = 'conor' """ Program to print out the largest of two numbers entered by the user Uses a function max Uses max in a print statement Using code from class """ def max(a, b): #Function that returns the largest of its two arguments""" if a > b: return a else: return b def get_input(): # Function to get input number number = float(raw_input("Please enter a number (float) \n")) return number # Prompt the user for two numbers number1 = get_input() number2 = get_input() print("The largest of %0.2f and %0.2f is %0.2f" % (number1, number2, max(number1,number2))) print("Finished")
true
7b0b0c7a11d8a4fd53a17bc6d607d59ae191f77b
c-okelly/Programming-1-Python
/Lab 14/P14P5.py
1,103
4.125
4
__author__ = 'conor' """ def fib_number(number): if number 1 or 2: return 1 else: return fib_number(number-1) + fib_number(number-2) def make_list(number): list = [] for i in range(1,number+1) list.append(fib_number(i)) def get_input(): get user input def main(): bring all function together """ def fib_number(number): if number == 1 or number ==2: return 1 else: return fib_number(number-1) + fib_number(number-2) def make_list(number): list = [] for i in range(1,number+1): list.append(fib_number(i)) print("The next number in the series was %i and was added to the Fibonacci list" % (fib_number(i))) return list def get_input(): number = int(raw_input("Please enter a number (int) \n")) return number def main(): number = get_input() while number > 0: list = make_list(number) print("The list of Fibonacci numbers to the %i place is %s" % (number, list)) number = get_input() else: print("The number entered is 0 or below") main()
true
e8434fd9236e0c92a62ccbd8fdeab63b81991aa7
mansal3/Python-From-Scratch
/TupleOperations.py
748
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 24 07:10:55 2019 @author: manpreetsaluja """ #TUPLES OPERATIONS #tuples are immutable data type #that means it cannot edit,update,change etc #once after creasting the tuple you cannot do any change in that #tuples represent by round brackets tuple1=('wdff','wdwdsf','qa',213213,4,'hgfd') print(tuple1) print(tuple1[1]) #ouput wdwdsf print(tuple1[1:5]) tuple2=('a','b','c','d','e') tuple3=tuple1+tuple2 print(tuple3) #ouut ('wdff', 'wdwdsf', 'qa', 213213, 4, 'hgfd', 'a', 'b', 'c', 'd', 'e') del(tuple3) print(tuple3) #NameError: name 'tuple3' is not defined len(tuple2) #5 tuple2.count('a') #1 tuple2.index('a') #0 max(tuple2) #e min(tuple2) #a
false
4cd2003c3f7950b28cbab36a5d87e612aab872b0
Cptgreenjeans/python-workout
/ch05-files/e20b1_count_certain_words.py
472
4.15625
4
#!/usr/bin/env python3 """Solution to chapter 5, exercise 20, beyond 1: count_certain_words""" def count_certain_words(): s = input("Enter a filename, and then words you want to track: ").strip() if not s: return None filename, *words = s.split() counts = dict.fromkeys(words, 0) for one_line in open(filename): for one_word in one_line: if one_word in counts: counts[one_word] += 1 return counts
true
f9560164cb0494ae78d77c478dc8c44226686c1f
VinayakAsnotikar/Python_Snippets
/insertion_sort.py
797
4.65625
5
#Insert sort method. def insertion_sort(unordered_list): #Takes in the list to be sorted as parameter. for i in range(1,len(unordered_list)): #We start from one since the iteration occurs upto the lenght of the list. j = i - 1 #j is the position of the current element. #i is the position of the next element. next_element = unordered_list[i] while (unordered_list[j] > next_element) and (j >=0 ): #We swap the elements if the current element is larger than the next element. unordered_list[j+1] = unordered_list[j] j = j - 1 #We move to the next element. unordered_list[j+1] = next_element #We print out the ordered_list but its name is still unordered_list print(unordered_list)
true
c3d1c260b69da8cc27649854343458c1a5beaeb0
Sharayu1071/Daily-Coding-DS-ALGO-Practice
/Hackerank/Python/DigitFreq.py
904
4.15625
4
#program to find the digit frequency in an appropriate string # and the digits are ranging from 0-9 def DigitFrequency(string): #maintaining a hash table to store #the digit frequency of the occuring digits in the string d=dict() for i in string: #check if the character is digit/not if i.isdigit(): d[i]=string.count(i) #sort the hashtable so that the required output will get d=dict(sorted(d.items())) #print the result from the hash table # in a required format for i in range(10): if str(i) in d: print(f'{i} is {d[str(i)]} times') else: print(f'{i} is {0} times') #Input Code str=input() DigitFrequency(str) ''' if input string is as2dfl21kji5e9mc 0 is 0 times 1 is 1 times 2 is 2 times 3 is 0 times 4 is 0 times 5 is 1 times 6 is 0 times 7 is 0 times 8 is 0 times 9 is 1 times '''
true
3752eb4c220dcce6a224b9ea453343a33447e46b
Sharayu1071/Daily-Coding-DS-ALGO-Practice
/Gfg/Python/ugly_num.py
2,189
4.375
4
# DESCRIPTION # Ugly numbers are numbers whose only prime factors are 2, 3 or 5. # The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. # Through this python code we can find out the ugly number at Nth position # Example : # Input : n = 7 # Output : 8 # Input : n = 15 # Output : 24 # Function to divide number by greatest divisible of 2,3,5 and return the last result def Divide(a, b): while a % b == 0: a = a / b return a # Function to find whether the number is ugly or not def is_ugly_num(no): no = Divide(no, 2) no = Divide(no, 3) no = Divide(no, 5) return 1 if no == 1 else 0 # Function to find Nth ugly number def Nth_ugly_num(n): # Initializing the list with 1 as it's not bound by the rule of prime factors by 2,3 or 5 lst = [1] # Initializing the counter with 1 because one ugly number is already stored in the list count = 1 i = 1 # Loop until we reach to the Nth ugly number while count < n: i += 1 # to check the naturally occcuring number is ugly or not, then appending it to the end of the list and updating the counter by one if is_ugly_num(i): lst.append(i) count += 1 # Printing the list of ugly numbers till the Nth ugly number print(*lst) # Returning Nth ugly number return lst[-1] # Main function def main(): # Taking input from user num = int(input("Enter position for ugly number : ")) # Passing the number to Nth_ugly_num function and storing return value in variable un un = Nth_ugly_num(num) print(f"{num}th Ugly Number is : {un}") # To check if the file contains the main function and then calling the main function if __name__ == '__main__': main() # COMPLEXITY: # Space : O(1) # Time :O(N) # OUTPUT # Input : # Enter position for ugly number : 10 # Output : # 10th ugly number is : 12 # Input : # Enter position for ugly number : 150 # Output : # 10th ugly number is : 5832
true
7e6fa59878d310dd1ad3001fb02f86de52b70ba6
Sharayu1071/Daily-Coding-DS-ALGO-Practice
/Gfg/Python/Union_of_2_sorted_arrays.py
810
4.21875
4
def printUnion(arr1, arr2, m, n): i, j = 0, 0 while i < m and j < n: if arr1[i] < arr2[j]: print(arr1[i]) i += 1 elif arr2[j] < arr1[i]: print(arr2[j]) j+= 1 else: print(arr2[j]) j += 1 i += 1 while i < m: print(arr1[i]) i += 1 while j < n: print(arr2[j]) j += 1 m=int(input("Size of first array")) arr1 = [ ] arr2 = [ ] for i in range(m): a=int(input("element")) arr1.append(a) n=int(input("Enter size of second array")) for j in range(n): b=int(input("element")) arr2.append(b) printUnion(arr1, arr2, m, n) #Example # Input : arr1[] = {1, 3, 4, 5, 7} # arr2[] = {2, 3, 5, 6} # Output : Union : {1, 2, 3, 4, 5, 6, 7}
false
94c034b84c14cd066d9d6832a6e5877283624eaa
VSablin/pandas_for_your_grandpa
/2_4_series.py
1,649
4.28125
4
# In this script, we go through lesson 2.4 of Python Pandas for your # Grandpa course: Series Overwriting Data. Web link here: # https://www.gormanalysis.com/blog/python-pandas-for-your-grandpa-series-overwriting-data/ # %% Import libraries import numpy as np import pandas as pd # %% Overwriting with iloc foo = pd.Series(['a', 'b', 'c', 'd', 'e'], index=[10, 40, 50, 30, 20]) # We can use iloc to replace an element: foo.iloc[1] = 'w' print(foo) # replace a set of elements: foo.iloc[[0, 1, 2]] = 'x' print(foo) # or use slicing: foo.iloc[:3] = 'x' print(foo) # %% Overwriting with loc # We can do the same with loc: foo = pd.Series(['a', 'b', 'c', 'd', 'e'], index=[10, 40, 50, 30, 20]) foo.loc[40] = 'w' foo.loc[[10, 40, 50]] = 'x' foo.loc[10:50] = 'x' # %% Overwrite all the elements # Let's assume we want to replace all the elements of foo by new_vals = np.array([5, 10, 15, 20, 25]) # Doing something like foo = pd.Seris(new_vals) is not a good idea, since the # indices will be removed. Instead, use slicing: foo.iloc[:] = new_vals print(foo) # %% Overwriting with another Series x = pd.Series([10, 20, 30, 40]) y = pd.Series([1, 11, 111, 1111], index=[7, 3, 2, 0]) x.loc[[0, 1]] = y print(x) # What the last operaton did was to assign y.loc[0] to x.loc[0] and y.loc[1] # to x.loc[1]. As y.loc[1] does not exist, x.loc[1] is now NaN. Besides, notice # that the type is now float64. # We can combine this with slicing: x.iloc[:2] = y print(x) # We can also use numpy arrays, but they must have the same length. Otherwise, # you get an error: x.loc[[0, 1]] = y.to_numpy() # However, this works: x.loc[[0, 1]] = y.to_numpy()[:2] print(x)
true
f9c51ec263e652f92ff4d2d6ac30ca714db018f1
toluwajosh/algos
/bfs_transversal.py
1,084
4.1875
4
"""print out a binary tree with breadth first search (BFS) Example: 2 - 3 - 1 - 4 - 6 - 5 Output: 2 34 125 """ class BinaryNode: val = None level = None left = None right = None def __init__(self, val, level=None): self.val = val self.level = level def __str__(self): tree_out = "{{[Node] Level: {},\nValue: {},\nLeft: {}, Right: {}}}".format( self.level, self.val, self.left, self.right ) return tree_out class BinaryTree: def __init__(self, root_node): self.root_node = root_node def __str__(self): return self.root_node.__str__() # def add_node(self, ) if __name__ == "__main__": two = BinaryNode(2, 1) three = BinaryNode(3, 2) four = BinaryNode(4, 2) one = BinaryNode(1, 3) six = BinaryNode(6, 3) five = BinaryNode(5, 3) three.left = one four.left = six four.right = five two.left = three two.right = four # two.level = 1 print(two) print(four)
false
971d861c627eace71550a5230197d538f4edb0ef
toluwajosh/algos
/set_check.py
942
4.15625
4
"""set_check Given two sorted lists, create functions that would perform a set union and set intersections on the lists """ def set_union(list1, list2): return list(set(list1 + list2)) def set_intersection(list1, list2): return list(set(list1) - set(list2)) # implement manually def set_union_manual(list1, list2): list_dict = {x: x for x in list1} new_list = list1 for ele in list2: if ele in list_dict: continue new_list.append(ele) return new_list def set_intersection_manual(list1, list2): list_dict = {x:x for x in list1} new_list = [] for ele in list2: if ele in list_dict: new_list.append(ele) return new_list if __name__ == "__main__": a = [1, 2, 3, 4, 5, 6, 7] b = [6, 7, 8, 9, 0] # print(set_union(a, b)) # print(set_union_manual(a, b)) print(set_intersection(a, b)) print(set_intersection_manual(a, b))
true
2adc9f264e7b9166c931ac5fbe145630ed9d9b98
MarioYu1206/PythonStudy
/Chapter3/3.2_manipulate_list.py
2,631
4.1875
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' #直接修改list里的值 print (motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] motorcycles.append('ducati') #append()直接在末尾追加 print(motorcycles) motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') print(motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] motorcycles.insert(0, 'ducati') # insert()可以指定元素插入位置 print(motorcycles) motorcycles.insert(3, 'lifan') print(motorcycles) #如果你要从列表中删除一个元素, 且不再以任何方式使用它, 就使用del 语句; 如果你要在删除元素后还能继续使用它, 就使用方法pop() 。 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[0] # del可以删除任何位置的list元素 print(motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) popped_motercycle = motorcycles.pop() #pop()可以删除list末尾的元素,并让你能够接着使用它,相当于弹出。 print(motorcycles) print(popped_motercycle) motorcycles = ['honda', 'yamaha', 'suzuki'] last_owned = motorcycles.pop() print("The last motorcycle I owned was a " + last_owned + ".") motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles.remove('suzuki') #remove()可以删除指定值,但是只删除第一个指定的值,如果要删除的值在列表中出此案多次,就需要使用循环来判断是否删除了所有这样的值。 print(motorcycles) print("test") motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) too_expensive = 'suzuki' motorcycles.remove(too_expensive) print(motorcycles) print("\nA " + too_expensive.title() + " is too expensive for me.") #练习 #practice 1 guest = ['mario','tom','jane'] print("please join my party " + guest[0].title() + "\nplease join my party " + guest[1].title() + "\nplease join my party " + guest[2].title()) #practice 2 print(guest[-1].title() + " can't join") guest.remove(guest[-1]) print(guest) guest.append('kate') print(guest) #practice 3 guest.insert(0,'a') guest.insert(3,'b') guest.append('c') print(guest) #practice 4 message0 = guest.pop() print(message0) #guest.pop() print(message0 + " sorry") print(guest) message1 = guest.pop() print(message1) #guest.pop() print(message1 + " sorry") print(guest) message2 = guest.pop() print(message2) #guest.pop() print(message2 + " sorry") print(guest) message3 = guest.pop() print(message3) #guest.pop() print(message3 + " sorry") print(guest) del guest[0] del guest[0] print(guest)
false
162f14aee3978f9c99f98512251763be56fa25b3
RobertNguyen125/Udemy-Python-Bootcamp
/6_list/2_listMethod.py
611
4.40625
4
# append(): add an element to the end of the list first_list = [1,2,3,4] first_list.append(5) print(first_list) # extend(): add all elements (in form of list) to the end of list first_list.extend([5,6,7,8]) print(first_list) # insert(index, element): add an element before the index first_list.insert(3, 3) print(first_list) # insert() an element to the end of list first_list.insert(len(first_list), 9) print(first_list) # clear(): get rid of everything in a list # pop(): remove the item at given index and return it print(first_list.pop()) print(first_list) # remove(): remove the item 'x' from a list
true
1afd9b303b3c5f3206a56aa2de078eb5038d1eb0
abhi1540/PythonConceptExamples
/OpenClosedPrinciple.py
2,815
4.34375
4
import math # class Rectangle(object): # # def __init__(self, height, width): # self._height = height # self._width = width # # @property # def height(self): # return self._height # # @height.setter # def height(self, height): # self._height = height # # @property # def width(self): # return self._width # # @width.setter # def width(self, width): # self._width = width # # def __str__(self): # pass # # # class Circle(object): # # def __init__(self, radius): # self._radius = radius # # @property # def radius(self): # return self._radius # # @radius.setter # def radius(self, radius): # self._radius = radius # class AreaCalculator: # # def Area(self, shapes): # # area = 0 # # area = shapes.width*shapes.height # return area # # # rect = Rectangle(12, 13) # area = AreaCalculator() # print(area.Area(rect)) # Let's say if Area is circle then you can do like below # class AreaCalculator: # # def Area(self, shapes): # # area = 0 # if isinstance(shapes, Rectangle): # area = shapes.width*shapes.height # else: # area = shapes.radius * shapes.radius * math.pi # return area # rect = Rectangle(12, 13) # area = AreaCalculator() # print(area.Area(rect)) # # cir = Circle(3) # print(area.Area(cir)) # Now if you have been asked for triangle area then you might have to change AreaCalculator again. #A solution that abides by the Open/Closed Principle #One way of solving this puzzle would be to create a base class for both rectangles and #circles as well as any other shapes that Aldford can think of which defines an abstract method for calculating it’s area. class Shape: def area(self): pass class Rectangle(Shape): def __init__(self, height, width): self._height = height self._width = width @property def height(self): return self._height @height.setter def height(self, height): self._height = height @property def width(self): return self._width @width.setter def width(self, width): self._width = width def area(self): area = self._width * self._height return area class Circle(Shape): def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, radius): self._radius = radius def area(self): area = self._radius * self._radius * math.pi return area def Area(shapes): area = 0; area = shapes.area(); return area; rect = Rectangle(2,4) cir = Circle(3) print(Area(rect)) print(Area(cir))
false
378459cb1e357b2e860a1b885a240532dfddd579
vivekaxl/LexisNexis
/ExtractFeatures/Data/kracekumar/guess_the_number.py
1,984
4.25
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math # initialize global variables used in your code SECRET = -1 CHANCES = 0 LOW = 0 HIGH = 100 # helper function to start and restart the game def new_game(): global SECRET, CHANCES SECRET = random.randrange(LOW, HIGH) print("I have thought of a number between %d and %d" % (LOW, HIGH)) CHANCES = int(math.ceil(math.log(HIGH-LOW+1, 2))) print("You have %d chances to guess it right" % CHANCES) # define event handlers for control panel def range100(): global LOW, HIGH LOW = 0 HIGH = 100 new_game() def range1000(): global LOW, HIGH LOW = 0 HIGH = 1000 new_game() def input_guess(myguess): # main game logic goes here global CHANCES guess = int(myguess) print("Your guess was %d" % guess) CHANCES = CHANCES - 1 if (guess > SECRET): print("That was higher. Please try again.") elif (guess < SECRET): print("That was lower. Please try again.") if (guess == SECRET): print("That was correct! You won!\n") print("Let's play again!") new_game() if (CHANCES == 0): print("You ran out of guesses!\n") print("No problem.Let's play once again.") new_game() else: print("You have %d chances remaining.\n" % CHANCES) # create frame frame = simplegui.create_frame("Guess the Number", 300, 300) # register event handlers for control elements frame.add_button("Range [0-100)", range100, 150) frame.add_button("Range [0-1000)", range1000, 150) frame.add_input("Enter Guess", input_guess, 150) # call new_game and start frame print("Let's play Guess the number.") new_game() frame.start() # always remember to check your completed program against the grading rubric
true
de11857b91a39140a93337535929da806097ba82
ryuuzaki42/apreendendo_python3
/progs/05prog.py
903
4.3125
4
a = 10 b = 3 print("\nPython tem Exponeciação e espaço depois de sring e variável (print(\"a:\", a) -> a: 10)") print("\nValor de a:", a) print("Valor de b:", b) print("\nSoma a + b:", a + b) print("Subtração a - b:", a - b) print("Divisão a / b:", a / b) print("Multiplicação a * b:", a * b) print("Exponeciação a ** b:", a ** b) print("\nDivisão inteira a // b:", a // b) print("Resto da divisão inteira a % b: ", a % b) print("\nCuidado com valores float, são aproximações finitas dos números reais") print("Erros de aredondamento podem se acumular após sucessivas operações nesses valores") print("\nResultado extado das operações abaixo é 1, mas...") print("(100/3 - 33) * 3:", (100/3 - 33) * 3) print("100 - (33 * 3):", 100 - (33 * 3)) print("\n8/4:", 8/4) print("8/3:", 8/3) print("\nint + int = int") print("float + float = float") print("int + float = float\n")
false
83f44607327245eb5012a6144d25f8b8dfa35069
NealWhitlock/Intro-Python-II
/examples/scratch.py
766
4.25
4
class Student: def __init__(self, first_name, last_name): # What happens when an instance is created self.first_name = first_name self.last_name = last_name def __str__(self): # What gets returned when printing with calling a given instance # print(me) <-- printed # Without this you will return the instance's location in memory return f"This student's name is {self.first_name}, {self.last_name}." def __repr__(self): # Returns a printable version of the method # me <-- not printed, just called return f"Could return info here on how the object is created." # f"Point (x={self.x}, y={self.y})" # From lecture me = Student("Neal", "Whitlock") print(me)
true
8bf942009cacad758851721c37ab0b60f30d07af
aggarwal-manisha/Python
/program1.py
425
4.28125
4
''' Print all the values from 1 to 100 which are not divisible by 3 or 5. output should be in following format # # # # # # # # # # # # ''' def pattern(): x = 1 y = 1 while x <= 100: if x % 3 != 0 or x % 5 != 0: pass else: if y % 5 == 0: print('\n') else: print(x, ' ', end='') y += 1 x += 1 pattern()
true
9eb7a0c409c7931ab53fe55ad460abe3ecf36c7a
SAlex1976/repo-gui
/Lesson 7/task3.py
786
4.125
4
#Task 3 Cell # Пользовался разбором ДЗ class Cell: def __init__(self, nums): self.nums = nums def make_order(self, rows): return '\n'.join(['*' * rows for _ in range(self.nums // rows)]) + '\n' + '*' * (self.nums % rows) def __str__(self): return str(self.nums) def __add__(self, other): return str(self.nums + other.nums) + ' Sum of cell' def __sub__(self, other): if self.nums - other.nums > 0 : return self.nums - other.nums def __mul__(self, other): return str(self.nums * other.nums) def __truediv__(self, other): return str(round(self.nums / other.nums)) cell_1 = Cell(14) cell_2 = Cell(24) print(cell_1) print(cell_1 + cell_2) print(cell_2.make_order(10))
false
2040868a44f926d6b3663d8eb25130e3f41870fe
xOscarCodes/Calculator
/Calculator.py
2,107
4.53125
5
print("|------ /\ | |------ | | | /\ --------- |------| |-----| ") print("| / \ | | | | | / \ | | | |_____| ") print("| /____\ | | | | | /____\ | | | |\ ") print("| / \ | | | | | / \ | | | | \ ") print("|______ / \ |______ |______ |______| |______ / \ | |______| | \ ") print("BY CHARANPREET") while True: print("OPTIONS:") print("Enter 'add' to add two numbers") print("Enter 'subtract' to subtract two numbers") print("Enter 'multiply' to multiply two numbers") print("Enter 'divide' to divide two numbers") print("Enter 'age' to find your birth year") user_input = input(":") if user_input == "quit": break elif user_input == "add": #we used float because while doing any operation in decimal from , we will get accurate answer. num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1+num2) print("The answer is " + result) elif user_input == "subtract": num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1 - num2) print("The answer is " + result) elif user_input == "multiply": num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1 * num2) print("The answer is " + result) elif user_input == "divide": num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1 / num2) print("The answer is " + result) elif user_input == "age": x = float(input("Enter the current year: ")) y = float(input("Enter your age: ")) print("This is your birth year") print(x - y) else: print("Unknown Input")
false
430dd2d29e94db6aaa26cdf421872cd5ec366d2e
sanjars/coding_python_isFun
/while_loop_nested_prompt.py
868
4.3125
4
# Small nested While loops with if else statements. # At the prompt, it asks you to type one of the kinds of products that you would # like to see. import sys vegetables = ['potato','tomato','onions','green pepper','cucumber'] fruits = ['apricot','apple','pineapple','strawberry','peach','banana'] while True: while True: answer_1 = input('\nPlease choose what kind of products you would like to see:' + '\n' + '\n1)Vegetables\n2)Fruits' + '\n' + '\nTo Exit the program type quit OR exit\nChoose 1 OR 2 >') if answer_1 == '1': print("\nVegetables are:") for name in vegetables: print('\n' + name.title()) break elif answer_1 == '2': print("\nFruits are:") for name in fruits: print('\n' + name.title()) break elif answer_1 == 'exit' or answer_1 == 'quit': sys.exit() else: print("\nIncorrect Option! Enter 1 OR 2")
true
5fee892a318c55131eb4a3a376278e457e2ee108
liangxiaoxuan/Algorithm-training
/Leetcode/Python/easy/11_26_2_Balanced Binary Tree.py
575
4.21875
4
# For this problem, a height-balanced binary tree is defined as: # # a binary tree in which the left and right subtrees of every node differ in height by no more than 1. # # Example 1: # # # Input: root = [3,9,20,null,null,15,7] # Output: true # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """
true
c0c65aa87fb811020b571454e90d3012ba8649de
liangxiaoxuan/Algorithm-training
/Leetcode/Amazon/arrays/Rotate Image.py
1,327
4.21875
4
# you are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). # # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] # Output: [[7,4,1],[8,5,2],[9,6,3]] def rotate(matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ res1 = [] res2 = [] res3 = [] if len(matrix) == 1: return matrix if len(matrix) == 2: for i in matrix: res1.insert(0, i[0]) res2.insert(0, i[1]) return [res1, res2] else: for i in matrix: res1.insert(0, i[0]) res2.insert(0, i[1]) res3.insert(0, i[2]) return [res1,res2,res3] # inplace def rotate2(matrix): n = len(matrix) for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] print(matrix[i][j]) matrix[i] = matrix[i][::-1] return matrix if __name__ == '__main__': matrix = [[1, 2, 3], [4, 5, 6],[7,8,9]] print(rotate2(matrix))
true
3698887d935f2eb2fa054129a0139bd9d7d69b69
liangxiaoxuan/Algorithm-training
/Leetcode/Python/easy/11_05_2_Search Insert Position.py
917
4.28125
4
# 4.Search Insert Position # Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. # Example 1: # Input: nums = [1,3,5,6], target = 5 # Output: 2 # Example 3: # Input: nums = [1,3,5,6], target = 7 # Output: 4 def Search_Insert_Position(nums, val): if val > max(nums): return len(nums) else: for i, num in enumerate(nums): if num == val: return i elif num < val: pass elif num > val: return i # exp: # 比如[1,3,5,6] target=4, 循环到3的时候,pass;循环到5的时候,5>target, # 插入target到5的左边,数组变成[1,3,4,5,6],return target的index, 还是2 if __name__ == '__main__': nums = [1,2,4,5,6] val =3 Search_Insert_Position(nums, val)
true
e42eaec60fca5225de0563f1e936faaae40fec2f
liangxiaoxuan/Algorithm-training
/Leetcode/Amazon/arrays/Implement strStr() Solution.py
554
4.21875
4
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. # Example 1: # # Input: haystack = "hello", needle = "ll" # Output: 2 def strStr(haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle == "": return 0 for i, num in enumerate(haystack): if haystack[i:i+len(needle)] == needle: return i return -1 if __name__ == '__main__': haystack = "Hello" needle = "ll" print(strStr(haystack, needle))
true
1520173b7692a41a0c37dbb59719020c799277e5
liangxiaoxuan/Algorithm-training
/Leetcode/Python/easy/11_25_1_Maximum Depth of Binary Tree.py
1,062
4.1875
4
# Given the root of a binary tree, return its maximum depth. # # A binary tree's maximum depth is the number of nodes along the longest path # from the root node down to the farthest leaf node. # Example 1: # # # Input: root = [3,9,20,null,null,15,7] # Output: 3 class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left and root.right is None: return 1 return self.dfs(root) # recursion def dfs(self, node, depth=0): if not node: return depth return max(depth, self.dfs(node.left, depth+1), self.dfs(node.right, depth+1)) if __name__ == '__main__': # root = [1, "null", 2] root = TreeNode(1) root.right = TreeNode(2) # root.left = TreeNode(0) s = Solution() print (s.maxDepth(root))
true
d4182b8bd61351e6426d21d6c28fe37feba643c5
BranCP/PYTHON
/Fundamentos/listas.py
1,066
4.375
4
nombre = ['hola',2,'3']; print(nombre[0]); print(len(nombre)); print(nombre[-1]); print(nombre[0:2]); #sin incluir el indice 2 #imprimir los elementos de inicio hasta el indice proporcionado print(nombre[:2]); #sin incluir el indice 2 print(nombre[1:]); nombre.append("nuevo"); print(nombre); nombre[3]="holaaaa"; print(nombre); for name in nombre: print(name); if "Karla" in nombre: print("existe"); else: print("no existe"); #agregar un nuevo elemento nombre.append("new"); print(nombre); #insertar un nuevo elemento en el indice proporcionado nombre.insert(1,"octavio"); print(nombre); #remover un elemento nombre.remove("octavio"); #remover el ultimo elemento de lista nombre.pop(); print(nombre); #remover el indice indicado de la lista del nombre[0]; print(nombre); #limpiar los elementos denuestra lista nombre.clear(); #eliminar por completo la lista del nombre; numeros=[] i=0 while (i<=10): numeros.append(i); i+=1; for numero in numeros: if numero%3==0: print("numero es: ",numero);
false
95e1b2791d9ed8482e70ed3995d86c77b897333d
fieldstoneBigBoss/ICS4U
/a1.py
991
4.21875
4
""" #1 def helloWorld(): print("Hello world!") helloWorld() #2 def greet(x): print("Hello",x,"!") greet("john") #3 def greet2(): a=input("What's your name?") print("Hello",a,"!") greet2() #4 def plus1(num): return num+1 plus1(46) #5 def max3(a,b,c): return(max(a,b,c)) max3(1,2,3) #6 def printN(n): for x in range(1,n+1): print(x) printN(9) #7 def sumN(n): return sum(range(1,n+1)) sumN(4) #8 def strFirst(): str=input("please input a string:") return str[0] strFirst() #9 def strHalf(): str=input("please enter whatever you want!") return str[0:int(len(str)//2)] """ #10 def guessingGame(x): n=0 while True: guess=input("please enter any number that you think:") if float(guess)==x: n=n+1 print("Guess",n,". Your guess is right.It's ",x,".") return else: n=n+1 print("Guess",n,"is wrong !","Try again.") guessingGame(56)
true
8ed17187e2f7e82885837a24b1edd1d9b642b4ac
nbuyanova/stepik_exercises
/exercise_2_1__1.py
385
4.15625
4
# Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после # первого введенного нуля выводит сумму полученных на вход чисел. a = 1 s = 0 while a != 0: a = int(input()) s += a print(s)
false
d2ab52afdf3f3bb8cccd63831f119887ba190ace
a3nv/python-practice
/archive/p_staircase.py
349
4.25
4
def staircase(n): """ You are given a positive integer N which represents the number of steps in a staircase. You can either climb 1 or 2 steps at a time. Write a function that returns the number of unique ways to climb the stairs. :param n: :return: """ # Fill this in. print(staircase(4)) # 5 print(staircase(5)) # 8
true
2ebacba56129e5f8687f29eb6160e3298d29765b
nayeon-hub/daily-python
/python-algorithm/lambda_f.py
233
4.15625
4
''' 람다 함수 def plus_one(x): return x+1 print(plus_one(1)) plus_two = lambda x : x+2 print(plus_two(1)) ''' def plus_one(x): return x+1 a = [1,2,3] print(list(map(plus_one, a))) print(list(map(lambda x : x+2, a)))
false
5465ec8cb42d35ec8db1c1af0791bd608194c1de
zchen0211/topcoder
/python/leetcode/number_theory/326_power_of_three.py
564
4.125
4
''' 326. Power of Three (Easy) Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? ''' class Solution(object): def isPowerOfThree(self, n): # AC if n <= 0: return False while(n>1): if n % 3 == 0: n /= 3 else: return False return True def solution2(self, n): # without loop / recursion # 116... = 3^19 return (n>0 and 1162261467%n==0) if __name__ == '__main__': a = Solution() print a.isPowerOfThree(2)
true
7a0801bc8f8822475219aa8a9de1150d2dd6710d
zchen0211/topcoder
/python/leetcode/combinatorial/491_increasing_subsequences.py
1,644
4.1875
4
""" 491. Increasing Subsequences (Medium) Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 . Example: Input: [4, 6, 7, 7] Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]] Note: The length of the given array will not exceed 15. The range of integer in the given array is [-100,100]. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence. """ class Solution(object): def findSubsequences(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n = len(nums) if n <= 1: return [] if n == 2: if nums[0] <= nums[1]: return [[nums[0], nums[1]]] else: return [] # n >=3 case result = self.findSubsequences(nums[:-1]) print result new_result = [] for item in nums[:-1]: if item <= nums[-1]: new_result.append([item, nums[-1]]) for item in result: new_result.append(item) print 'item', item if item[-1] <= nums[-1]: print 'item', item new_item = [i for i in item] print 'new item', new_item new_item.append(nums[-1]) new_result.append(new_item) print new_result new_result = [tuple(item) for item in new_result] new_result = list(set(new_result)) new_result = [list(item) for item in new_result] return new_result if __name__ == '__main__': a = Solution() # print a.findSubsequences([4,6,7,7]) print a.findSubsequences([1,1,1])
true
82917bdd1191702ac5dcd201927bba62dd22d2e3
zchen0211/topcoder
/python/leetcode/binary_search/436_find_right_interval.py
2,466
4.1875
4
''' 436. Find Right Interval (Medium) Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i. For any interval i, you need to store the minimum interval j's index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array. Note: You may assume the interval's end point is always bigger than its start point. You may assume none of these intervals have the same start point. Example 1: Input: [ [1,2] ] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1. Example 2: Input: [ [3,4], [2,3], [1,2] ] Output: [-1, 0, 1] Explanation: There is no satisfied "right" interval for [3,4]. For [2,3], the interval [3,4] has minimum-"right" start point; For [1,2], the interval [2,3] has minimum-"right" start point. Example 3: Input: [ [1,4], [2,3], [3,4] ] Output: [-1, 2, -1] Explanation: There is no satisfied "right" interval for [1,4] and [3,4]. For [2,3], the interval [3,4] has minimum-"right" start point. ''' # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def findRightInterval(self, intervals): """ :type intervals: List[Interval] :rtype: List[int] """ n = len(intervals) if n == 1: return [-1] arr = [] for i in range(n): arr.append((intervals[i].start, i)) arr.sort(key= lambda item: item[0]) print arr # contains (start, id) result = [] for interv in intervals: result.append(self.helper(arr, interv.end)) return result def helper(self, arr, item): # return id s.t. arr[id] >= item # else return -1 n = len(arr) start = 0 end = n while(start < end): mid = (start+end)/2 if item > arr[mid][0]: start = mid+1 elif item < arr[mid][0]: end = mid else: # item == arr[mid][1] return arr[mid][1] if end == n or start>end: return -1 else: return arr[start][1] if __name__ == '__main__': a = Solution() int1 = Interval(1,4) int2 = Interval(2,3) int3 = Interval(3,4) print a.findRightInterval([int1, int2, int3])
true
57c73e048af1a0163330c4bb2a9994c527d683f5
zchen0211/topcoder
/python/leetcode/system_design/648_replace_words.py
2,125
4.125
4
""" 648. Replace Words (Medium) In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another. Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length. You need to output the sentence after the replacement. Example 1: Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat" Note: The input will only have lower-case letters. 1 <= dict words number <= 1000 1 <= sentence words number <= 1000 1 <= root length <= 100 1 <= sentence words length <= 1000 """ class Trie(object): def __init__(self): self.mapping = {} self.is_word = False class Solution(object): def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ root = Trie() for word in dict: # add to the Trie node = root for i in range(len(word)): c = word[i] if c not in node.mapping: node.mapping[c] = Trie() node = node.mapping[c] if i == len(word)-1: node.is_word = True result = [] sentence_list = sentence.split(" ") for word in sentence_list: # check the word in Trie() # if has a prefix in Trie(), return prefix # if not found, return itself node = root tmp = "" found = False for c in word: if node.is_word: found = True break if c not in node.mapping: break tmp = tmp+c node = node.mapping[c] if found: result.append(tmp) else: result.append(word) # print result return " ".join(result) if __name__ == '__main__': a = Solution() print a.replaceWords(["cat", "bat", "rat", "catt"], "the cattle was rattled by the battery")
true
c5ef92fd7333ddc88316fb415d3da0c75b297a63
zchen0211/topcoder
/python/leetcode/dp/354_russian_doll.py
2,376
4.4375
4
""" 354. Russian Doll Envelopes (Hard) You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? (put one inside other) Example: Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). """ """ Sort the array. Ascend on width and descend on height if width are same. Find the longest increasing subsequence based on height. Since the width is increasing, we only need to consider height. [3, 4] cannot contains [3, 3], so we need to put [3, 4] before [3, 3] when sorting otherwise it will be counted as an increasing number if the order is [3, 3], [3, 4] """ class Solution(object): def maxEnvelopes(self, envelopes): """ :type envelopes: List[List[int]] :rtype: int """ # sort first n = len(envelopes) if n == 0: return 0 envelopes = [tuple(item) for item in envelopes] # step 0: sort by width, (decreasing in height s.t.) envelopes.sort(cmp = lambda a,b: -1 if a[0]<b[0] or (a[0]==b[0] and a[1]>b[1]) else 1) print envelopes # step 1: find the longest increasing subsequence result = [0] * n result[0] = envelopes[0][1] nums = [item[1] for item in envelopes] print nums cnt = 1 for item in nums: idx = bsearch(result, cnt, item) print cnt, idx, item if idx == cnt: result[idx] = item cnt += 1 elif result[idx] > item: result[idx] = item print result return cnt def bsearch(nums, len_, val): print 'search', val, nums[len_-1] if val > nums[len_-1]: return len_ # find first num >= val start = 0 end = len_ mid = (start + end)/2 while start < end: mid = (start + end) /2 if nums[mid] == val: return mid elif nums[mid] < val: start = mid + 1 else: # nums[mid] > val end = mid mid = min(len_-1, max(start, end)) if nums[mid] >= val: return mid else: return mid+1 if __name__ == "__main__": a = Solution() # print a.maxEnvelopes([[5,4],[6,4],[6,7],[2,3]]) print a.maxEnvelopes([[10,17],[10,19],[16,2],[19,18],[5,6]])
true
af24e52705239982eee05e4f70439ed789aebb7a
zchen0211/topcoder
/python/leetcode/combinatorial/247_strobo_num.py
1,124
4.125
4
""" 247. Strobogrammatic Number II (Medium) A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. For example, Given n = 2, return ["11","69","88","96"]. """ class Solution(object): def findStrobogrammatic(self, n): """ :type n: int :rtype: List[str] """ ret = self.helper(n) print ret if n == 1: return ret ret = [item for item in ret if item[0] != "0"] return ret def helper(self, n): if n == 2: return ["00", "11","69","88","96"] if n == 1: return ["0", "1", "8"] ret = self.helper(n - 2) print ret newret = [] for item in ret: newret.append("1" + item + "1") newret.append("6" + item + "9") newret.append("9" + item + "6") newret.append("8" + item + "8") newret.append("0" + item + "0") return newret if __name__ == "__main__": a = Solution() print a.findStrobogrammatic(4)
true
565bb19b7b4fb9344b06b3d46befc0af30c431a1
zchen0211/topcoder
/python/leetcode/tree/687_longest_unival.py
2,585
4.21875
4
""" 687. Longest Univalue Path (Easy) Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. Note: The length of path between two nodes is represented by the number of edges between them. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output: 2 Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output: 2 Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000. """ # 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 longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 res1, res2 = self.helper(root) return res2 - 1 def helper(self, root): # return [0]: longest path with same val # return [1]: best value with this as root if root is None: return 0, 0 # longest path l if root.left is not None and root.left.val == root.val: long_pathl = self.helper_path(root.left) else: long_pathl = 0 # longest path r if root.right is not None and root.right.val == root.val: long_pathr = self.helper_path(root.right) else: long_pathr = 0 # 1 + l + r res = 1 + long_pathl + long_pathr # max(1+l, 1+r) long_path = 1 + max(long_pathl, long_pathr) _, res2 = self.helper(root.left) _, res3 = self.helper(root.right) print 'root:', root.val, res, res2, res3 return long_path, max(res, res2, res3) def helper_path(self, root): if root is None: return 0 path_l, path_r = 1, 1 if root.left is not None and root.left.val == root.val: path_l += self.helper_path(root.left) if root.right is not None and root.right.val == root.val: path_r += self.helper_path(root.right) return max(path_l, path_r) if __name__ == "__main__": n1 = TreeNode(1) n2 = TreeNode(4) n3 = TreeNode(5) n4 = TreeNode(4) n5 = TreeNode(4) n6 = TreeNode(5) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.right = n6 a = Solution() print a.helper_path(n1) print a.longestUnivaluePath(n2)
true
330db3307da0c76e8d020bf8614ee783e4b3abaf
zchen0211/topcoder
/python/leetcode/numerical/537_complex_mul.py
1,319
4.21875
4
''' 537. Complex Number Multiplication (Medium) Given two strings representing two complex numbers. You need to return a string representing their multiplication. Note i2 = -1 according to the definition. Example 1: Input: "1+1i", "1+1i" Output: "0+2i" Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. Example 2: Input: "1+-1i", "1+-1i" Output: "0+-2i" Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. Note: The input strings will not have extra blank. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form. ''' class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ a_r, a_i = a.split('+') b_r, b_i = b.split('+') a_r, b_r = int(a_r), int(b_r) a_i, b_i = int(a_i[:-1]), int(b_i[:-1]) c_r = a_r*b_r - a_i*b_i c_i = a_i*b_r + a_r*b_i result = str(c_r)+'+'+str(c_i)+'i' return result if __name__ == '__main__': a = Solution() print a.complexNumberMultiply('1+1i', '1+1i') print a.complexNumberMultiply('1+-1i', '1+-1i')
true
f09c71c3d6c0e40aa1b391c696b751843b5f0702
zchen0211/topcoder
/python/leetcode/array/1042_flower_painting.py
2,480
4.53125
5
""" 1042. Flower Planting With No Adjacent (Easy) You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers. paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y. Also, there is no garden that has more than 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. Example 1: Input: N = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Example 2: Input: N = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3: Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4] Note: 1 <= N <= 10000 0 <= paths.size <= 20000 No garden has 4 or more paths coming into or leaving it. It is guaranteed an answer exists. """ class Solution(object): def gardenNoAdj(self, N, paths): """ :type N: int :type paths: List[List[int]] :rtype: List[int] """ # memo: i to j memo = {} for i, j in paths: if i in memo: memo[i].append(j) else: memo[i]=[j] if j in memo: memo[j].append(i) else: memo[j]=[i] # dfs result = [-1] * N flag = False def dfs(idx): avail = set([1,2,3,4]) if idx in memo: for idx2 in memo[idx]: color = result[idx2-1] if color in avail: avail.remove(color) for c in avail: result[idx-1] = c if idx == N: return True else: flag = dfs(idx+1) if flag: return True return False dfs(1) return result def solve2(self, N, paths): res = [0] * N G = [[] for i in range(N)] for x, y in paths: G[x - 1].append(y - 1) G[y - 1].append(x - 1) for i in range(N): res[i] = ({1, 2, 3, 4} - {res[j] for j in G[i]}).pop() return res if __name__ == "__main__": a = Solution() print(a.solve2(4, [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]))
true
18223bbf51407e74dd1afa0f4223af02c8874333
zchen0211/topcoder
/python/leetcode/string/482_license_key_formatting.py
2,549
4.3125
4
''' 482. License Key Formatting (Medium) Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced. We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case. So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above. Example 1: Input: S = "2-4A0r7-4k", K = 4 Output: "24A0-R74K" Explanation: The string S has been split into two parts, each part has 4 characters. Example 2: Input: S = "2-4A0r7-4k", K = 3 Output: "24-A0R-74K" Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said above. Note: The length of string S will not exceed 12,000, and K is a positive integer. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). String S is non-empty. ''' class Solution(object): def licenseKeyFormatting(self, S, K): # go through S cnt = 0 output = '' for i in range(len(S)): if S[i] != '-': cnt += 1 if cnt == 0: return '' # generate output tmp_cnt = K - cnt % K # to save mod tmp_pos = 0 while(tmp_pos<len(S)): if S[tmp_pos] == '-': tmp_pos += 1 else: output += S[tmp_pos] tmp_cnt += 1 if tmp_cnt % K == 0: tmp_cnt = 0 output += '-' tmp_pos += 1 if output[-1] == '-': output = output[:-1] return output.upper() def solution2(self, S, K): S = S.replace('-', '') n = len(S) output = S[:n%K] i = n%K while i<n: end = i+K output += '-' + S[i:i+K] i += K if len(output)>0 and output[0] == '-': output=output[1:] return output.upper() if __name__ == '__main__': a = Solution() print a.licenseKeyFormatting("2-4A0r7-4k", K = 5) print a.solution2("2-4A0r7-4k", K = 5) print a.licenseKeyFormatting("---", K = 3) print a.solution2("---", K = 3)
true
3de0f7fe3e2008005e17fa3796eec8d0bf64f455
zchen0211/topcoder
/python/leetcode/geometry/296_best_meeting.py
1,364
4.375
4
""" 296. Best Meeting Point (Hard) A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. For example, given three people living at (0,0), (0,4), and (2,2): 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6. """ class Solution(object): def minTotalDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ m = len(grid) if m == 0: return 0 n = len(grid[0]) if n == 0: return 0 pts = [] for i in range(m): for j in range(n): if grid[i][j] == 1: pts.append([i,j]) if len(pts) == 0: return 0 xs = [item[0] for item in pts] xs.sort() midx = xs[(len(pts)-1)/2] ys = [item[1] for item in pts] ys.sort() midy = ys[(len(pts)-1)/2] print midx, midy result = 0 for item in pts: result += abs(item[0] - midx) result += abs(item[1] - midy) return result
true
00b2190943a5932b17345c6768b4caf4907b756e
RashidRahim/AI-Lab-
/lab1 python environment/Task4.py
420
4.21875
4
a = int(input('Enter the Month\n')) if(a==1 or a==2 or a==3): { print("Winter\n") } elif(a==4 or a==5 or a==6): { print("Spring") } elif (a == 7 or a == 8 or a == 9): { print("Summer") } elif (a == 10 or a == 11 or a == 12): { print("Autumn") } else:print("the month does not exist")
false
2c4a2b6a2258c4c56fdec46dfbfae1a2c2e370e2
ebisLab/codingchallenges
/DP/memoization.py
1,236
4.4375
4
"""caching helps speed up data MEMOIZATION - specific form of caching that involves caching the return value of func based on its paramaters, and if paramater doesnt change, then its memoized, it uses the cache version """ # without MEMOIZATION def addTo80(n): print("long time") return n + 80 print(addTo80(5)) print(addTo80(5)) print(addTo80(5)) # optimize this cache = {} # cache ={ # 5:85 # } def memoizedAddTo80(n): if n in cache: return cache[n] else: print("long time") cache[n] = n+80 return cache[n] print("1", memoizedAddTo80(5)) print("2", memoizedAddTo80(5)) print("2", memoizedAddTo80(5)) # IDEALLY is good to put the cache inside of the function as opposed to global scope # cache gets reset every run def memoizedInsideAddTo80(): cache = {} def memoized(n): if n in cache: return cache[n] else: print("long time") cache[n] = n+80 return cache[n] return memoized memoized = memoizedInsideAddTo80() print("memoized", memoized(7)) print("memoized", memoized(6)) # print("1", memoizedInsideAddTo80(5)) # print("2", memoizedInsideAddTo80(5)) # print("2", memoizedInsideAddTo80(5))
true
134787d49047f65e82bb1a684ad1dd4557a3dc44
privateHmmmm/leetcode
/306-additive-number/additive-number.py
1,963
4.15625
4
# -*- coding:utf-8 -*- # Additive number is a string whose digits can form additive sequence. # # A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. # # # For example: # "112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8. # 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 # "199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199. # 1 + 99 = 100, 99 + 100 = 199 # # # # Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. # # # Given a string containing only digits '0'-'9', write a function to determine if it's an additive number. # # # Follow up: # How would you handle overflow for very large input integers? # # # Credits:Special thanks to @jeantimex for adding this problem and creating all test cases. class Solution(object): def isAdditiveNumber(self, num): """ :type num: str :rtype: bool """ if len(num) <=2 : return False def dfs(idx, pre1, pre2, count): if idx == len(num): return count > 2 min_lens = 1 if not pre1 else max(len(pre1), len(pre2)) for lens in range(min_lens, len(num)+1-idx): tmp = num[idx:idx+lens] if tmp[0] == '0' and len(tmp) > 1: return False if pre1 and pre2: _sum = int(pre1) + int(pre2) if _sum < int(tmp): return False elif _sum > int(tmp): continue if dfs(idx+lens, pre2, tmp, count + 1) == True: return True return False return dfs(0, "", "", 0)
true
411c4b3ec8ccbe607e7db71008cf6179c92d0d51
privateHmmmm/leetcode
/261-graph-valid-tree/graph-valid-tree.py
2,205
4.125
4
# -*- coding:utf-8 -*- # # Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. # # # # For example: # # # Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. # # # Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false. # # # # Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. # class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ """ # DFS if n == 1 and edges == []: return True if len(edges) != n-1: return False biEdges = collections.defaultdict(list) for i in range(0, len(edges)): biEdges[edges[i][0]].append(edges[i][1]) biEdges[edges[i][1]].append(edges[i][0]) visited = set([edges[0][0]]) def helper(node, parent): neighbors = biEdges[node] for nei in neighbors: if nei == parent: continue if nei in visited: return False visited.add(nei) if False == helper(nei, node): return False return True return helper(edges[0][0], -1) """ # union-find if n == 1 and edges == []: return True if len(edges) != n-1: return False fa = [i for i in range(n)] def merge(x, y): fa_x = getfa(x) fa_y = getfa(y) if fa_x != fa_y: fa[fa_x] = fa_y return True else: return False def getfa(x): if fa[x] != x: fa[x] = getfa(fa[x]) return fa[x] for i in range(0, len(edges)): if False == merge(edges[i][0], edges[i][1]): return False return True
true
f2de80bc2659af09ddfce9f402794305eed39fb4
privateHmmmm/leetcode
/251-flatten-2d-vector/flatten-2d-vector.py
1,310
4.15625
4
# -*- coding:utf-8 -*- # # Implement an iterator to flatten a 2d vector. # # # For example, # Given 2d vector = # # [ # [1,2], # [3], # [4,5,6] # ] # # # # By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]. # # # # Follow up: # As an added challenge, try to code it using only iterators in C++ or iterators in Java. # class Vector2D(object): def __init__(self, vec2d): """ Initialize your data structure here. :type vec2d: List[List[int]] """ self.nextI, self.nextJ = 0, 0 self.vec = vec2d def next(self): """ :rtype: int """ self.nextJ += 1 return self.vec[self.nextI][self.nextJ-1] def hasNext(self): """ :rtype: bool """ if self.nextI >= len(self.vec): return False while self.nextJ >= len(self.vec[self.nextI]): self.nextI += 1 self.nextJ = 0 if self.nextI >= len(self.vec): return False return True # Your Vector2D object will be instantiated and called as such: # i, v = Vector2D(vec2d), [] # while i.hasNext(): v.append(i.next())
true
c089b2ec13e35e95e802978a767177f97130d80a
privateHmmmm/leetcode
/680-valid-palindrome-ii/valid-palindrome-ii.py
831
4.21875
4
# -*- coding:utf-8 -*- # # Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # # # Example 1: # # Input: "aba" # Output: True # # # # Example 2: # # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. # # # # Note: # # The string will only contain lowercase characters a-z. # The maximum length of the string is 50000. # # class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ def isPalindrome(s): return s[::-1] == s for i in range(0, len(s)): if s[i] != s[len(s)-1-i]: return isPalindrome(s[i+1:len(s)-i]) or isPalindrome(s[i:len(s)-1-i]) return True
true
9b172301a2fcc2498474d64df6883484d0345c11
privateHmmmm/leetcode
/073-set-matrix-zeroes/set-matrix-zeroes.py
1,478
4.1875
4
# -*- coding:utf-8 -*- # # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. # # # click to show follow up. # # Follow up: # # # Did you use extra space? # A straight forward solution using O(mn) space is probably a bad idea. # A simple improvement uses O(m + n) space, but still not the best solution. # Could you devise a constant space solution? # # class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if matrix == []: return row = len(matrix) column = len(matrix[0]) col0 = 1 for i in range(0, row): for j in range(0, column): if matrix[i][j] == 0: matrix[i][0] = 0 if j == 0: col0 = 0 else: matrix[0][j] = 0 for i in range(row-1, -1, -1): for j in range(column-1, -1, -1): if j == 0: if matrix[i][0] == 0 or col0 == 0: matrix[i][j] = 0 else: if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 return
true
016b05f3d7ffb7d652f6f24a408fa0bcddd33ee7
plaetzaw/Python
/Tues1.21.py
1,267
4.15625
4
class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print("Your car is a {}, {}, {} ".format(self.year, self.make, self.model)) car = Vehicle('Honda', 'Brown', 2015) car.print_info() class Person: def __init__(self, name, email, phone, friends): self.name = name #Instance variable self.email = email self.phone = phone self.friends = [] def greet(self, other_person): print('Hello {}, I am {}!'.format(other_person.name, self.name)) def print_contact_info(self): print('My email: {}, My phone number {}'.format(self.email, self.phone)) def add_friend(self, other_person): self.friends.append(other_person) def num_frineds(self): len(Jordan.friends) print(Jordan.friends) Sonny = Person('Sonny', 'sonny@hotmail.com', '483-485-4948', []) #Creating an object(Person Type) #Passing arguments to the paramaters (instc var) Jordan = Person('Jordan', 'jordan@aol.com', '495-586-3456', []) Sonny.print_contact_info() Jordan.print_contact_info() Jordan.add_friend(Sonny) print(len(Jordan.friends)) Jordan.num_frineds()
false
af85c9bda36c1fd25b4404031f8a9a9081224143
arch1904/Python_Programs
/nth_palindromic_prime.py
1,096
4.40625
4
# nthPalindromicPrime # # Given a non-negative integer n return the nth palindromic prime # A palindromic prime is a number that is both prime and a palidrome - a prime number that is read the same backwards and forwards. # Some examples of palindromic primes: 2,3,5,7,11,101,131,151,181,191,313 # For example, if n = 3, the third palindromic prime is 5. Return 5. # # Example(s) # ---------- # Example 1: # Input: 5 # What is the 5th palindromic prime? It is 11 # Output: # 11 # # Example 2: # Input: 8 # What is the 8th palindromic prime? It is 151 # Output: # 151 # # Parameters # ---------- # n : a non-negative integer # # Returns # ------- # bool # the nth palindromic prime # # hint: write a helper function isPalindromicPrime(n) first! def isPalindromicPrime(num1): if palindrome(num1) and prime_test(num1): return True else: return False def nthPalindromicPrime(n): count=0 i=0 pp=0 while count!=n: if isPalindromicPrime(i): count+=1 pp=i else: pass i+=1 return pp
true
771568a8cf1c85eb33a5601cfc5a4c701a1082e5
arch1904/Python_Programs
/longest_unique_substring.py
1,120
4.125
4
# Longest Unique Substring # # Given a string, find the longest unique substring # # Ideal runtime: o(n). full credit only given for o(n). # # RESTRICTIONS: # There is guarunteed to be exactly 1 longest unique substring # # Example(s) # ---------- # Example 1: # Input: "asdfawefABCDEFaabasfeasf" # # Output: # "wefABCDEF" # # Example 2: # Input: "AA" # # Output: # "A" # # Parameters # ---------- # word: str # String input # # Returns # ------- # String # Longest unique substring def longest_unique_substring(word): ''' returns the longest unique substring ''' i, j = 0, 0 previous_i,previous_j = 0, 0 # word1=word.lower() H = set([]) #create an empty set while j < len(word1): if word1[j] in H: #if the char at j is in the set H.remove(word1[i]) #remove the char i += 1 #increment i else: H.add(word1[j]) #If the word is not in the set then add it to the set j += 1 #increase j if previous_j - previous_i < j - i: previous_i, previous_j = i, j return word[previous_i:previous_j]
true
97b222d1347b4cd51d9c19c31d46b543f5e2cb41
arch1904/Python_Programs
/happy_numbers.py
1,856
4.15625
4
# Happy Numbers # # A happy number is a positive integer with the following characteristic: if we # take ths sum of the square of its digits to get another number, and take the # sum of the squares of that number and continue this process, we eventually # get the number 1. If a number is not happy, we will get stuck in a cycle that # does not include the number 1. # # Your task is to find the number of happy numbers between 0 and the given # integer n. # # Calculation Example: # 19 is a happy number. # 19 -> 1^2 + 9^2 = 1 + 81 = 82 # 82 -> 8^2 + 2^2 = 64 + 4 = 68 # 68 -> 6^2 + 8^2 = 36 + 64 = 100 # 100 -> 1^2 + 0^2 + 0^2 = 1. # # Example(s) # ---------- # Example 1: # Input: 8 # Between 0 and 8, numbers 1 and 7 are happy numbers # Output: # 2 # # Example 2: # Input: 15 # Between 0 and 25, numbers 1, 7, 10, and 13 are happy numbers # Output: # 4 # # Parameters # ---------- # n : int # The high end of the range you need to check for happy numbers # # Returns # ------- # int # The number of happy numbers between 0 and n (exclusive) # square_dictionary=dict([(c,int(c)**2) for c in "0123456789"]) def is_happy(num): l = [] #list to hold values already checked for sum1=0 #holds sum each time while sum1!=1 and num not in l : l.append(num) sum1=0 num=list(str(num)) for i in num: sum1=sum1+square_dictionary[i] if sum1==1: return True else: num=sum1 #assigns num to the sum if sum!=1 return False def happy_numbers(n): """ Given an integer input, return the number of happy numbers between 0 and n """ no_happy_nos=0 for i in range(0,n):#iterates from 0 to input n to check if each no is happy if is_happy(i): no_happy_nos+=1 else: continue return no_happy_nos
true
a39486058732caeb019dee8bca0977c1799f1a70
arch1904/Python_Programs
/rotate_matrix.py
1,417
4.3125
4
# Rotate Matrix # # Write a function that given an NxN matrix will rotate the matrix to the left 90 degrees # # Examples # ---------- # Example 1: # Input: [[1,2],[3,4]] # Output: [[2,4],[1,3]] # # Example 2: # Input: [[1,2,3],[4,5,6],[7,8,9]] # Output: [[3,6,9],[2,5,8],[1,4,7]] # # Parameters # ---------- # matrix: List[List[int]] # A square matrix of ints # # # Returns # ------- # List[List[int]] # Returns parameter matrix rotated 90 degrees to the left # def matrix_transpose(matrix): """ returns the matrix transpose """ # create a list with no of rows = no of columns in original and vice versa transpose= [[0 for y in range(len(matrix))] for x in range(len(matrix[0]))] #loop through the new array for i in xrange(0,len(matrix[0])): for j in xrange(0,len(matrix)): transpose[i][j]=matrix[j][i] #reverse rows and columns and add to new array return transpose def rotate_matrix(matrix): ''' returns a matrix rotated by 90 degrees to the left ''' #We Know Matrix Rotates by 90 degrees by left by taking transpose and then reversing all columns matrix=matrix_transpose(matrix) #Transpose the matrix for i in xrange(0,len(matrix[0])): for j in xrange(0,len(matrix)/2): matrix[j][i],matrix[len(matrix)-1-j][i]=matrix[len(matrix)-1-j][i],matrix[j][i] #Reverse Columns Of Transposed Matrix return matrix
true
f598bb4f1697aa17a2e1312df69740bbcb2f4f5d
arch1904/Python_Programs
/largest_sum_subarray.py
1,331
4.25
4
# Largest Sum Subarray # # Write a function that given an array of integers will return the continuous subarrray with the largest # sum in the entire array # # # Example(s) # ---------- # Example 1: # Input: [-8,-6,1,-4,3,4,6] # Output: [3,4,6] # # Example 2: # Input: [2,-8,7,-3,4,-20] # Output: [7,-3,4] # # Example 3: # Input: [-1,-2,-3,-4] # Output: [-1] # # Parameters # ---------- # arr : List[int] # A variable length array of integers # # Returns # ------- # List[int] # Largest sum continous sub array # def largest_sum_subarray(arr): ''' returns the largest sum continous sub array ''' if len(arr) == 0: #If Arr is Empty Return None return None sum = max_sum = arr[0] #initialising sum and max sum to first element of the array i = 0 first = last = 0 for j in range(1, len(arr)): #Iterate through list starting at the second element if arr[j] > (sum + arr[j]): #if current element is greater than sum + current element sum = arr[j] i = j else: sum += arr[j] #keep adding consecutive elements if sum > max_sum: max_sum = sum #get maximum sum first = i #index where largest sum subarray starts last = j #index where largest sum subarray ends return arr[first:last+1]
true
0996481021d3742264b80013c3e40d3707782a7f
eithney/learning-works
/python/learn-python/test-04/app-class.py
865
4.15625
4
#!/usr/bin/env python # coding:utf-8 class Date(object): day = 0 month = 0 year = 0 def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year def display(self): return "{2}年{1}月{0}日".format(self.day, self.month, self.year) @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) return cls(day, month, year) @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day <= 31 and month <= 12 and year <= 3999 date1 = Date('12','11','2014') date2 = Date.from_string('11-13-2017') print date1.display() print date2.display() print date2.is_date_valid('11-12-2014') print Date.is_date_valid('11-13-2014')
false
cfa3fe45040279d5bfdb304e072da0ff7dca2d4d
mlgomez0/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
348
4.25
4
#!/usr/bin/env python3 """This function returns the transpose of a 2D matrix""" def matrix_transpose(matrix): """matrix elements are of the same type/shape""" transpose = [] for i in range(len(matrix[0])): row = [] for item in matrix: row.append(item[i]) transpose.append(row) return transpose
true
15f1fc6bc216df74365ed393eecd065acf19989f
bcveber/COSC101
/lab12/word_search_functions.py
2,386
4.15625
4
# The constants describing the multiplicative factor for finding a word in # a particular direction. These should be used in function get_factor. FORWARD_FACTOR = 1 DOWN_FACTOR = 2 BACKWARD_FACTOR = 3 UP_FACTOR = 4 def get_current_player(player_one_turn): """ (bool) -> str Return 'Player One' if player_one_turn is True; otherwise, return 'Player Two'. >>> get_current_player(True) 'Player One' >>> get_current_player(False) 'Player Two' """ if player_one_turn == True: return "Player One" else: return "Player Two" #Independent Function Test #print(get_current_player(True)) # Helper functions. Do not modify these, although you are welcome to call # them. def get_row(puz, row_num): """ (str, int) -> str Precondition: 0 <= row_num < number of rows in puzzle Return row row_num of puzzle. >>> get_row('abcd\nefgh\nijkl\n', 1) 'efgh' """ separated_words = puz.split("\n") final_word = separated_words[row_num] return final_word #Independent Function Test #print("get_row Function Test") #print(get_row('abcd\nefgh\nijkl\n', 1)) def get_column(puz, col_num): """ (str, int) -> str Precondition: 0 <= col_num < number of columns in puzzle Return column col_num of puzzle. >>> get_column('abcde\nefghi\nijklm\n', 1) 'bfj' """ separated_words = puz.split("\n") final_list = '' for word in range(len(separated_words) - 1 ): character = separated_words[word].strip() final_list += character[col_num] return final_list #Independent Function Test #print("get_column Function Test") #print(get_column('abcd\nefgh\nijkl\n', 1)) def reverse(s): """ (str) -> str Return a reversed copy of s. >>> reverse('abc') 'cba' """ if s == "": return s else: return reverse(s[1:]) + s[0] #Independent Function Test #print("Reverse Function Test") #print(reverse("abc")) def contains(s1, s2): """ (str, str) -> bool Return True iff s2 appears anywhere in s1. >>> contains('abc', 'bc') True >>> contains('abc', 'cb') False """ if s1 == '': return False if len(s2) > len(s1): return False if s1[:len(s2)] == s2: return True change = s1[1:] return contains(change, s2)
true
b0b2e71c786d7d80dbd87050a2949157a67332a4
bcveber/COSC101
/lab10/generator.py
2,927
4.15625
4
#Brian Veber, Lab 10 import random def noun_phrase(): ''' () --> (str) Takes an random article from a list and a random noun from a list and adds them together. >>> noun_phrase() LOVE AN >>> noun_phrase() WORLD THE ''' noun = (random.choice(open('nouns.txt').readline().split())) article = (random.choice(open('articles.txt').readline().split())) noun_phrase = article + ' ' + noun return(noun_phrase) def prepositional_phrase(): ''' () --> (str) Takes a random preposition from a list and runs noun_phrase() to get a random noun_phrase and adds them together. >>> prepositional_phrase() PAST LITERATURE AN ''' nounphrase = noun_phrase() #print(nounphrase) preposition =(random.choice(open('prepositions.txt').readline().split())) prepositional_phrase = preposition + ' ' + nounphrase return prepositional_phrase def verb_phrase(): ''' () --> (str) Takes a random verb from a list, a random noun phrase from noun_phrase fuunction, and a random prepositional phrase from prepositional_phrase function. >>> verb_phrase() ABILITY THE ABOUT COMPUTER AN 'JUMP ABILITY THE ABOUT COMPUTER AN' ''' nounphrase = noun_phrase() #print(nounphrase) prepositionalphrase = prepositional_phrase() #print(prepositionalphrase) verb = (random.choice(open('verbs.txt').readline().split())) verb_phrase = verb + ' ' + nounphrase + ' ' + prepositionalphrase return verb_phrase def sentence(): ''' () --> (str) Takes a random noun phrase and a random verb phrase and adds them together. >>> sentence() THANKS AN TALK MUSIC A ON LOVE A ''' verbphrase = verb_phrase() nounphrase = noun_phrase() sentence = nounphrase + ' ' + verbphrase return sentence def generator(): ''' () ---> (str) Generates a list of sentences based on how many sentences the user requests using the sentence() function. >>> generator() Enter the number of sentences: 4 ABILITY AN ADD METHOD AN ONTO MUSIC AN LAW A VISIT HEALTH AN MINUS HISTORY AN FOOD A JUMP DATA THE BUT HISTORY A FAMILY AN PASS WORLD A DESPITE SOFTWARE A >>> ''' sentence_list = [] sentences = int(input ('Enter the number of sentences: ')) for amount in range (sentences): sentence_list += [(sentence())] return sentence_list def main(): ''' () ---> (str) Displays a set of sentences user the generator() program. >>> main() Enter the number of sentences: 4 FOOD A OBEY HEALTH THE MINUS DATA AN BIRD AN WALK BIRD THE AT COMPUTER AN DATA A JUMP LAW A AT THEORY AN LITERATURE THE JUMP MAP THE EXCEPT PERSON AN ''' sentences = generator() for item in sentences: print(item)
false
ed5d6a924359a4471c36c2f4bc52da167b8e5e71
haibinj/lecture_notes
/lecture_python/test.py
1,564
4.34375
4
print("hello") print(19/3) print(19//3) ## rounded print(19%3) ## remainder print(18/3) ### this give 6.0. Division always gives a floating round number. it is treated differently. print(5**2) print(2**10) ## assign a number to a variable a = 10 b = 20 print(a+b) a = 19 print(a/3) print(a//3) ## rounded print(a%3) ## remainder a = 31 print(a/3) print(a//3) ## rounded print(a%3) ## remainder ## assignment at the place that a variable is used for the first time to avoid mistake. ## in economics, assign number to simulate. ## if no define. returns an error, and the code stop there. This can be a reminder for where the error is. This can also be used to test a piece of code. # print(c+1) print("hello world") ## function, colon is needed. ## space in front the code after the def function, easy to read. def addandmultiply(a,b): print(a+b) print(a*b) addandmultiply(10,20) addandmultiply(20,40) addandmultiply(100,200) addandmultiply(1000,2000) ## compared with other coding language ## in R, use curly brackets to include the function code. ## ## addandmultiply <- function(a,b) { ## print(a+b) ## print(a*b) ## } ## to round a float number to certain dicimal print(round(3.1415926,3)) # in terminal # git status # git add . # git status # git commit -m "python numbers" # git push ## to name the variable and function, easy to read using snake case. def add_and_multiply(a,b): print(a+b) print(a*b) add_and_multiply(10,20) add_and_multiply(20,40) add_and_multiply(100,200) add_and_multiply(1000,2000)
true
a6b54df808e0dc88590e696ebe2f9a5a2b9e7b44
petershan1119/Python-practice
/09.functions/closure.py
530
4.125
4
level = 0 def global(): global level level += 3 print(level) def outer(): # outer함수의 지역변수 level level = 50 # outer함수의 지역함수 inner def inner(): # inner에서 nonlocal로 outer의 level을 사용 nonlocal level level += 3 # outer함수의 level을 출력 print(level) # outer함수는 자신의 내부에서 정의된 inner함수를 리턴 return inner f1 = outer() f2 = outer() print(f1) print(f2) f1() f1() f2()
false
03374388b5b65080e963a2bb9cc3b0d7ce90b13a
HarrietLLowe/python_rock-paper-scissors
/Type_2.py
1,290
4.25
4
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' #Rock wins against scissors; Scissors wins against paper; Paper wins against rock import random human_choice = input("What do you choose? Type 0 for Rock, 1 for Paper and 2 for Scissors. \n") if human_choice == "0": print(rock) elif human_choice == "1": print(paper) elif human_choice == "2": print(scissors) print("Computer choses:") computer_choice = random.randint(0, 2) if computer_choice == 0: print(rock) elif computer_choice == 1: print(paper) elif computer_choice == 2: print (scissors) if human_choice == "0" and computer_choice == 1: print("You win") elif human_choice == "0" and computer_choice == 2: print ("You lose") elif human_choice == "1" and computer_choice == 0: print ("You win") elif human_choice == "1" and computer_choice == 2: print ("You lose") elif human_choice == "2" and computer_choice == 1: print ("You win") elif human_choice == "2" and computer_choice == 0: print ("You lose") else: print("It's a draw!")
false
a02b63ddac85f5512c8e4ac7de66904911865d06
W-Thurston/Advent-of-Code
/2021/Day_02/Day_2_Dive_Part_1.py
2,289
4.34375
4
""" --- Day 2: Dive! --- Now, you need to figure out how to pilot this thing. It seems like the submarine can take a series of commands like forward 1, down 2, or up 3: forward X increases the horizontal position by X units. down X increases the depth by X units. up X decreases the depth by X units. Note that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect. The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example: forward 5 down 5 forward 8 up 3 down 8 forward 2 Your horizontal position and depth both start at 0. The steps above would then modify them as follows: forward 5 adds 5 to your horizontal position, a total of 5. down 5 adds 5 to your depth, resulting in a value of 5. forward 8 adds 8 to your horizontal position, a total of 13. up 3 decreases your depth by 3, resulting in a value of 2. down 8 adds 8 to your depth, resulting in a value of 10. forward 2 adds 2 to your horizontal position, a total of 15. After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.) Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? To begin, get your puzzle input (Day_2_Dive.txt). Answer: 1840243 """ ## Code Starts here horizontal_pos = 0 depth = 0 ## Read in input data with open('Day_2_Dive.txt', 'r') as f: file = f.readlines() ## For each instruction from the data file for lines in file: lines = lines.strip() if "forward" in lines: lines = lines.replace('forward ','') horizontal_pos += int(lines) elif "up" in lines: lines = lines.replace('up ','') ## Depth can not be less than 0, it's a submarine if int(lines) > depth: depth = 0 else: depth -= int(lines) elif "down" in lines: lines = lines.replace('down ','') depth += int(lines) print(f"Horizontal Position: {horizontal_pos}") print(f"Depth: {depth}") print(f"Answer: {horizontal_pos*depth}")
true
bfb652db9145bce6b77152ac4949a8b2b2ee9dcc
W-Thurston/Advent-of-Code
/2021/Day_02/Day_2_Dive_Part_2.py
2,662
4.40625
4
""" --- Part Two --- Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated. In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought: down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by your aim multiplied by X. Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction. Now, the above example does something different: forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change. down 5 adds 5 to your aim, resulting in a value of 5. forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40. up 3 decreases your aim by 3, resulting in a value of 2. down 8 adds 8 to your aim, resulting in a value of 10. forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60. After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.) Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? Input: Day_2_Dive.txt Answer: 1727785422 """ ## Code Starts here horizontal_pos = 0 aim = 0 depth = 0 ## Read in input data with open('Day_2_Dive.txt', 'r') as f: file = f.readlines() ## For each instruction from the data file for lines in file: lines = lines.strip() if "up" in lines: lines = int(lines.replace('up ','')) aim -= lines elif "down" in lines: lines = int(lines.replace('down ','')) aim += lines elif "forward" in lines: forward = int(lines.replace('forward ','')) horizontal_pos += forward ## Depth can not be less than 0, it's a submarine depth_change = (forward*aim) if (depth_change<0)&(abs(depth_change) > depth): depth = 0 else: depth += depth_change print(f"Horizontal Position: {horizontal_pos}") print(f"Depth: {depth}") print(f"Answer: {horizontal_pos*depth}")
true
192060ffbd6c4f265a94537ebf579507c4861ef7
saratonite/python-workshop
/basics/08-loops.py
769
4.125
4
#! /usr/bin/python3 # Loops ## For Loop names = ['sarath','billy','daou']; for name in names: print(name) ### using range for i in range(10): print(i) for i in range(1,10): print(i) #### range with steps for j in range(120,150,2): print(j,"Increment by 2") for j in range(170,150,-3): print(j,"Decrement by 3") ## While loop x= 10; while(x>5): x -=1 print("Hey",x) ## Break and Continue lessons = ['print','lists','loops','functions','classes'] for lesson in lessons: if(lesson == "loops"): print("Current lesson is loops") break; else: print("Lesson",lesson,"Not matching") for lesson in lessons : if( not lesson == "functions"): continue; print("Next lesson is ",lesson)
true
b816b5274996372550c5e3287b35c412f3f958b3
LeonidIvanov/checkio-solutions
/elementary/digits_multiplication.py
789
4.34375
4
def digits_multiplication(number): """You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes. For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes). Input: A positive integer. Output: The product of the digits as an integer. Precondition: 0 < number < 106 """ x = 1 for n in str(number): if n != '0': x *= int(n) return x if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert digits_multiplication(123405) == 120 assert digits_multiplication(999) == 729 assert digits_multiplication(1000) == 1 assert digits_multiplication(1111) == 1
true
660965cbcc1cd6ba48d7fa4b2152f5d44f340d69
LeonidIvanov/checkio-solutions
/elementary/even_last.py
1,010
4.1875
4
def even_last(array): """You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Precondition: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) """ if array == []: return 0 sum = 0 for n in array[::2]: sum += n total = sum * array[-1] return total if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert even_last([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30" assert even_last([1, 3, 5]) == 30, "(1+5)*5=30" assert even_last([6]) == 36, "(6)*6=36" assert even_last([]) == 0, "An empty array = 0"
true
b0c468fe0a7281b396e9ea2608a6057490c12330
Eleanorica/hackerman-thebegining
/proj02_loops/proj02_02.py
1,622
4.46875
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... """ #key word is "for" #loop over a range of numbers # sum = 0 # for num in range (0,9): # sum = sum + num # print sum #loop over strings # s = "vsa" # for letter in s: # print letter # if letter == "s": # print "This is an s" # prev = 0 # curr = 1 # nxt = 1 # thismany = raw_input("How many Fibonacci numbers should I generate?") # for num in range (0,int(thismany)): # print curr # nxt = curr + prev # prev = curr # curr = nxt # s = 0 # p = 0 # c = 1 # n = 1 # thismany = raw_input("How many Fibonacci numbers should I generate?") # while s < int(thismany): # print c # n = c + p # p = c # c = n # s = s + 1 # prev = 0 # curr = 1 # thismany = raw_input("How many Fibonacci numbers should I generate?") # for num in range (0,int(thismany)): # print curr # curr = curr + prev # prev = curr - prev # prev = 0 # curr = 1 # nxt = 1 # thismany = raw_input("How many powers of 2 should I generate?") # for num in range (0,int(thismany)): # print curr # nxt = curr*2 # prev = curr # curr = nxt # counter = 1 # thisone = int(raw_input("Input a number and I will find all of the divisors!")) # while counter <= thisone: # if thisone % counter == 0: # print counter # counter = counter + 1
true
83b1e3e0a5d8f27936f6b3322aef1173d04259d3
TWilson2017/GrossPayPython
/GrossPay.py
1,008
4.28125
4
#A program that Calculate and Display the Gross Pay for an Hourly Paid Employee #Define the main function def main(): #1. Get the number of hours worked Hours_Worked = int(input('Enter number of hours worked: ')) # Test for numbers of Hours Worked < 0 while Hours_Worked < 0: # Ask User for Hours Worked again Hours_Worked = int(input('Enter number of hours worked: ')) #2. Get the Hourly Pay Rate Hourly_Pay = float(input('Enter Hourly Pay Rate: ')) # Test for Hourly Pay Rate < 0 while Hourly_Pay < 0.0: # Ask User for Hourly Pay Rate again Hourly_Pay = float(input('Enter Hourly Pay Rate: ')) #3. Multiply number of hours worked by hourly pay rate Gross_Pay = float(Hours_Worked * Hourly_Pay) #4. Display result of calculation print('Your Gross Pay for the Week is: ', Gross_Pay) #main_function # Call the main function main() # Print the copyright notice declaring authorship. print("\n(c) 2018, Tishauna Wilson\n\n")
true
a6476be7fb4a3012aee63e750fa231726ebc016b
Abhijith-1997/pythonprojects
/operators/oper2.py
290
4.15625
4
#Relational operators #<><=>= #comparison operators #true/false # num1=int(input("enter the first number")) # num2=int(input("enter the second number")) # print(num1!=num2) #true value 1 #false value 0 num1=int(input("enter number")) num2=int(input("enter the num")) print(num1>num2)
true
4b0461f0375eab33f532c80f7d6f3ce869d5cf0e
Abhijith-1997/pythonprojects
/files/textfiles.py
280
4.34375
4
# # file reading # f=open("textfile","r") # for i in f: # print(i) # file writing # f=open("textfile","w") # f.write("12345") # without creating file # f=open("abc.txt","w") # f.write("12345") # write and append doing same function f=open("textfile","a") f.write("12345")
false
f6eb493d6b5342163e3217f93e88a630c4ffc742
Jhangsy/LPHW
/ex33.1_factorial_test.py
308
4.28125
4
def factorial(num): i = 1 factoria = 1 if num == 0: return 1 elif num > 0: while i <= num: factoria = factoria * i i = i + 1 return factoria else: return "No factorial!" print factorial(0) print factorial(-3) print factorial(3)
false
801a3e94f1ef647ab20ff1a769f15bb7bde0f246
beregok/pythontask
/task/w2/practic/6-n chisel.py
680
4.28125
4
# Дано три цілих числа. Визначте, скільки серед них збігаються. Програма повинна вивести одне з чисел: 3 (якщо все збігаються), 2 (якщо два збігається) або 0 (якщо все числа різні). # # ## Формат введення # # Вводяться три цілих числа. # # ## Формат виведення # # Виведіть відповідь до задачі. a = int(input()) b = int(input()) c = int(input()) if (a == b) and (a == c) and (b == c): print(3) elif (a == b) or (a == c) or (b == c): print(2) else: print(0)
false
36b7d6512c1824f06a300b9bb0721769b274e2cc
beregok/pythontask
/task/w8/lecture.py
2,005
4.3125
4
# Перша програма яка виводить Привіт світ! print("Привіт, світ!") # Арифметичні обчислення print(1+2+3+4+5) # Об'єднання рядків print('1'+'2') print("2 + 3 =", 2+3) # Арифметичні обчислення print(1+2+3+4+5) # Розділювач, та об'єднання рядків print("1", "2", "3", sep="+", end=" ") print("=", 1+2+3) # Арифметичні операції print(11+6) print(11-6) print(11*6) print(11//6) # ділення на ціло print(11/6) print(11%6) # Остача від ділення print(11**2) # Степінь # Задача про годинник і застосування остачі від ділення print((23+8)%24) print((7-8)%24) # Обернена задача # Фізичний зміст speed = 108 # Швидкість speed2 = -5 # Поправка спідометра time = 12 # Час dist = time*(speed+speed2) # Пройдена дистанція print(dist) # Рядкові операції phraza = "Hasta la vista" who = "Baby" print(phraza,", ", who, sep='') ans = 2+3 expr = '2 + 3 =' print(expr + str(ans)) print(id(ans)) # Добуток рядків print("abc"*6) # Введення даних name = input() print("Hello,", name) # Сума двох чисел a1 = int(input()) # Перетворення в число a2 = int(input()) print(a1+a2) # Перетворення в число print(int('100'*100)) # Змінні a = int(input()) b = int(input()) c = int(input()) d = int(input()) cost1 = a*100 + b cost2 = c*100 + d totalCost = cost1 + cost2 print(totalCost // 100, totalCost % 100) # 0-255 n = int(input()) print(n % 256) # Вивід останньої цифри числа n = int(input()) k = int(input()) print(n//100**k) # Ділення двох чисел a = int(input()) b = int(input()) print((a+b-1)//b) print((a-1)//b+1)
false
607a16ba7faf62b5fa060bc4261f86df63f854be
beregok/pythontask
/task/w1/practic/14-next-previus number.py
848
4.125
4
# Напишіть програму, яка зчитує ціле число і виводить текст, аналогічний наведеному в прикладі (прогалини важливі!). Не можна користуватися конкатенацієй рядків (використовуйте print з декількома параметрами). ## Формат введення # Вводиться ціле число (гарантується, що число знаходиться в діапазоні від -1000 до +1000). ## Формат виведення # Виведіть два рядки, відповідно до зразка. n = int(input()) print("The next number for the number ", n, " is ", n+1, ".", sep="") print("The previous number for the number ", n, " is ", n-1, ".", sep="")
false
e822f2477cb9139c22010580a496701108612f3b
beregok/pythontask
/task/w2/practic/7-monte kristo.py
1,174
4.15625
4
#За багато років ув'язнення в'язень замку Іф виконав в стіні прямокутний отвір розміром D × E. Замок Іф складний з цегли, розміром A × B × C. Визначте, чи зможе в'язень викидати цеглини в море через цей отвір, якщо сторони цегли повинні бути паралельні сторонам отвори. #Формат введення #Програма отримує на вхід числа A, B, C, D, E. #Формат виведення #Програма повинна вивести слово YES або NO. a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) if a > 0 and b > 0 and c > 0 and d > 0 and e > 0: if a <= d and b <= e: print("YES") elif a <= e and b <= d: print("YES") elif b <= d and c <= e: print("YES") elif b <= e and c <= d: print("YES") elif a <= d and c <= e: print("YES") elif a <= e and c <= d: print("YES") else: print("NO") else: print("NO")
false
de7634f482ea3720b88610d28484805fb8693ea0
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x0D-RNNs/0-rnn_cell.py
2,107
4.1875
4
#!/usr/bin/env python3 """File that contains the Class RNNCell""" import numpy as np class RNNCell(): """Class that represents a cell of a simple RNN""" def __init__(self, i, h, o): """ class constructor Args: i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs Creates the public instance attributes Wh, Wy, bh, by that represent the weights and biases of the cell Wh and bh are for the concatenated hidden state and input data Wy and by are for the output The weights should be initialized using a random normal distribution in the order listed above The weights will be used on the right side for matrix multiplication The biases should be initialized as zeros """ self.Wh = np.random.normal(size=((i + h), h)) self.Wy = np.random.normal(size=(h, o)) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) def forward(self, h_prev, x_t): """ Public instance method that performs forward propagation for one time step Args: x_t is a numpy.ndarray of shape (m, i) that contains the data input for the cell m is the batche size for the data h_prev is a numpy.ndarray of shape (m, h) containing the previous hidden state The output of the cell should use a softmax activation function Returns: h_next, y h_next is the next hidden state y is the output of the cell """ def softmax(x): """Function that perform the softmax function""" e_x = np.exp(x - np.max(x, axis=1, keepdims=True)) softmax = e_x / e_x.sum(axis=1, keepdims=True) return softmax concatenation = np.concatenate((h_prev, x_t), axis=1) h_next = np.tanh(np.matmul(concatenation, self.Wh) + self.bh) y = softmax(np.matmul(h_next, self.Wy) + self.by) return h_next, y
true
cb5064fefe8627c161a823ed65d57611de7888d0
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x07-cnn/1-pool_forward.py
2,124
4.15625
4
#!/usr/bin/env python3 """File that contains the function pool_forward""" import numpy as np def pool_forward(A_prev, kernel_shape, stride=(1, 1), mode='max'): """ Function that performs forward propagation over a pooling layer of a neural network Args: A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer m is the number of examples h_prev is the height of the previous layer w_prev is the width of the previous layer c_prev is the number of channels in the previous layer kernel_shape is a tuple of (kh, kw) containing the size of the kernel for the pooling kh is the kernel height kw is the kernel width stride is a tuple of (sh, sw) containing the strides for the pooling sh is the stride for the height sw is the stride for the width mode is a string containing either max or avg, indicating hether to perform maximum or average pooling, respectively Returns: the output of the pooling layer """ m, h_prev, w_prev, c_prev = A_prev.shape kh, kw = kernel_shape sh, sw = stride conv_height = int((h_prev - kh) / sh) + 1 conv_wide = int((w_prev - kw) / sw) + 1 convolutionary_image = np.zeros((m, conv_height, conv_wide, c_prev)) for i in range(conv_height): for j in range(conv_wide): if mode == 'max': convolutionary_image[:, i, j] = (np.max(A_prev[:, i * sh:((i * sh) + kh), j * sw:((j * sw) + kw)], axis=(1, 2))) elif mode == 'avg': convolutionary_image[:, i, j] = (np.mean(A_prev[:, i * sh:((i * sh) + kh), j * sw:((j * sw) + kw)], axis=(1, 2))) return convolutionary_image
true
8d2d7c499358b08cea4fd4c350bead222a568644
AndrewMiranda/holbertonschool-machine_learning-1
/math/0x06-multivariate_prob/multinormal.py
2,602
4.1875
4
#!/usr/bin/env python3 """File that contains the class MultiNormal""" import numpy as np class MultiNormal(): """ Multinormal class that represents a Multivariate Normal distribution """ def __init__(self, data): """ Init method data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2D numpy.ndarray If n is less than 2, raise a ValueError with the message data must contain multiple data points """ if type(data) is not np.ndarray: raise TypeError('data must be a 2D numpy.ndarray') if len(data.shape) != 2: raise TypeError('data must be a 2D numpy.ndarray') if data.shape[1] < 2: raise ValueError('data must contain multiple data points') d, n = data.shape self.mean = np.mean(data, axis=1).reshape(d, 1) X_mean = data - self.mean self.cov = np.matmul(X_mean, X_mean.T) / (n - 1) def pdf(self, x): """ Public instance method def that calculates the PDF at a data point x is a numpy.ndarray of shape (d, 1) containing the data point whose PDF should be calculated d is the number of dimensions of the Multinomial instance If x is not a numpy.ndarray, raise a TypeError with the message x must be a numpy.ndarray If x is not of shape (d, 1), raise a ValueError with the message x must have the shape ({d}, 1) Returns the value of the PDF """ if type(x) is not np.ndarray: raise TypeError('x must be a numpy.ndarray') if len(x.shape) != 2: raise ValueError('x must have the shape ({}, 1)'. format(self.cov.shape[0])) if x.shape[1] != 1: raise ValueError('x must have the shape ({}, 1)'. format(self.cov.shape[0])) if x.shape[0] != self.cov.shape[0]: raise ValueError('x must have the shape ({}, 1)'. format(self.cov.shape[0])) X_mean = x - self.mean d = self.cov.shape[0] det = np.linalg.det(self.cov) inv = np.linalg.inv(self.cov) p_a = 1 / np.sqrt(((2 * np.pi) ** d) * det) p_b1 = np.dot(-(X_mean).T, inv) p_b2 = np.dot(p_b1, X_mean / 2) p_c = np.exp(p_b2) pdf = float(p_a * p_c) return pdf
true
8c1d16d50dfbe2fc7ece2056adfacbf1d4a6f857
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x07-cnn/0-conv_forward.py
2,468
4.28125
4
#!/usr/bin/env python3 """File that contains the function """ import numpy as np def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)): """ Function that performs forward propagation over a convolutional layer of a neural network Args: A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer m is the number of examples h_prev is the height of the previous layer w_prev is the width of the previous layer c_prev is the number of channels in the previous layer W is a numpy.ndarray of shape (kh, kw, c_prev, c_new) containing the kernels for the convolution kh is the filter height kw is the filter width c_prev is the number of channels in the previous layer c_new is the number of channels in the output b is a numpy.ndarray of shape (1, 1, 1, c_new) containing the biases applied to the convolution activation is an activation function applied to the convolution padding is a string that is either same or valid, indicating the type of padding used stride is a tuple of (sh, sw) containing the strides for the convolution sh is the stride for the height sw is the stride for the width """ (m, h_prev, w_prev, c_prev) = A_prev.shape (kh, kw, c_prev, c_new) = W.shape sh, sw = stride pw, ph = 0, 0 if padding == "same": ph = int(((h_prev + 2 * ph - kh) / sh) + 1) pw = int(((w_prev + 2 * pw - kw) / sw) + 1) padding_image = np.pad(A_prev, pad_width=((0, 0), (ph, ph), (pw, pw), (0, 0)), mode="constant") c_height = int(((h_prev + 2 * ph - kh) / sh) + 1) c_wide = int(((w_prev + 2 * pw - kw) / sw) + 1) result = np.zeros((m, c_height, c_wide, c_new)) for i in range(c_height): for j in range(c_wide): for z in range(c_new): v_start = i * sh v_end = v_start + kh h_start = j * sw h_end = h_start + kw img_slice = padding_image[:, v_start:v_end, h_start:h_end] kernel = W[:, :, :, z] result[:, i, j, z] = (np.sum(np.multiply(img_slice, kernel), axis=(1, 2, 3))) Z = result + b return activation(Z)
true
36eaa7f7be812bad99a3814ddfa70266f732f6cf
Code-Wen/LeetCode_Notes
/484.find_permutation.py
2,802
4.21875
4
# 484. Find Permutation # [Medium] # By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decreasing relationship between two numbers, 'I' represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n (n is the length of the secret signature plus 1). For example, the secret signature "DI" can be constructed by array [2,1,3] or [3,1,2], but won't be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can't represent the "DI" secret signature. # On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, ... n] could refer to the given secret signature in the input. # Example 1: # Input: "I" # Output: [1,2] # Explanation: [1,2] is the only legal initial spectial string can construct secret signature "I", where the number 1 and 2 construct an increasing relationship. # Example 2: # Input: "DI" # Output: [2,1,3] # Explanation: Both [2,1,3] and [3,1,2] can construct the secret signature "DI", # but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3] # Note: # The input string will only contain the character 'D' and 'I'. # The length of input string is a positive integer and will not exceed 10,000 class Solution: def findPermutation(self, s: str) -> List[int]: def simplePermutation(prev, inc, dec): """ Return a list of unique numbers from prev+1 to prev+inc+dec inclusive, such that the first inc steps are increasing followed by dec number of decreasing steps """ if inc > 1: return [i for i in range(prev+1, prev+inc)]+[prev+inc+dec]+[j for j in range(prev+dec+inc-1, prev+inc-1,-1)] else: return [prev+inc+dec]+[j for j in range(prev+inc+dec-1, prev,-1)] prev, pos, inc, dec = 0, 0, 0, 0 while pos < len(s) and s[pos] == 'D': pos += 1 dec += 1 if dec: res, restart, inc, dec, prev = [i for i in range(dec+1,0,-1)], False, 0, 0, dec+1 else: res, restart, prev = [1], False, 1 while pos < len(s): if s[pos] == 'I': if restart: res += simplePermutation(prev, inc, dec) prev += inc+dec inc, dec, restart = 1, 0, False else: inc += 1 else: dec += 1 restart = True pos += 1 if inc: res += simplePermutation(prev, inc, dec) return res
true
757550c61149f18242b9df2713ab8e74e5df6d98
UWPCE-PythonCert/Scratchpad
/dynamic_strings/dynamic_strings.py
680
4.46875
4
#!/usr/bin/env python """ code for dynamic string formatting script """ # old style: "My name is %s and I am %ift %iin tall" % ("Chris", 5, 10) "My name is {:s} and I am {:d}ft {:d}in tall".format("Chris", 5, 10) english = "My name is {:s} and I am {:d}ft {:d}in tall" french = "Je m'appelle {:s} et je suis {:d}ft {:d}in tall" def use_format_string(formatter): name = "Fred" height = (5, 10) return formatter.format(name, *height) def display_items(seq): print("There are 3 items, and they are: {}, {}, {}".format(*seq)) def display_items(seq): l = len(seq) return ("There are {} items, and they are: " + ", ".join(["{}"] * l)).format(l, *seq)
false
c698ec4a2bfd2b8fbe24a3f931709c4166e84e50
devbaggett/animal
/animal.py
2,099
4.40625
4
# Assignment title print "\n----------Assignment: Animal----------\n" # instantiate parent class: "Animal" with the following properties/attributes: class Animal(object): # this method to run every time a new object is instantiated def __init__(self, name): self.name = name self.health = 100 def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "Animal name: {}\nHealth: {}".format(self.name, self.health) return self # create instance of class: "Animal" animal1 = Animal("Mr. Higgins") # Animal1 instance title separator print "\n-----Animal 1-----" # gives Animal1 instance some methods to follow and displays info animal1.walk().walk().walk().run().run().displayHealth() # instantiate Animal child class: "Dog" class Dog(Animal): def __init__(self, name): # use super to call the Animal parent __init__ method super(Dog, self).__init__(name) self.health = 150 def pet(self): self.health += 5 return self def displayHealth(self): print "Dog name: {}\nHealth: {}".format(self.name, self.health) # create child instance from parent class: "Animal" dog1 = Dog("Zoe") # Dog1 separator print "\n-----Dog 1-----" # give dog some method instructions and display health and name dog1.walk().walk().walk().run().run().pet().displayHealth() # instantiate Animal child class: "Dragon" class Dragon(Animal): def __init__(self, name): # use super to call the Animal parent __init__ method super(Dragon, self).__init__(name) self.health = 170 def fly(self): self.health -= 10 return self def displayHealth(self): print "Dragon name: {}\nHealth: {}".format(self.name, self.health) # create instance of Dragon subclass dragon1 = Dragon("Gizmo") # dragon1 separator print "\n-----Dragon 1-----" # give dragon1 some instructions and display info dragon1.fly().displayHealth() # create instance of parent class: "Animal" animal2 = Animal("Garfield") # animal2 separator print "\n-----Animal 2-----" # display animal2 info animal2.displayHealth() # bottom separator print ""
true
4ac13cbe272d8ed915e0bc275a03603d1ee11265
tlee0058/python_basic
/compare_lists.py
1,690
4.59375
5
# # Assignment: Type List # # Write a program that takes a list and prints a message for each element in the list, based on that element's data type. # # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the list contains. If it contains only one type, print that type, otherwise, print 'mixed'. # # Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get? # Assignment: Compare Lists # Write a program that compares two lists and prints a message depending on if the inputs are identical or not. # Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." Try the following test cases for lists one and two: list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] # list_one = [1,2,5,6,5] # list_two = [1,2,5,6,5,3] # list_one = [1,2,5,6,5,16] # list_two = [1,2,5,6,5] # list_one = ['celery','carrots','bread','milk'] # list_two = ['celery','carrots','bread','cream'] def compare_list(list_one, list_two): if not len(list_one) == len(list_two): print "The lists are not the same" else: for i in range(0, len(list_one)): if not list_one[i] == list_two[i]: print "The lists are not the same" return print "The lists are the same" compare_list(list_two, list_one)
true
b57e720e88e92fca04af4c9dc1f900a2c7c84802
tlee0058/python_basic
/stars.py
1,015
4.3125
4
"""Assignment: Stars Write the following functions. Part I Create a function called draw_stars() that takes a list of numbers and prints out *. For example: x = [4, 6, 1, 3, 5, 7, 25] draw_stars(x) should print the following when invoked:""" """x = [4, 6, 1, 3, 5, 7, 25] def draw_stars(x): star = "*" for i in x: i *= star print i draw_stars(x) Part II Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string according to the example below. You may use the .lower() string method for this part.""" x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] def draw_stars(x): star = "*" for i in x: if type(i) == int: i *= star print i if type(i) == str: i = i[0].lower() * len(i) print i draw_stars(x)
true
b6c6fb47fba539be980f1ae7a7da65a93d4dff87
Little-Captain/py
/Automate The Boring Stuff With Python/04/02-myPets.py
385
4.125
4
#!/usr/bin/env python myPets = ['Zophie', 'Pooka', 'Fat-tail'] print('Enter a pet name: ') name = input() if name not in myPets: print('I do not hava a pet named ' + name) else: print(name + ' is my pet.') # 多重赋值技巧 cat = ['fat', 'black', 'loud'] # 变量的数目和列表的长度必须严格相等 size, color, disposition = cat print(size, color, disposition)
false
514f9a5bcdedccaa7022106f3b938b7907a16a0b
Little-Captain/py
/PyQt/string3.py
320
4.25
4
s = "Hello World!" print("Original String is", s) print('String after toggling the case:', s.swapcase()) print("String in uppercase is", s.upper()) if s.istitle(): print("String in lowercase is", s.lower()) print("String,", s, "is in title case:", s.istitle()) print("String in capitalized form is", s.capitalize())
false
e03fff4f987d92b711cbfeea5aea28ded2a39e78
Little-Captain/py
/PyQt/stringfunc2.py
416
4.375
4
s = input("Enter a sentence: ") print('The original sentence is:', s) if s.startswith('It'): print('The entered sentence begins with the word It' ) if s.startswith('It', 0, 2): print('The entered sentence begins with the word It' ) if s.endswith('today'): print('The entered sentence ends with the word today' ) if s.endswith('today', 10, 15): print('The entered sentence ends with the word today' )
true
6ff1651af0ae50b937f2453062e1599a44ddd136
Little-Captain/py
/PyQt/breaking.py
699
4.15625
4
s = 'education ' k = s.partition('cat') print('The word', s, 'is partitioned into three parts') print('The first part is', k[0], 'separator is', k[1], 'and the third part is',k[2]) t = input('Enter a sentence: ') print('The original sentence is', t) print('The sentence after replacing all the characters "a" by "#" is:',\ t.replace('a', '#')) print('The sentence after replacing first three "a" characters by "#" is:',\ t.replace('a', '#', 3)) u = t.split(' ') print('The words in the entered sentence are', u) print('The words in the entered sentence are') for i in range(0, len(u)): print(u[i]) u = t.split(' ',1) print('The sentence is split into two parts:', u[0], 'and', u[1])
false