blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fccc80fd3e15132cec6df9511b811ba43453700a
williamboco21/pythonfundamentals
/FUNDPRO/MP-02.py
257
4.125
4
def change_word(ow, s, tr): print(ow.replace(s, tr)) original_word = input("Enter the word: ") sub = input("Enter the substring: ") to_replace = input("Enter the string to replace the substring: ") print("") change_word(original_word, sub, to_replace)
true
814894a33b070c62540498503cdce6698b7669dc
williamboco21/pythonfundamentals
/FUNDPRO/arrays-to-functions.py
423
4.15625
4
def multiply_by_2(nums): for i in range(len(nums)): nums[i] *= 2 numbers = [] for i in range(5): num = int(input(f"Enter number {i+1}: ")) numbers.append(num) print("\nThe contents of the array are: ") for i in range(len(numbers)): print(numbers[i], end=" ") multiply_by_2(numbers) print("\n\nThe new contents of the array are: ") for i in range(len(numbers)): print(numbers[i], end=" ")
false
50916d56430f15a9ef6f83c07d0301d7ad35f16b
toadereandreas/Babes-Bolyai-University
/1st semester/Fundamentals-of-programming/Assignment 1/A4.py
2,480
4.34375
4
def read(): ''' The function reads the value of x. Input : x, an integer Preconditions : x must be a natural number => x >= 0 Output : x, an integer Postconditions : - ''' print('Enter the value of x : ') x = input() while True: try : x = int(x) # Checking if we can convert it into an integer. break # If yes, we break the while loop. except ValueError as xx : # If not, we re-enter the value for x x = input('Enter a number, not a string :') while x < 0 : # Checking if x is a natural number and # re-enter it until it is. print('Enter a natural number !') x = input() x = int(x) return x def create_largest_number(x): ''' The function determines the largest number that can be formed with the figures of x. Input : x, an integer Preconditions : - Output : number, the result Postconditions : - ''' figuresList = [0,0,0,0,0,0,0,0,0,0] # We create the list where all the # digits of x will be placed. while x > 0 : figuresList[x%10] = figuresList[x%10] + 1 # We take the last digit of # x and add it to the list. x = x / 10 # We then eliminate the last digit. x = int(x) # We then reconvert x back to an integer. number = 0 # number will be the resulted number. digit = 9 while digit != -1 : while figuresList[digit] != 0: number = number * 10 + digit figuresList[digit] = figuresList[digit] - 1 digit = digit - 1 return number def ui(): ''' The function reads a natural number and finds the largest natural number written with the same digits. Input : - Preconditions : - Output : - Postconditions : - ''' a = read() # Read the value of the given number. x = create_largest_number(a) a = str(a) print('The largest number that can be written with the same digits as '+ a + ' is :' ) print(x) def test_function(): ''' The function determines whether the function create_largest_number works properly or not. Input : - Preconditions : - Output : - Postconditions : ''' assert create_largest_number(234)==432 assert create_largest_number(22) == 22 assert create_largest_number(104)==410 test_function() ui()
true
f9bc4a438050fe843e2f93c4f5f0dddcbb7bedb8
vincyf1/pythonproject
/concepts/insertion_sort.py
358
4.1875
4
# Algorithm: Insertion Sort # Order of Complexity: O(n^2) def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = key print(arr) my_array = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] insertion_sort(my_array)
false
643803be6152c73ae18cbf5e5d6601ba258f2207
johngriffin21/Python-Programming-Computer-Programming-III
/Iteration_with_hash_set.py
1,196
4.125
4
#Add an __iter__() method to the HashSet class so the Hash Set can be iterated. For an example, see the LinkedList code from a previous question. Note that you don't have to worry about the order of the elements. from LinkedList import LinkedList class HashSet: def __init__(self, capacity=10): # Create a list to use as the hash table self.table = [None] * capacity def add(self, item): # Find the hash code h = hash(item) index = h % len(self.table) # Check is it empty if self.table[index] == None: self.table[index] = LinkedList() # Need a new linked list for this entry if item not in self.table[index]: # Only add it if not already there (this is a set) self.table[index].add(item) # Provide an iterator function def __iter__(self): a = [] ptr = None for i in range(0,len(self.table)): if self.table[i]: ptr = self.table[i].head while ptr != None: a.append(ptr.item) ptr = ptr.next yield from sorted(a)
true
f7c68056def39f88a1482984d87387df2231a7bd
eduardorasgado/AlgorithmsX
/introduction/bubble_sort.py
344
4.125
4
#!/usr/bin/env python3 def bubble_sort(A): for i in range(len(A)-1): j_list = [i for i in range(i+1, len(A))] j_list.reverse() # for j = A.length downto i + 1 for j in j_list: if A[j] < A[j-1]: A[j], A[j-1] = A[j-1], A[j] A = [9,8,5,7,4,6,1,2,3] print(A) bubble_sort(A) print(A)
false
0ef00573ca11ebfac5f8e656888bfe1ac73adc37
mariesstl/SWDV-610-3W-20SP2
/Lesson 3/fibo_iterative.py
560
4.25
4
import time def fibonacciloop(number): print("fibonacci evaluation of: {0}".format(numbertoevaluate)) if number == 0: return 0 if number == 1: return 1 sequence = [0, 1]#Always starts with 0 and 1 for i in range(2,number+1): sequence.append(sequence[i-1] + sequence[i-2])#Add the previous two elements together, then append their sum to the list. print("Fibonacci Sequence: ", sequence) return sequence[number] numbertoevaluate = 10 fibonacciloop(numbertoevaluate)
true
e93c006c3f8073a56551f673a14ef6aada860bbf
mariesstl/SWDV-610-3W-20SP2
/Lesson 3/recursiveFibonacciWithTimings.py
671
4.34375
4
# Python program to display the Fibonacci sequence up to n-th term using recursive functions import time def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) # Change this value for a different result nterms = 30 # uncomment to take input from the user #nterms = int(input("How many terms? ")) # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") start = time.time() for i in range(nterms): recur_fibo(i) end = time.time() print ("time taken:{0:>10.7f}".format(end-start))
true
8761dc56015c048668a0a0a526665d77080ed184
mariesstl/SWDV-610-3W-20SP2
/Lesson 1/is_multiple.py
541
4.28125
4
''' is_multiple(n, m), that takes two integer values and returns True is n is a multiple of m, that is, n = mi for some integer i, and False otherwise. ''' def is_multiple(integerMultiple, integer): integerMultiple = int(input("Enter an integer to evaluate for a multiple: ")) integer = int(input("Enter an integer to evaluate as a multiple of the previous integer: ")) if integerMultiple % integer == 0: print(True) else: print(False) def main(): is_multiple(15,5) main()
true
bece58399c4352a6fa40e23b002b4fab4411386c
mariesstl/SWDV-610-3W-20SP2
/Lesson 5/insertionsort.py
780
4.375
4
# Consider the following list of integers: [1,2,3,4,5,6,7,8,9,10]. # Show how this list is sorted by the following algorithms: # insertion sort def insertionSort(alist): for index in range(1,len(alist)): #skip position 0. Move right and we assume a sorted sublist at 0 currentvalue = alist[index] #Get current value. position = index #Get current position. while position>0 and alist[position-1]>currentvalue: #if not at beginning and value to left is greater than current value alist[position]=alist[position-1]#put that value here position = position-1 #move one position to the left alist[position]=currentvalue#put current value there alist = [1,9,3,4,8,10,7,5,2,6] print('unsorted', alist) insertionSort(alist) print('sorted',alist)
true
a82e1b1089590bff61949e22d2d24adb8ed8b14d
Hamza29199/A-New-Dawn
/CollatzConjecture.py
1,405
4.46875
4
"""A bit of background first-the Collatz Conjecture defines the following sequence; take any positive integer "n", if it's even, divide it by 2, otherwise multiply it by 3 and add 1 to it. You do the same for whatever result you obtain, and keep going. The conjecture, intro duced by Lothar Collatz in 1937, says that no matter what positive integer you start with, you will eventually reach 1. It's one of the unsolved problems of mathematics, and while this program doesn't come up with a beautiful proof, it does print out all the terms and the number of steps it takes for any integer to be eventually reduced to 1, as per the Collatz sequence.""" n=input("ENTER NUMBER: ") #taking user input for n here steps=0 #initializing integer variable steps while x!= 1: if int(x) %2 == 0 and x!=1: x=int(x)/2 #if n, and any other succesive term, is even, it's halved steps+=1 print(x) #for clarity, I've decided to print out every succesive term obtained in the sequence if int(x)%2!=0 and x!=1: x=(3*int(x))+1 #if n, and any other succesive term, is odd, it's multiplied by 3 and 1 added to result steps+=1 print(x) #subtracting 1 because the program also counts the step at which 1 is reached, whereas I just want to display the no. of steps leading up #to 1. print("Conjecture ends after %d steps" % (int(c)-1))
true
8936cadc7b4378462e071cd7458175782cf1f3f7
josephwanderer/JosephWandererHW1
/PythonModules/TablePrinterGeneral.py
1,890
4.375
4
import copy tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): workTable = copy.deepcopy(table) # Making a dummy variable to derive attributes of the original list without altering the original list colWidths = [0] * len(workTable) # Initializes a list with a number of values equal to the number of inner lists in the table. This makes a spot to store the highest length of strings in each inner list. for i in range(len(workTable)): for j in range(len(workTable[i])): workTable[i].sort(key=len,reverse=True) # Sorts the strings in each inner list by length(because key=len), with longest first(because reverse=True) colWidths[i] = len(workTable[i][0]) # Stores the length of the largest string of each list(which is at index 0 because of the sorting) in the colWidths list orderedTable = [] # Initializes a variable to store a list of lists of strings. Each list of strings is a row to be printed for a in range(len(table[0])): # I'm using len(table[0]), ie. the length of the first list in the table, because I'm assuming the all the lists are of equal length orderedTable.append([]) # Appends an empty list for each row to be printed for b in range(len(table)): orderedTable[a].append(table[b][a]) # Fills each new empty list with the strings for each row in order for x in range(len(orderedTable)): for y in range(len(colWidths)): print(orderedTable[x][y].rjust(colWidths[y] + 1),end='') # Prints each row with amount of justification pulled from colWidths list, plus 1 for a space between columns. end="" prevents printing a new line in the middle of a row. print('') # Prints a new line after a row to separate rows. printTable(tableData)
true
c6155a031b1a09a293b68ed5857850315c17f4b1
flaviu2001/University-Projects
/Semester 1/Fundamentals of Programming/Labs/Assignment 1/set 2.py
287
4.25
4
def fibo(n): ''' This function takes an integer parameter n and returns the first fibonacci number larger than n ''' a = 1 b = 1 if n < 1: return 1 while b <= n: c = a+b a = b b = c return b n = int(input('input the value of n ')) print('The answer is ' + str(fibo(n)))
true
f2341d60a7f0d4c00b73bc372c5d7a114a719d4d
googleberk/CS61ASp2019Self1
/Core01Week/dis01/dis.py
1,011
4.28125
4
# Question 1.1: # Alfonso will only wear a jacket outside if it is below 60 degrees or it is raining. # Write a function that takes in the current temperature and a boolean value telling # if it is raining and returns True if Alfonso will wear a jacket and False otherwise. def wears_jacket_with_if(temp, raining): """ >>> wears_jacket_with_if(90, False) False >>> wears_jacket_with_if(40, False) True >>> wears_jacket_with_if(100, True) True """ return temp < 60 or raining # Question 1.3: # Write a function that returns True if a positive integer n is a prime number and False otherwise. def is_prime(n): """ >>> is_prime(10) False >>> is_prime(7) True """ if n == 1: return False i = 2 while i < n: if n % i == 0: return False i += 1 return True # back notes: Alternatively, the while loop’s conditional expression could # ensure that i is less than or equal to the square root of n.
true
acb59fbfe2df919894a0ee7dfa76f259a2f52ee2
EnderCaster/MyGitExperimentSpace
/python_path/python3_brief_tutorial/11_student_teacher.py
1,056
4.5
4
#!/usr/bin/env python3 # -*- utf-8 -*- # and a class can extends more than one class # dont use getters and setters in python class Person(object): """person is a base class """ def __init__(self,name): self.name=name def get_details(self): return self.name class Student(Person): """extends Person """ def __init__(self,name,branch,year): """use var self as usual, nothing special """ Person.__init__(self,name) self.branch=branch self.year=year def get_details(self): return "{} studies {} and is in {} year".format(self.name,self.branch,self.year) class Teacher(Person): def __init__(self,name,papers): Person.__init__(self,name) self.papers=papers def get_details(self): return "{} teaches {}".format(self.name,",".join(self.papers)) person=Person("Sachin") student=Student("Kushal","CSE",2005) teacher=Teacher("Prashad",["c","C-fuck"]) print(person.get_details()) print(student.get_details()) print(teacher.get_details())
true
44422d9a72c8f41288899ce1d616d6947c483b53
Chuckboliver/Data-structure-and-Algorithms
/Tree/BinarySearchTree.py
2,042
4.125
4
""" Binary Search Tree Implement tutorial. """ class Node: """ data node. """ def __init__(self, key: int) -> None: self._key = key self._left = None self._right = None class BST: """ Binary Search Tree obj. """ def __init__(self) -> None: self.__root = None def insert(self, key: int) -> None: """ insert key into BST. """ def __insert_util(root: Node, key: int) -> Node: if root is None: return Node(key) elif key < root._key: root._left = __insert_util(root._left, key) else: root._right = __insert_util(root._right, key) return root self.__root = __insert_util(self.__root, key) def delete(self, key: int) -> None: """ delete key from BST. """ def __delete_util(root: Node, key: int) -> Node: def __deepest_node(root: Node) -> Node: if root is None or root._left is None: return root return __deepest_node(root._left) if root is None: return root elif key < root._key: root._left = __delete_util(root._left, key) elif key > root._key: root._right = __delete_util(root._right, key) else: if root._left is None: temp = root._right root = None return temp elif root._right is None: temp = root._left root = None return temp else: deepest_node = __deepest_node(root._right) root._key = deepest_node._key root._right = __delete_util(root._right, deepest_node._key) return root if __name__ == "__main__": tree = BST() for i in range(int(input())): tree.insert(i)
false
9f0c01695200d779dcd9fe0d9bff5d1260e20b22
dakotabourne373/plp
/NEW/7.10.21.num.dice.py
1,108
4.46875
4
""" Function should do three things: A. take in user input (telling the user the range in which they can guess) (NOTE: obviously make it so if they guess outside the range, it tells them to try again) B. generate random input C. tell user whether or not they're input was correct or not """ def number_guesser(): input("NUMBER GUESSER!!") """ dice_roll should do three things: A. ask user how many sides they want on each dice B. ask user how many dice they want to roll C. return result of roll(s) """ def dice_roll(): input("DICE ROLLLLLL") """ What I did in here is really ugly but it gets the job done, don't take from me!!! When testing you can use number or n and dice or d """ def main(): while(True): route = input("Do you want to Guess the Number or roll some dice? (number/dice)\n") if(route == "number" or route == "n"): number_guesser() break elif(route == "dice" or route == "d"): dice_roll() break else: print("\n\nIncorrect input, try again\n") if (__name__ == '__main__'): main()
true
5492f1f5861c08e456cd7efa33f99adf7727b2d5
zsofii/kiscica
/gyakorlas/iteracio.py
440
4.21875
4
""" d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(key, 'corresponds to', d[key])""" """def one_to_three_doubles(): for num in range(1, 8): yield num, num * 2 x = one_to_three_doubles() for one in x: print(one) x=one_to_three_doubles() print(next(one)) print(next(one)) k = {'x': 1, 'y': 2, 'z': 3} for x in range(0, 3): print("éhfáa") """ d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(d[key]*key)
false
e02f56d9b913303efd6021b7ca914f562c288036
FaizHamid/PyTutorial
/Ch1WhyProg.py
1,838
4.34375
4
# Chapter 1 - Why Program? What do we say? # Programming Language is like learning all other natural language # where Vocabulary = "Variable" and Words = "Reserved Words" # RESERVED WORDS - cannot be use as "Variable Name" / "Identifiers" # These are the reserved words # False # None # True # and # as # assert # break # class # if # def # del # elif # else # except # return # for # from # global # try # import # in # is # lambda # while # not # or # pass # raise # finally # continue # nonlocal # with # yield # SYNTAX - Like sentence structure in natural languages there are "Syntax" with its valid patterns in Python language. x = 2 # Assignment Statement, "x" is a Variable, "2" is a Constant x = x + 2 # Assignment with expression, "=" and "+" are Operators print(x) # Print Statement, "print" is a Reserved Word and also a Function # SCRIPTS - as the paragraphs in natural languages Python has its "Scripts" # Interactive Python is good for experiments and programs of 3 to 4 lines long # Most programs are much longer, so we type them into a file and tell Python to run the commands in the file # In a sentence we are "giving Python a Script" # As a conversation, we add ".py" as the suffix on the end of these files to indicate they contain Python programs. # PROGRAM FLOW - # Like a recipe or installation instruction, a program is a sequence of steps to be done in orders. # Some steps are conditional - they may be skipped. # Sometimes a steps or a group of steps is to be repeated. # Sometimes we store a set of steps to be used over and over as needed several places throughout the program. # When a program is running, it flows from one step to the next. As programmers, we set up "paths" for program to follow. x = 2 print(x) x = x + 2 print(x) # STORY STRUCTURE - constructin a paragraph for a purpose.
true
4d72890eef1cae460a93951c0e69b417028a4be6
FaizHamid/PyTutorial
/Ch5.2LoopPatterns.py
2,293
4.34375
4
# Chapter 5.2 - LOOP PATTERNS # COUNTING - to 'count' how many times we execute a loop, # we introduce a counter variable that starts at '0' and # we add 'one to it each time through the loop'. # Counting in a Loop count = 0 print('Before', count) for thing in [9, 41, 12, 3, 74, 15]: # thing is the iteration variable count = count + 1 print(count, thing) print('After', count) # Summing in a Loop # to add up a value we encounter in a loop, # we introduce a 'sum variable that start at 0' and # we add the 'value' to the sum each time through the loop. sum = 0 print('Before', sum) for thing in [9, 41, 12, 3, 74, 15]: # Thing is the iteration variable add = sum + thing print(sum, thing) # Average in a Loop # An 'average' just combines the counting and sum patterns and divides when the loop is done. count = 0 sum = 0 print('Before', count, sum) for value in [9, 41, 12, 3, 74, 15]: # 'Value' is the iteration variable count = count + 1 sum = sum + value print(count, sum, value) print('After', count, sum, sum / count) # Filtering in a loop # we use an if statement in the loop to catch / filter the values we are looking for. print('Before') for value in [9, 41, 12, 3, 74, 15]: # 'Value' is the iteration variable if value > 20: print('Large number', value) print('After') # BOOLEAN VARIABLE in a Loop # If we just want to search and 'know if a value was found', we use a 'variable' that starts at 'False' and set to 'True' # as soon as we 'find' what we are looking for. found = False print('Before', found) for value in [9, 41, 12, 3, 74, 15]: if value == 3: found = True print(found, value) print('After', found) # Smallest Value # we still have a variable that is the 'smallest' so far. The first time through the loop 'smallest' is 'None'. # so we take the first value to be the smallest. smallest = None print('Before') for value in [9, 41, 12, 3, 74, 15]: if smallest is None: smallest = value elif value < smallest: smallest = value print(smallest, value) print('After', smallest) # IS or IS NOT Operators # Python has a 'IS' operator that can be used in logical expressions. # implies 'IS THE SAME AS' or similar to, but stronger than == # 'IS NOT' also is a logical operator.
true
4e2c0b5e342eef01221904fbdb20535830381f3e
abdullahpsoft/Calculator
/index.py
1,007
4.25
4
def calculation(): operator = input("ChoseOperation \n + For Addition \n - For Subtraction \n * For Multiplication \n / For Division") number_1 = int(input("Enter first number:")) number_2 = int(input("Enter second number:")) if operator == "+": print("Addition: ", number_1 + number_2) elif operator == "-": print("Subtraction: ", number_1 - number_2) elif operator == "*": print("Multiplication: ", number_2 * number_1) elif operator == "/": print("Division: ", number_1 / number_2) else: print("Invalid Operator!!!") cal_again() def cal_again(): chose = input("Use Calculator Again \n Y for Yes \n N for no") if chose.upper()=="Y": calculation() elif chose.upper()=="N": print("See you later\n") else: print("Invalid Input!!!") cal_again() def welcome(): print("Welcome! You are using Calculator with Python") welcome() calculation() print("Thank you for using me!")
false
b4544bb1926b02a4675244154999093539209e15
balazsorban44/NTNU
/2016/Fall/TDT4110/Forelesninger/doorman.py
282
4.125
4
name = input("Hei jeg er THE DOORMAN. What is your name? ") age = int(input("What is your age? ")) drunk = input("Are you drunk? Yes, or No? ") if age>=18: if drunk=="Yes": print("You are drunk, sorry.") else: print("You are in",name) else: print("You are too young")
true
f79e4c2a2596f71617ccdb2131eb0cdb7bf42fac
DMS-online/python3-for-beginners
/python-exercises/print/print.py
632
4.53125
5
''' Given the following two variables name = “John Banks” age = 34 Write a print() statement using the f string notation, substituting the variables where necessary that will display on the console: Hi, my name is John Banks and I am 34 years old ''' name = "John Banks" age = 34 print(f" Hi, my name is {name} and I am {age} years old") ''' Given that x, y = 10, 12 Write the code using the format() command in a print() statement substituting the values of the variables x and y that will display the following on the console The result of 10 + 12 is 22 ''' x, y = 10, 12 print("The result of {} + {} is {}".format(x, y, x+y))
true
db94cf6518f55c40537e524053bef95ad140800d
DMS-online/python3-for-beginners
/python-basics/data-structures-dictionaries.py
972
4.375
4
#Dictionaries movie = { "title" : "Inception", "rating" : "PG-13", "director" : "Christopher Nolan", "stars" : ["Leonardo DiCaprio", "Tom Hardy"] } #Extracting key values print(movie["title"]) print(movie["stars"][1]) print (movie.get("title")) #Change a value movie["rating"] = "PG" #Adding a value movie["runtime"] = 200 print (movie) #Loop through a dictionary #print key names for x in movie: print(x) #print values for x in movie: print(movie[x]) #Loop through keys and values for x, y in movie.items(): print(x,y) #check if key exists if "rating" in movie: print("The movie has a rating") #Adding items movie["year"] = 2010 print(movie) #Removing items movie.pop("year") print(movie) #Remove items with a specified keyword del movie["rating"] print(movie) #Clear a dictionary movie.clear() print(movie) #Delete the whole dictionary del movie #dict() Constructor movie2 = dict (title="Matrix", rating = "PG-13", year=1999) print(movie2)
true
2e661e77d930027368b95baa265afad29cbfa660
DMS-online/python3-for-beginners
/python-exercises/functions/functions.py
919
4.21875
4
''' Write a function that takes as input any number of integer parameters. The function should return a list of the input numbers sorted in descending order ''' def sort_result(*nums) : result = list(nums) result.sort(reverse=True) return result print(sort_result(10,2,3,4,5)) print(sort_result(10,9,8,5)) ''' Write a function that accepts a sting and calculates the number of uppercase letters and lowercase letters in the string. E.g. Input “The weather on Monday in Atlanta is rainy” Output: No of uppercase characters: 3 No of lowercase characters: 31 ''' sentence = "The weather on Monday in Atlanta is rainy" uppercase, lowercase = 0 , 0 for char in sentence: if char.isalpha() and char.isupper(): uppercase += 1 elif char.isalpha() and char.islower(): lowercase += 1 print("No of uppercase characters:", uppercase) print("No of lowercase characters:", lowercase)
true
9fca12aa80390f4cb0910f75c6532b996d233a80
benlands/isat252
/lec3.py
685
4.40625
4
""" Lecture notes for day 3, week 1 """ my_list = [1,2,3,4,5] #print(my_list) #my_nested_list = [1,2,3,my_list] #print(my_nested_list) my_list[0]= 6 #print(my_list[-2]) #print(my_list[:3]) #my_letters = ['a','b','c'] #print(my_letters) #x,y,z = ['a','b','c'] #print(x) #print(y) #print(z) #my_list.append(7) #my_list.remove(7) #print(my_list) #my_list.sort() #print(my_list) #my_list.reverse() #print(my_list) #print(my_list + [8,9]) #my_list.extend(['a','b']) #print('6' in my_list) #print(len(my_list)) #print("hello\tworld") #print("helloworld"[1]) my_letters = ['a', 'a','b', 'b', 'c' ] print(my_letters) my_unique_letters = set(my_letters) print(my_unique_letters)
false
c37c8288412bfd4a6f72fb04859dc8ab50e9b0ae
MarioCastro14/AprendiendoPython
/codigos/Programa 4.py
219
4.15625
4
numero= int(input("Dime un número entre el 1 y el 100:\n")) if numero>=1 and numero<=100: print("Su número está entre el 1 y el 100") else: print("Su número no se encuentra en un rango del 1 al 100")
false
1e816fe0b21dee8f16de5f1c0606b5ba354afe0a
ZacharyGopinath/Year9DesignPythonZG
/Exercise 1 - Console Work/ConVolCylStep2.py
937
4.3125
4
import math #input #numbers needed to find volume of cylinder, height and radius/diameter print("Volume of a Cylinder Formula:") print("\n\tThe volume of a Cylinder is:") print("\n\t\t\tV = \u03C0\u00d7radius\u00b2\u00d7height") print("\n\tThis program will take as input the radius and height") print("\tand print the volume.") name = input("\n\t\t\tWhat is your name: ") #takes users name radius = input("\n\t\t\tInput radius(cm): ") #input radius = (int)(radius) #cast to int height = input("\n\t\t\tInput height(cm): ") #input height = (int)(height) #cast to int #process #what needs to be done to get volume from these numbers volume = math.pi*radius*radius*height volume = round(volume,2) #output #after calculating what number it output print("\n\tHi "+name+"!") print("\n\tGive a cylinder with:") print("\n\tRadius = "+str(radius)) print("\n\tHeight = "+str(height)) print("\n\tThe volume is: "+str(volume))
true
a157607168a95c768a088e708071a7fac3230827
ZacharyGopinath/Year9DesignPythonZG
/Coding Segments/adding_endings.py
208
4.5625
5
#in this example, the input was "venit" str = "Venit" #I then evaluate whether the ending is "it", then add "imus" to conjugate it if str[-2:] == "i": print("str" + "imus") print("Error: Not an -it verb")
true
b683767e75d355bf60e0537a2cdeed7d2c1e3060
maiorovi/PythonCoursera
/src/Variables.py
538
4.1875
4
#illegal names of vairable # 12343name, # python convention is to use underscore symbol in variable names my_name = "Joe Warren" print my_name my_age = 50; print my_age magic_pill = 30; print my_age - magic_pill #Temperature example #convert from Fahrenheit to Celsius #c = 5 / 9 * (f-32) temp_Fahrenheit = 52 temp_celsius = 5.0 / 9.0 * (temp_Fahrenheit - 32) print "Temperature in ceilsius: ", temp_celsius #convert from celsius to fahrenheit temp_celsius = 0 temp_Fahrenheit = 9.0 / 5.0 * temp_celsius + 32 print temp_Fahrenheit
true
f770f275b9ee9ac4384fa426d43f8cb7d1b2ec69
rlorenzini/githubtest
/testwork6.py
655
4.1875
4
#palindrome word = input("\nEnter Word Here: \n").lower() def reverse(word): return word[::-1] def palindrome(word): rev = reverse(word) if word == rev: return True return False result = palindrome(word) if result == True: print("\nPalindrome.\n") else: print("\nNot palindrome.\n") user_input = input("\nEnter Word Here:\n").lower() def reverse(user_input): return user_input[::-1] def testing(user_input): if user_input == reverse(user_input): return True return False returned = testing(user_input) if returned == True: print("\nPalindrome.\n") else: print("\nNot palindrome.\n")
true
ec34f36ec5df0dc2b1ee61846b726d8c2ac5d1bf
ayobablo/Steinserve-python-assignments
/prog.py
372
4.1875
4
print('please input your home address') address=input() if len(address)<5: print ('the length of your address is less than 5') elif len(address)<10: print ('the length of your address is less than 10') elif len(address)<20: print ('the length of the address is less than 20') else: print ('the length of your address is greater than 20')
true
f01e81e6384690cc86df5387eabdf1b33749334f
Bradysm/daily_coding_problems
/editDistance.py
1,311
4.15625
4
# This problem was asked by Google. # The edit distance between two strings refers to the minimum number of character insertions, # deletions, and substitutions required to change one string to the other. # Given two strings, compute the edit distance between them. def edit_distance_help(str1, str2, i, min_len): """ Gives the edit distance between two strings :param str1: first string :param str2: second string :param i: index being compared :return: the number of insertions, deletions, and removes to make the same """ # check if we're at the end of shortest length if min_len is i: return abs(len(str1) - len(str2)) change = 0 if str1[i] is not str2[i]: change = 1 return change + edit_distance_help(str1, str2, i+1, min_len) def edit_distance(str1, str2): if str1 is None and str2 is None: return 0 if str1 is None: return len(str2) if str2 is None: return len(str1) # neither none, calculate edit distance return edit_distance_help(str1, str2, 0, min(len(str1), len(str2))) # prove that it works correctly print(edit_distance("kitty", "abc")) print(edit_distance("kitten", "sitting")) print(edit_distance("brady", "shadyness")) print(edit_distance("abc", None)) print(edit_distance(None, "abc")) print(edit_distance(None, None))
true
20bd57d289350c2852d452a21c4142af8f038e23
Bradysm/daily_coding_problems
/cycleLL.py
1,477
4.125
4
# Given a linked list, determine if it has a cycle in it. # # To represent a cycle in the given linked list, # we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. # If pos is -1, then there is no cycle in the linked list. # This might be one of the weirdest cycle problems that I've ever seen. Most cycle problems, you # can run something like a fast slow and if they ever meet than you know you have a cycle, # you could also do the HashSet where you hash the actual node itself and not just the value # so when you see that object again, you know you have a cycle in the LL # The thin that threw me off was the position, I still really don't understand it so I just put a flag # to check if that position was correct or not. I then just compared to see if I have seen that object # or not using a set. Sets are implemented using hashing so this allows for theoretical O(1) lookup # (depending on the collisions and resolution). If we see that current node in the set, then # we know there is a cycle; return False. Otherwise, if head turns into None, return True. Super easy, # but a very common problem! def hasCycle(head, pos): """ :type head: ListNode :type pos: int :rtype: bool """ if pos == -1: return False seen = set() while head is not None: if head in seen: return False else: seen.add(head) head = head.next return True
true
6bd2b523c6886b0a1a5b674269ece4a5395554ee
Bradysm/daily_coding_problems
/permutationPalindrome.py
2,456
4.34375
4
# Good morning! Here's your coding interview problem for today. #This problem was asked by Amazon. #Given a string, determine whether any permutation of it is a palindrome. #For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome. # daily should return false, since there's no rearrangement that can form a palindrome. # This problem has the ability to become hard because people overthink the problem. When they see it, # they immediately think of the permutation problem and try to generate all possible permutations and # then check to see if that permutation is a palindrome. This is extremly niave and will create # a factorial time complexity which makes any serious software engineer want to barf. We can # reduce this time complexity to O(N) and O(1) space using something called a frequency counter. # So when you look at all palindromes, they have a couple characteristics, but the one that # we care about the most is that all valid palindromes have at most one character that has an odd # frequency. So that means that there can only be one character that is contained in the string # that occurs an odd number of times. Now lets look at how a frequency counter can help us. We can # go through the string and increment the frequency of that character within the frequency counter. # Since we assume a fixed sized alphabet, this will be O(1) space. You can then implement this with # an array and map the ascii values of the character to an index within the array. I'm going # to use a Counter object for simplicty purposes, but I encourage you to try it with an array as well # Once we get all the characters frequencies, we then check to make sure there is only one character # with an odd frequency. If there is more than one, then we return false, if there is one or less, then # we return true from collections import Counter def permutation_palindrome(string): return valid_odd_frequencies(Counter(string)) def valid_odd_frequencies(counter): valid = True seen_odd = False for f in counter.values(): is_odd = True if f % 2 == 1 else False if is_odd: # check if odd if not seen_odd: seen_odd = True else: # seen odd already, not valid valid = False return valid print(permutation_palindrome("carrace")) print(permutation_palindrome("abbcad")) print(permutation_palindrome("daily"))
true
e58961561a2b6fd3cd16a1c8707ff91994e9a5cb
Bradysm/daily_coding_problems
/lexi_numbers.py
1,354
4.125
4
# given a number n, return a list containing numbers 1 through n # that is sorted lexiographically # For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9] # this problem is question 389 on leetcode # my solution is faster than 93% of the other soltions # I first realize that we're creating a list of numbers from 1-n, so I immediately # think of using the range function with an initializer list to generate the numbers # once we have the list of numbers, we then need to sort the numbers, using their # lexiographical value. We can do this by using the built in sort function # that is included within the list datastructure. If we used the sort algorithm # with no arguments, then the numbers would be sorted numerically. This is not what we want # Instead, we want to treat them as if they were strings. To do this, we change the key for # sorting to the string representation of the number using a lambda expression. This will # then result in the values being sorted in a lexiographical fashion but will maintain # their numerical identity. # viola. There you go, a simple, but useful solution. # lastly, note that range is not inclusive on the ending value, so n+1 is used def lexicalOrder(n): """ :type n: int :rtype: List[int] """ l = [x for x in range(1, n + 1)] l.sort(key=lambda v: str(v)) return l
true
a2b5743ed0d5b059c61d69d9275de12d4d5d7813
Bradysm/daily_coding_problems
/climbStairs.py
2,724
4.25
4
""" Hi, here's your problem today. This problem was recently asked by LinkedIn: 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. def staircase(n): # Fill this in. print staircase(4) # 5 print staircase(5) # 8 Can you find a solution in O(n) time? So this is A CLASSIC Let's first solve this recursively and then get to the O(n) time. This is very similar to the fib problem. If not, exactly like it. So, here we can think we start at the nth stair, and the ways to get to the nth stair are the ways to get to the n-2 stair and n-1 stair. We can then see that there are two base cases. When n=1, there is one way to get up that stair and when n=2, there are two ways to get up teh stair. Once we have that, we can see that we can actually start form the bottom and build up the solution because we need the n-1 and n-2 number to get the nth number, just like fib right. So start at the 1 and 2 and then build up from there! Let's do it! O(n) time and space """ def recursive_stair(n) -> int: # base cases if n <= 0: return 0 if n == 1: return 1 if n == 2: return 2 return recursive_stair(n-2) + recursive_stair(n-1) print("5 steps", recursive_stair(5)) print("4 steps", recursive_stair(4)) print("27 steps", recursive_stair(27)) def iterative_stair(n) -> int: if n <= 0: return 0 # build an array to hold the numbers ways_to_climb = [0 for i in range(n+1)] # note that we have to do n+1 to make sure we can store the nth value ways_to_climb[1] = 1 # set the base cases to build up the soltion ways_to_climb[2] = 2 for stair in range(3, n+1): ways_to_climb[stair] = ways_to_climb[stair-2] + ways_to_climb[stair-1] return ways_to_climb[n] print("5 steps", iterative_stair(5)) print("4 steps", iterative_stair(4)) print("27 steps", iterative_stair(27)) """ We can then see that we can just use two variables to store the values instead of using an array to store the values O(n) time O(1) space """ def iterative_stair_no_space(n) -> int: if n <= 0: return 0 if n == 1: return 1 if n == 2: return 2 one_lower = 2 # act like this is the second stair two_lower = 1 # act like this is the first stair for stiar in range(3, n): ways_to_climb_stair = one_lower + two_lower # update the variables two_lower = one_lower one_lower = ways_to_climb_stair return two_lower + one_lower print("5 steps", iterative_stair_no_space(5)) print("4 steps", iterative_stair_no_space(4)) print("27 steps", iterative_stair_no_space(27))
true
5247a5c61e9605ad498023dd28c037fc9d3da9a3
Bradysm/daily_coding_problems
/wordDistance.py
1,284
4.375
4
# Good morning! Here's your coding interview problem for today. # Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string. # For example, given words "hello", and "world" and a # text content of "dog cat hello cat dog dog hello cat world", # return 1 because there's only one word "cat" in between the two words. # O(w) space where w is the number of words and the time complexity is O(w*s) where s is the longest word inputted from word1 and word2 # due to the comparisons of the words. Note that this uses the simple "two pointer" technique import sys def word_distance(string, word1, word2): # split the string at the space w1_i = w2_i = -1 # start them at -1 for not being seen distance = sys.maxsize for i, w in enumerate(string.split(' ')): # update w1_i or w2_i if is the same w1_i = i if w == word1 else w1_i # update the w1_i w2_i = i if w == word2 else w2_i # update the w2_i both_words_seen = True if w1_i is not -1 and w2_i is not -1 else False if both_words_seen: distance = min(distance, abs(w1_i - w2_i)-1) return distance print(word_distance("dog cat hello cat dog dog hello cat world", "hello", "world"))
true
7beaef7e20e8dc75033283f29677f7ea1b3db54e
aberk104/CS410-Project
/address_compare/parsers.py
918
4.3125
4
# this file contains parsers for converting address strings to lists # of tokens import re def naive_parse(s: str, tolower: bool = False) -> list: """ :param s: string to be parsed :param tolower: convert to lowercase? """ return [k.lower() for k in s.split()] if tolower else s.split() def hyphen_parse(s: str, tolower: bool = True) -> list: """ keeps trailing hyphens, i.e. hyphen_parse("A-b") = ["A-", "b"] :param s: string to be parsed :param tolower: convert to lowercase? """ s = re.sub(' +-', '-', s) parts = [re.split('([^\s]+-)', k) for k in re.split(' |\t', s)] return [k for sl in parts for k in sl if k and (k != '-')] def omit_hyphen(s: str) -> list: """ turne "1 - 2" into ["1", "2"] :param s: a string :return: s split by spaces, but without any single hyphens. """ return [k.strip() for k in s.split() if k and (k != '-')]
false
8a774d2b6288390f45fed98ad760eb2dbeb7dd6e
Jane-Zhai/target_offer
/eg_06_printlist.py
522
4.1875
4
""" 输入一个链表头节点,从尾到头打印每个节点的值 """ class ListNode: def __init__(self, val=None): self.val = val self.next = None def printList(node): if node is None: return None stack = [] while node: stack.append(node) node = node.next while stack: node = stack.pop() print(node.val, end=' ') node1 = ListNode(10) node2 = ListNode(11) node3 = ListNode(13) node1.next = node2 node2.next = node3 printList(None)
false
474cc5d628de9e5e4060b3531c7ace5e4146c7e1
gong1209/my_python
/Loop/for_tuple.py
540
4.46875
4
#多元組 : 不可變的串列 numbers=(1,2,3) # 定義一個多元組 print("Original :") for number in numbers : # 在numbers多元組中取得元素再存到number變數中 print(number) # 印出變數存到的值 numbers=(4,5,6,7) # 讓原本多元組(1,2,3)的值改為(4,5,6) print("Modified :") for number in numbers : print(number) location = ("tainan","stust",("123","ABC","abc")) print(location) print(location[2][1]) print(location[2][1][1]) a=3 b=4 a,b=b,a # 或寫成(a,b)=(b,a) print(a) print(b)
false
09c32559f93dd1f77e1c76abd33d63f9cf5ee19e
krishnodey/Python-Tutoral
/count_words_characters_in_string.py
744
4.375
4
''' lets write a program to count total number of words and characters logic: iterate through the string using a for loop untill string ends then use a counter and counter is incremented each time for loop runs i.e. runs untill las charactes use a if conditon inside the for loop if we find space then use another counter and increment it. we will have to add 1 to counter at the end to count the last word lets implement it ''' str = input("enter the string: ") count1 = 0 count2 = 0 for k in str: count1 += 1 if k == ' ': count2 += 1 print("total number of words: ", count2+1) print('total number of charactes: ', count1 ) ''' thank you for watching '''
true
76925e4d2391e6fc65328a1008f9b1c443f6514d
krishnodey/Python-Tutoral
/factorial_of_a_number_without_recursion.py
251
4.25
4
#lets write a prrogram to find out the factorial of a given number without receursion number = int(input("enter a number: ")) factoral = 1 for i in range(2, number+1): factoral *= i print(number,"! = ",factoral) #thank you guys
true
1a6b3cd27cc7b6966889ac7284ff1f1b820eb2bd
krishnodey/Python-Tutoral
/second_largest_element_in_list.py
786
4.5625
5
''' lets write a program to find second largest element in a list logic: take a lsit as input or use defined list sort the list using sort() finction sort() --> sort the list in ascending order then element of the index before the last index will be the second largest element ''' n = int(input("enter the size of the list: ")) list = [] for i in range(0, n): element = int(input("enter the element: ")) list.append(element) list.sort() print("secornd largest element = ", list[n - 2]) ''' #as we have the length of the list we can directly use it or we use len() function to find the length of list list[lenght - 2 ] will be the second largest element i hope you understood the logic thank you for watching '''
true
e44f1116b51d9334db9f4091deb8ffb8f8e37605
krishnodey/Python-Tutoral
/pyramid_of_stars.py
484
4.125
4
''' let's wrtie a program to print a pyramid of stars --* -*** ***** like this ''' n = int(input("enter the number of rows: ")) #iterate through rows for i in range(1,n+1): for j in range(1, n-i+1): #print spaces from 1, till n-i th column print(" ", sep=" ", end=" ") for k in range(1, (2*i)): #print stars from 1 to 2*i -1 th column print("*", sep=" ", end=" ") print() #newline #thank you for watching
false
737b8358675a2abb8642aa9033eced669c11f19c
krishnodey/Python-Tutoral
/hollow-triangle.py
478
4.28125
4
#we will write a program to print a hollow triangle of stars n = int(input("enter the numbe of rows: ")) for i in range(1,n+1): for j in range(1,i+1): if(i == 1 or i == n or j == 1 or j == i): #print stars only when last row(i=n) , 1st column(j=1) amd row(i=1) , last column of triangle(j=i) print("*",sep=" ",end=" ") else: print(" ",sep=" ",end=" ") #else print a space print() #new line #thank you guys
false
270058b0ca72b1fad73142fc056b8ac752089a85
krishnodey/Python-Tutoral
/replace_space_with_underscore_in_string.py
372
4.5
4
''' lets write a program to replacea all space in a string with underscore use replace() funtion it has two parameters 1st one is the character you want to replace 2nd one is the character you want to replace with ''' str = input("enter the string: ") str = str.replace(" ", "_") print("Modified String: ", str) ''' thank you for watching '''
true
cce27fe81e39db70e2d3fc6677312063a885ad50
krishnodey/Python-Tutoral
/binarySearch.py
951
4.28125
4
#in this video we ll implement binary search. i hope your concept is clear. def binarySearch(list, num): first = 0 last = len(list)-1 flag = 0 while first <= last : mid = (first + last) // 2 if list[mid] == num: flag =1 else: if num < list[mid]: last = mid -1 else: first = mid + 1 return flag #driver code n = int(input("enter the size of the list: ")) list = [] for i in range(0, n): p =int(input("enter the element: ")) list.append(p) #we need a sorted list for binary search so lets use sort() function number = int(input("enter the number to be searched: ")) list.sort() print("\n",list,"\n") result = binarySearch(list,number) if result == 0: print(number," not found the list") else: print(number,"is found in the list") #thank you for watching
true
637268f7cb299da5666e6f7e0984140c5aa1c03b
krishnodey/Python-Tutoral
/palindrome.py
397
4.125
4
#a progrsm to identify palindrome number n = int(input("Entet The Number: ")) temp = n sum = 0 # let n = 121 while n > 0: remainder = n % 10 #1 % 10 = 1 sum = sum * 10 + remainder # sum = 10* 12 + 1= 121 n = n // 10 # 1 // 10 = 0 # that how it works if temp == sum: print(temp,"is Palindrome") else: print(temp, "is not Palindrome") # bye guys
false
2562c717ebd90de598d68a29b843f7345f92d773
krishnodey/Python-Tutoral
/replace_characters_in_string.py
522
4.5625
5
''' let's write a program to replace occurances of characters with another characters logic: we ll use replace() function it has two parameters 1st one is the character you want to replace 2nd one is the character you want to replace ''' str = input("enter a string: ") a = input("enter the character you want to replace: ") b = input("enter the character you want to replace with: ") str = str.replace(a, b) print("modified string: ", str) ''' thank you for watching '''
true
c41ae2705ef15215957a26f03e90fa27690657f9
krishnodey/Python-Tutoral
/largest_divisor_of_a_number.py
238
4.15625
4
#lets write aprogram to find largest divisor of a numebr number = int(input("enter a number: ")) l = [] for i in range(2, number): if number % i == 0 : l.append(i) l.sort() print("Largest Divisor = ", l[-1])
false
70a672c8872d9b33b9efb9042b71ed90b63ea4c2
krishnodey/Python-Tutoral
/mirrored_triangle.py
517
4.1875
4
''' lets write a program to print moirrored triangle * ** *** **** like this ''' row = int(input("enter the number of rows: ")) for i in range(1,row+1): for j in range(1,row-i+1): #print spaces from 1 to row-i positions print(" ", sep=" ", end=" ") for k in range(row-i+1,row + 1): #print stars from row-i+1 to row print("*" , sep=" ", end=" ") #dont forget sep and end print("") #print new line #thank you for watching bye guys
true
5533bb700f49d2efb9958ef00bc065cb1bbd2c7b
krishnodey/Python-Tutoral
/armstrong-numbers_in_an_interval.py
831
4.46875
4
''' let's write a program to find all armstrong numbers in an specific interval or range a number is called armstrong number if sum of all digit of a number is equal to the number itself i.e. 153 = 1^3 + 5^3 + 3^3 = 153 so armstrong number ''' lower = int(input("enter the lower limit: ")) upper = int(input("enter the upper limit: ")) print("armstrong number in interval ", lower, " to ", upper, "is: ") for number in range(lower, upper+1): temp = number # copy the number for future use, value of number variable will ber altered during calculations sum = 0 while number > 0: remainder = number % 10 sum += remainder ** 3 #we can also use instead of pow() function number //= 10 if temp == sum: print(temp) ''' thank you for watching '''
true
d1e4aea1e833537237c04ec9f1da7a06c1e60d0c
Sherman77/Triangle567
/TestTriangle.py
2,276
4.25
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle import math # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testInputA(self): self.assertEqual(classifyTriangle(0,1,2),'InvalidInput','0,1,2 is a InvalidInput') def testInputB(self): self.assertEqual(classifyTriangle(199,199,201),'InvalidInput','199,199,201 is a InvalidInput') def testInputC(self): self.assertEqual(classifyTriangle(1.2, 2, 1.2),'InvalidInput','1.2, 2, 1.2 is a InvalidInput') def testInputD(self): self.assertEqual(classifyTriangle(2,2,'three'),'InvalidInput','2,2, three is a InvalidInput') def testRightTriangleA(self): self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle') def testRightTriangleC(self): self.assertEqual(classifyTriangle(6,8,10),'Right','6,8,10 is a Right triangle') def testRightTriangleD(self): self.assertEqual(classifyTriangle(10,8,6),'Right','10,8,6 is a Right triangle') def testEquilateralTriangles(self): self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral') def testIsoscelesTrianglesA(self): self.assertEqual(classifyTriangle(1,1,2),'NotATriangle','1,1,2 is NotATriangle') def testIsoscelesTrianglesB(self): self.assertEqual(classifyTriangle(10,10,11),'Isoceles','10,10,11 is a Isoceles triangle') def testScaleneTrianglesA(self): self.assertEqual(classifyTriangle(10,12,11),'Scalene','10,12,11 is a Scalene triangle') def testScaleneTrianglesB(self): self.assertEqual(classifyTriangle(10,12,32),'NotATriangle','10,12,32 is NotATriangle') if __name__ == '__main__': print('Running unit tests') unittest.main(exit = False, verbosity= 2)
true
bae8212e9d02c49816ce4a86d0a14d6359bfcfa4
bhavin250495/Python-DataStructures
/QuickSort.py
984
4.21875
4
def quick_sort(arr): ''' Check if array is divisable else retrun single element array ''' if len(arr)>1: start_index = 0 end_index = len(arr) mid_index = int((start_index+end_index)/2) ''' Divide the array in 2 sub arrays and arrange them as 1 - This will put the mid point in its sorted index 2 - Smaller then mid_point 3 - Greater then mid_point ''' list1 = list(filter(lambda x : x < arr[mid_index],arr)) list2 = list(filter(lambda x : x > arr[mid_index],arr)) '''Continue division till we get last undivisable element''' list1 = quick_sort(list1) list2 = quick_sort(list2) list1.append(arr[mid_index]) '''Append sorted sub arrays and return ''' return(list1+list2) else: return arr test_unsorted_array = [14, 17, 13, 15, 19, 10, 3, 16, 9, 12] print(quick_sort(test_unsorted_array))
true
b4e051a6e13b8cac4540a874b578895a428865f0
codec-symbiosis/daily-coding-problems-python
/dcp6.py
612
4.15625
4
''' This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. ''' def max_non_adj_sum(arr): incl_sum, excl_sum = 0, 0 for i in arr: temp = max(incl_sum, excl_sum) incl_sum = excl_sum + i excl_sum = temp return max(incl_sum, excl_sum) if __name__ == '__main__': arr = list(map(int, input().split())) print(max_non_adj_sum(arr))
true
19f07ca7795d3ba2c4a2533f352ec20e2340d809
tanjased/python-bootcamp
/04-Milestone Project - 1/02-Milestone Project - 1.py
2,683
4.1875
4
## First step is to display the game board def display_board(): lst = ['']*9 # lst = ['X','1','1','X','0','0','X','7','7'] print("Let's start the game!") print("|".join(lst[:3])) print("|".join(lst[3:6])) print("|".join(lst[6:])) # print(f'{lst[:3]}\n{lst[3:6]}\n{lst[6:]}' return lst # Had problem with displaying on a few lines # lst = display_board() # print(lst[0]) ## Define the player's index position def user1_pos(): choice = 'wrong' while choice.isdigit() == False or int(choice) not in range(0, 9): # indices 0..8 choice = input("Choose the position: ") if choice.isdigit() == False: print('Please, choose a number') elif int(choice) not in range(0, 9): print('Your choice is out of range') return int(choice) # user1_pos() ## Define the player's choice def user_placement(board, position): # value = 'input' value = 1 rng = ['x', 'o'] while value not in rng: value = input('Make your move: ') print('Put x or o please') board[position] = value print(board) # user_placement(lst, 2) ##### Don't know how to set parameters for 2. ## Check if win def check_win(board,marker): # for n,el in enumerate(board): if all(el == marker for el in board[:3]): print('yay1') elif all(el == marker for el in board[4:6]): print('yay2') elif all(el == marker for el in board[7:]): print('yay3') # for i in len(board): # if board[i] == board[i+3] elif board[0] == board[3] and board[0] == board[6]: print('col1') elif board[1] == board[4] and board[1] == board[7]: print('col2') elif board[2] == board[5] and board[2] == board[8]: print('col3') elif board[0] == board[4] and board[0] == board[8]: print('diag1') elif board[2] == board[4] and board[2] == board[6]: print('diag2') elif ' ' not in board: print('tie') return True # check_win(lst,'X') ## Who goes first import random def choose_first(): flip = random.randint(1,2) print(f'User {flip} goes first') # choose_first() ## Check if they want to continue. def gameon(): answer = '' options = ['Y', 'N'] while answer not in options: answer = input('Do you want to keep playing? ') print('Please choose Y or N. ') if answer == 'Y': return True else: print('Ok. Come back later') return False # gameon() game_on = True while game_on: board = display_board() choose_first() pos = user1_pos() marker = user_placement(board, pos) check_win(board, marker) gameon()
true
5b4b6febb8c7a0a7fdfe75265f1a2990e6087735
Meysam-/CPSC_217
/ifStatement.py
697
4.21875
4
# This program will sort three inputted numbers # getting the inputs a = int(input()) b = int(input()) c = int(input()) # Method 1 # initializing # we imagine that x < y < z x = 0 y = 0 z = 0 if a < b: x = a z = b else: x = b z = a if x < c: if z < c: y = z z = c else: y = c else: y = x x = c print(x,y,z) # Method 2 if a < b < c: print(a, b, c) elif a < c < b: print(a, c, b) elif b < a < c: print(b, a, c) elif b < c < a: print(b, c, a) elif c < a < b: print(c, a, b) else: print(c, b, a) # Method 3 if a > b: a, b = b, a if b > c: b ,c = c, b if a > b: a, b = b, a print(a, b, c)
false
1db2e9e937915d7165716b371855fb3c973847b8
azhar2ds/Python-Integration
/Generators.py
1,878
4.1875
4
# Generator function for loop in a List def hello(): a=[1,2,3] for x in a: yield x b=hello() print(next(b)) print(next(b)) print(next(b)) # General function for loop in a List def hello2(): a=[1,2,3] for x in a: print(x) hello2() # Generator function for loop in a Dictionary def dicfunc(): a={1:'A',2:'B',3:'C'} for x,y in a.items(): print(x,y) dicfunc() # General function for loop in a Dictionary def dicfunc2(dict): a={1:'A',2:'B',3:'C'} for x,y in a.items(): yield x,y b=dicfunc2(dict) print(next(b)) print(next(b)) print(next(b)) # Generator function for while loop def wilfunc(i): while i<5: yield i i+=1 a=wilfunc(2) print(next(a)) print(next(a)) print(next(a)) # general function for while loop def wilfunc2(i): while i<5: print(i) i+=1 wilfunc2(1) #Normal LIST COMREHENSION lis=range(6) b=[x+2 for x in lis] print(b) # List comprehension all the values generated once # Generator expression lis2=range(6) b=(x+2 for x in lis2) for x in b: print(x) print(type(b)) # r is generator so it has be called with next method or by loop def hi(): f = range(4) r = (x+2 for x in f) for x in r: print(x) hi() lis3=range(6) b=(x+2 for x in lis3) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) # STOP ITERATION ERROR OCCURS AFTER EXHAUTING The ELEMENTS IN LOOP #Generating even and odd numbers using Generators f=range(2,50,2) b=(x for x in f) for y in b: print(y) #Generating even & odd number using loop for s in range(2,50,2): if s>30: break print(s) #Generating even & odd number using list comprehension a=[p for p in range(1,50,2)] print(a)
false
574ac4b786e49702931b9fd8342d4cbfaba2b1e8
mad18-lab/Madhav-Gupta
/reversal three strings.py
230
4.125
4
a=str(input("Enter your string: ")) b=a[::-1] print(b) i=len(a)-1 while (i>=0): print (a[i], end="") i=i-1 def stringreverse(a): a = a[::-1] return a print("\nReverse of string is:", stringreverse(a))
true
c570824c0690594fe0238df263181f7f2996b398
Pranik27/Python
/FUNCTIONS/unique_list.py
434
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 23 12:49:33 2020 @author: PRANIKP Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,1,1,1,2,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5] """ def unique_list(inp_list): return(list(set(inp_list))) out_list = unique_list([1, 89, 1, 1, 2, 73, 3, 3, 3, 3, 4, 5]) print("New list: {}".format(out_list))
true
071cb82d5a3c79dcc200f2d70282996894419544
Pranik27/Python
/FUNCTIONS/paper_doll.py
547
4.28125
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 23 00:19:16 2020 @author: PRANIKP PAPER DOLL: Given a string, return a string where for every character in the original there are three characters paper_doll('Hello') --> 'HHHeeellllllooo' paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii' """ def paper_doll(st): my_str = [] for letter in range(len(st)): my_str.append(st[letter]*3) return ''.join(my_str) final_str = paper_doll('Mississippi') print("Final String : {}".format(final_str))
false
4323811a7351c12a1581d3ed80513d15feee8b1b
neerajkumarsingh17/0132ex028
/pyListCmd.py
1,198
4.28125
4
#Consider a list (list = []). You can perform the following commands: #insert i e: Insert integer at position . #print: Print the list. #remove e: Delete the first occurrence of integer . #append e: Insert integer at the end of the list. #sort: Sort the list. #pop: Pop the last element from the list. #reverse: Reverse the list. #Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. #Iterate through each command in order and perform the corresponding operation on your list. if __name__ == '__main__': N = int(input()) the_list = list() for _ in range(N): query = input().split() if query[0] == "print": print(the_list) elif query[0] == "insert": the_list.insert(int(query[1]), int(query[2])) elif query[0] == "remove": the_list.remove(int(query[1])) elif query[0] == "append": the_list.append(int(query[1])) elif query[0] == "sort": the_list = sorted(the_list) elif query[0] == "pop": the_list.pop() elif query[0] == "reverse": the_list.reverse()
true
ee4c330cff73b7c6eba34974051a41e60d729809
cwruck13/Module_3
/average_scores.py
1,150
4.4375
4
""" program: average_scores.py Author: Cassandra Wruck Last date modified: June 7th, 2020 This program is meant to calculation an average score for 3 tests. It gets the user's input such as first and last name, age, and the test scores. It calls a method to calculate told and prints off the information. """ def average(): #defining start point average_scores = 0 #get input from user for test scores score1 = int(input('First test score: ')) score2 = int(input('Second test score: ')) score3 = int(input('Third test score: ')) #calucate average of test scores average_scores = (score1 + score2 + score3) / 3 return average_scores if __name__ == '__main__': #get input from user for name first_name = input('What is your first name? : ') last_name = input('What is your last name? : ') #get input from user for age age = input('What is your age? : ') #calling a method to return calculation average_scores = average() #printing information print(last_name + "," + first_name + " Age: " + age + " Average Grade: " + str(average_scores))
true
06b447e4f1ee16050312366feb60dbb18a3d4433
petermao/cryptography
/DVD/ngramFT.py
1,375
4.1875
4
import re import sys frequencies = {} one_occurrence = [] args = sys.argv def usage(): print( """ Usage: (python version) ngramFY.py <file> Outputs a dictionary with substrings as keys and counts as values, then a list of substrings that occur only once. This can generate a lot of output, so feel free to pipe. """ ) if len(args) != 2: usage() exit() try: fp = open(args[1]) # read mode is default except FileNotFoundError: print("Invalid file!") usage() exit() content = fp.read() fp.close() # perhaps somewhat crude method of stripping newlines and spaces content = content.replace("\n", "").replace("\r", "").replace(" ", "") if not content.isalpha(): print("Your file must contain only alphabetical characters.") exit() c_len = len(content) content = content.upper() # standardize case half_c_len = c_len // 2 for n_to_count in range(1, half_c_len + 1): for ind in range(0, c_len - (n_to_count - 1)): string_to_count = content[ind:ind + n_to_count] if string_to_count in frequencies: continue matches = re.findall(string_to_count, content) if len(matches) > 1: frequencies[string_to_count] = len(matches) else: one_occurrence.append(string_to_count) print(frequencies) print(one_occurrence)
true
aa0aed757fe782fad2dc6e1e8a7500ee74a2884d
bconti123/Python-Practice
/rafflefuncts.py
1,727
4.15625
4
import re #Function to reverse a string def reverse(s): if s == "": return s else: return reverse(s[1:]) ############################ add_user function ############################### def add_user(local_hash): # prompt for username & password username = input("Enter username: ") # strip off special chars from username (ref asmt sheet) username = re.sub(r'\W+', '', username) # convert username to lowercase (ref asmt sheet) username = username.lower() #check if username already exists & if so exit, else assign password as value to the hash referenced by username as the key if(username in local_hash): print("Username already exist!") return local_hash return local_hash ############################ delete_user function ############################### def del_user(local_hash): # prompt/chomp for username username = input("Enter username to delete: ") # strip off special chars from username (ref asmt sheet) username = re.sub(r'\W+', '', username) # convert username to lowercase (ref asmt sheet) username = username.lower() #check if username DOESNT already exists & if NOT so exit if username not in local_hash: print("Username does not exist!") return local_hash #delete key from hash (ref slides) del local_hash[username] return local_hash ############################ print_list function ############################### def print_list(local_hash): # print out to the screen each key & value pair from hash print(local_hash) return local_hash def start_raffle(local_hash): # print out to the screen who is winner name = random.choice(username in local_hash) print(random.choice(word))
true
900b24c145afb47f27ec208bac0b0f8fcd9bc0c4
Devansh2290/tutorials
/python/decorators/class_decorator.py
855
4.5
4
# Decoratorsa are the callable python objects which is use to modify # the behaviour of functions or class wihout modify it parmanently. # Two types of decoratore we can define in python. # 1. class based decorators # 2. funcation based decorators # 1. class based decorator: when we define a class based decorator we need # to define a __call__ method class MyDecoratore: def __init__(self, func): self.func = func def __call__(self): # We can add some code # before function call print ("before function call") self.func() print ("after function call") # We can also add some code # after function call. @MyDecoratore def func(): print ("I am wapped function.") func() def f(x): def g(y): return x * y + 3 return g nf1 = f(10) print (nf1(2))
true
b4ff2f127ad0e709a48730340e1161b77e34b61c
ganqzz/sandbox_py
/collections/list_demo.py
1,883
4.125
4
# List : mutable sequence list1 = list(range(10)) print(list1) print(list1.__len__()) print(len(list1)) # preferred list1.append(10) print(list1) print() # slices (sequence protocol) # [start:end:step] print(list1[1:5]) print(list1[0:3]) print(list1[:3]) print(list1[3:]) print(list1[-1]) # not slice, single value print(list1[-1:]) print(list1[:-1]) print(list1[::2]) print(list1[::-1]) # reverse list2 = list1[:] # shallow copy print(list2 is list1) del list2[0] print(list2) del list2[2:4] print(list2) print(list1) list2[1:2] = ['a', 'b', 'c'] print(list2) list2[:] = list1 # copy elements 1 by 1 print(list2) print(list2 is list1) list2[-1] = "hoge" print(list2) list2[-1:] = "hoge" # string is also iterable print(list2) list2[-4:] = ["".join(list2[-4:])] print(list2) print() # shallow copy e = ["hoge"] a = [5, e, 6] b = a[:] print(b) e += ["fuga"] print(b) print(a) print() # operators list3 = ['a', 'b'] print(list3 + ['c']) print(list3 * 2) print(list3) list4 = [[1]] * 4 print(list4) list4[0].append(2) print(list4) print() # methods l = [1, 2, 3] l.extend("abc") # => l += ['a', 'b', 'c'] print(l) print(l.index('c')) l.insert(3, 'x') print(l) l.remove('b') print(l) l.reverse() print(l) l = [[5, 8], {6, 3, 7}, (2, 9), [100]] l.sort(key=sum, reverse=True) # key: function to be applied to each item print(l) print(list(map(sum, l))) print() # out-of-place l1 = [(7, 2), (3, 4), (5, 5), (10, 3)] l2 = sorted(l1, key=lambda x: x[1]) print(l2) # => [(7, 2), (10, 3), (3, 4), (5, 5)] l3 = reversed(l1) print(l3) print(list(l3)) print() # enumerate print(list(enumerate("qwerty"))) for i, v in enumerate("qwerty"): print("{}: {}".format(i, v)) for i, v in enumerate("qwerty", start=10): print("{}: {}".format(i, v)) print() # unpack list_x = [5, 10] list_y = [2, 5] print([*list_x, *list_y]) print([*list_x, "あ", "ほ", *list_y])
false
6a8de42677a3724f1158dcea4746e213de1cfb37
ganqzz/sandbox_py
/collections/generator_demo.py
310
4.125
4
# Generator # Generator is Iterator and Iterable def gen123(): input("yield 1: press enter") yield 1 input("yield 2: press enter") yield 2 input("yield 3: press enter") yield 3 print("end") g = gen123() print(next(g)) print(next(g)) print(next(g)) print(next(g)) # StopIteration
false
35cdfb4edc9369607e59335594200b9e5f05483f
ganqzz/sandbox_py
/strings/format_string_demo.py
2,224
4.375
4
# string format demo def demo1(): name = "Hoge Hoge" machine = "HAL" print('Nice to meet you %s. I am %s' % (name, machine)) # like C printf (legacy) print('Today is %(month)s %(day)s.' % {'month': 12, 'day': 31}) print('Nice to meet you {}. I am {}'.format(name, machine)) print('Nice to meet you {0}. I am {1}'.format(name, machine)) print("Nice to meet you {name}. I am {machine}".format(name=name, machine=machine)) print(f'Nice to meet you {name}\\. I am {machine}') # f-string 3.6 print(rf'Nice to meet you {name}\\. I am {machine}') # raw f-string print(f'{{escaping braces {machine}}}') # useful for dynamic templates print() product = "Widget" price = 19.99 tax = 0.07 print(f"{product} has a price of {price}, with tax {tax:.2%}" f" the total is {round(price + (price * tax), 2)}") print() v = [1, -2, 3.3] print('%4d %10d %10.3f' % (1, -2, 3.3)) # print('%4d %10d %10.3f' % v) # NG print('%4d %10d %10.3f' % tuple(v)) print('{0:4} {1:10} {2:10.3f}'.format(*v)) print('{:4} {:10} {:10.3f}'.format(*v)) # 順番通りなら位置指定は省略できる print('{:>04} {:<10} {:10.3f}'.format(*v)) # 右寄せ0埋め, 左寄せ def demo2(): foo = 123 bar = 456 print(f"Output: {foo:04x}, {bar:04x}, {bar:4X}") # x: hexadecimal print(f"Output: {foo:b}, {foo:08b}") # b: binary def demo3(): # Example of building the format string dynamically width = {"w1": 4, "w2": 4, "w3": 10} # Build a format string (two curly brackets get you one curly bracket) formatter = "{{0:{w1}}} {{1:{w2}}} {{2:{w3}.5f}}".format(**width) print(formatter) # {0:4} {1:4} {2:10.5f} import math for i in range(1, 6): print(formatter.format(i, i * 2, math.sqrt(i))) # Use the formatter we built def demo4(): q = 7.748091e-5 print(q) print(format(q)) print(format(q, ".2e")) print(format(q, "f")) print(format(q, ".11f")) print(format(q, ">+20.11f")) if __name__ == '__main__': print("--- demo1 ---") demo1() print("\n--- demo2 ---") demo2() print("\n--- demo3 ---") demo3() print("\n--- demo4 ---") demo4()
true
3cb1fbd89bef1cce69215d014a84714183409aca
ganqzz/sandbox_py
/collections/tuple_demo.py
750
4.125
4
# Tuple : immutable sequence tuple1 = (1, 2) tuple2 = 1, 2 not_tuple = (5) print(type(not_tuple)) tuple3 = (5,) print(type(tuple3)) print() def add(*nums): total = 0 for num in nums: total += num return total print(add(5, 5)) print(add(32)) print() subjects = ('Python', 'Coding', 'Tips') subjects2 = ('Python', 'Coding', 'Tips') print(subjects == subjects2) # => True print(id(subjects) == id(subjects2)) # => False : stringとは違う点 print(subjects is subjects2) # => False print() z = ["hoge"] c = (1, z, 2) d = c[:] z += ["fuga"] print(c) print(d) print() # multiple assignment tt = (a, (b, (c, d))) = (4, (3, (2, 1))) print(a, b, c, d) print(tt) # swapping technique s = 5 t = 20 s, t = t, s print(s, t)
false
3861bad640958081fe28287234a1b20e0588458d
noveroa/DataBases
/practiceCodes/queues.py
2,878
4.40625
4
''' The queue abstract data type is defined by the following structure and operations. A queue is structured, as described above, as an ordered collection of items which are added at one end, called the Rear and removed from the other end, called the Front Queues maintain a FIFO ordering property. The queue operations are given below. - - Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue. - - enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing. - - dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. - - isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value. - - size() returns the number of items in the queue. It needs no parameters and returns an integer. ''' class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) ''' Deque abstract data type is defined by the following structure and operations. an ordered collection of items where items are added and removed from either end, either front or rear. - - Deque() creates a new deque that is empty. - - addFront(item) adds a new item to the front of the deque. - - addRear(item) adds a new item to the rear of the deque. - - removeFront() removes the front item from the deque. The deque is modified. - - removeRear() removes the rear item from the deque. The deque is modified. - - isEmpty() tests to see whether the deque is empty. - - size() returns the number of items in the deque. returns an integer. ''' class Deque: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def addFront(self, item): self.items.append(item) def addRear(self, item): self.items.insert(0,item) def removeFront(self): return self.items.pop() def removeRear(self): return self.items.pop(0) def size(self): return len(self.items) '''Queue function''' def hotPotato(namelist, num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue() def palchecker(aString): chardeque = Deque() for ch in aString: chardeque.addRear(ch) stillEqual = True while chardeque.size() > 1 and stillEqual: first = chardeque.removeFront() last = chardeque.removeRear() if first != last: stillEqual = False return stillEqual
true
2c7d3baaa7ea788d3eadbaa00c1592b3339184a5
ksenialearn/Intro-to-Python
/Coder.py
668
4.34375
4
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces. shift: 0 <= int < 26 returns: dict """ l= string.ascii_lowercase h= string.ascii_uppercase t= h+l l= l*2 h= h*2 lowV= range(26) hiV= range(26) i= 0 j= 0 while i+shift<26+shift: lowV[i]= l[i+shift] i+=1 while j+shift<26+shift: hiV[j]= h[j+shift] j+=1 t1= hiV+lowV d= {} k=0 while k< 26*2: d[t[k]]= t1[k] k+=1 return d
true
ccd61d2da4b0e2d1e8f135bc0f93eac00f1e3d86
niceNASA/Python-Foundation-Suda
/05_leetcode/178.Bigram.py
1,150
4.125
4
""" 给出第一个词 first 和第二个词 second, 考虑在某些文本 text 中可能以 "first second third" 形式出现的情况, 其中 second 紧随 first 出现,third 紧随 second 出现。 对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。 输入:text = "alice is a good girl she is a good student", first = "a", second = "good" 输出:["girl","student"] """ class Solution: def findOcurrences(self, text: str, first: str, second: str) -> list: third = [] text_list = text.split() if len(text_list) > 2: for index in range(len(text_list)-2): if text_list[index:index+2] == [first,second]: third.append(text_list[index+2]) return third def findOcurrences2(self, text: str, first: str, second: str) -> list: import re return re.findall(fr"(?<=\b{first} {second} )(\w+)", text) if __name__ == "__main__": s = Solution() text = "alice is a good girl she is a good student" first, second = "a", "good" print(s.findOcurrences(text, first, second))
false
f84358f99f3c0174545f2034e8f46a01ca441c18
niceNASA/Python-Foundation-Suda
/05_leetcode/657.机器人能否返回原点.py
1,533
4.125
4
""" 在二维平面上,有一个机器人从原点 (0, 0) 开始。 给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。 移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。 机器人的有效动作有 R(右),L(左),U(上)和 D(下)。 如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。 注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次, “L” 将始终向左移动等。 此外,假设每次移动机器人的移动幅度相同。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/robot-return-to-origin 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def judgeCircle(self, moves: str) -> bool: # 80ms hori, vert = 0, 0 for dirction in moves: if dirction == 'U': vert += 1 elif dirction == 'D': vert -= 1 elif dirction == 'L': hori += 1 else: hori -= 1 if hori or vert: return False else: return True def judgeCircle2(self, moves: str) -> bool: # 52ms return moves.count('U')==moves.count('D') and moves.count('R')==moves.count('L') if __name__ == "__main__": test = "UD" s = Solution() print(s.judgeCircle(test))
false
cb0098ec92408d862b88fdcdd383c2b2b11b54ff
lzwhirstle/comp1531
/lab09/inverse.py
383
4.375
4
def inverse(d): ''' Given a dictionary d, invert its structure such that values in d map to lists of keys in d. For example: >>> inverse({1: 'A', 2: 'B', 3: 'A'}) {'A': [1, 3], 'B': [2]} ''' new = {} for i in d.values(): if i not in new: new[i] = [] for i in d.items(): new[i[1]].append(i[0]) return new
true
e886cba56ea2047bfd50ea8d233287c8ba56aae1
sforrester23/Python_Basics
/Exercise/Exercise 1.py
1,110
4.5625
5
# Define the following variables # first_name, last_name, age, eye_colour, hair_colour first_name='Ronald' last_name='Macdonaldz' age=83 eye_colour='Fuschia' hair_colour='Clown Red' # Prompt user for input and re-assign these first_name = input('What is your first name, young fellow? ') last_name = input('What is your last name, old bean? ') age = input('Brilliant, {}, and how old are you? '.format(first_name)) eye_colour = input('So, old pal, what colour eyes do you have? ') hair_colour = input('And what lovely colour eyes you do have, my friend! What colour hair do you have? ') # Print them back to the user as conversation print('So, {} {}, you are {} years old! And a fine age it is. You also have {} eyes and {} hair. Fantastic stuff. You must have been shaped by the gods.'.format(first_name, last_name, age, eye_colour, hair_colour)) # Example: 'Hello Jack! Welcome, your age is 26, your eyes are green and your hair is black age=int(age) year_born=(2019-age) year_born=str(year_born) print('As you are {}, you were born in {}! Amazing that I can work that out, hey?'.format(age, year_born))
true
47f19acfe21bb7e78538f136743af2dd8bcfd503
sforrester23/Python_Basics
/Exercise/Exercise 7.py
660
4.21875
4
# Check the rating for the movies: rating = input('What is the rating for this film?: ') rating = rating.lower() if rating == '18': print('No one younger than 18 may see this film.') elif rating == '15': print('No one younger than 15 may see this film.') elif rating == '12a': print('No one younger than 12 may see this film without a parent.') elif rating == '12': print('No one younger than 12 may see this film.') elif rating == 'pg': print('This film has a parental guidance recommendation.') elif rating == 'universal': print('Anyone can watch this film!') else: print('I cannot tell what the rating of this function is...') 6
true
41c67bb2e5912c5406e64e05fa3d0db1a1b95bff
AlphaSunny/study
/study_algorithm/python/Sort/Insert Sortion.py
496
4.1875
4
def insertion_sort(arr): # For every index in array for i in range(1,len(arr)): # Set current values and position currentvalue = arr[i] position = i # Sorted Sublist while position>0 and arr[position-1]>currentvalue: arr[position]=arr[position-1] position = position-1 arr[position]=currentvalue arr =[3,5,4,6,8,1,2,12,41,25] insertion_sort(arr) arr
true
3df3255f03ec16c2ffb34d847699b02267bfdf63
automationhacks/python-ds-algorithms
/recursion/reverse.py
380
4.1875
4
def reverse(string): acc = '' for i in range(len(string) - 1, -1, -1): acc += string[i] return acc def reverse_recursive(string): if len(string) == 1: return string else: return reverse_recursive(string[1:]) + string[0] def test_reverse(): assert reverse('gaurav') == 'varuag' assert reverse_recursive('gaurav') == 'varuag'
false
c1b64e6862d3c944f92636feb00e7a0b89ccbf7b
remsyk/Pyothon_Test_Projects
/Project_7/baseball.py
2,658
4.15625
4
import os #In this file created in step 1, write python code using sqlite3 to: import sqlite3 from contextlib import closing from collections import defaultdict from Blair_Scott_Project_Part1 import BaseballCSVReader #Create a “create_dbs.py” file. def create_db(): #Create a “baseball.db” database with closing(sqlite3.connect('baseball.db')) as connection: cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Baseball_stats") #Create 1 table named “baseball_stats” with the following columns: ''' The "baseball.db" SQLite3 database should look like this: Baseball_stats ======================== player_name text games_played int average real salary real ''' cursor.execute("CREATE TABLE Baseball_stats(" "player_name TEXT," "salary INT," "games_played REAL," "average REAL)") def insert(records, cursor): #Insert each record in a list of ``records`` into the database. # For each record in the list, write and execute an INSERT INTO statement to save the record's information to the correct table. # For each row fetched, iterate with a for loop over the result of your select command for i in records: # Example for baseball: cursor.execute(“INSERT INTO baseball_stats VALUES( ?, ?, ?, ?)”, (name, number_games_played, avg, salary)) cursor.executemany("INSERT INTO Baseball_stats VALUES(?,?,?,?)", (i,)) def select(cursor): selectList =[] # write and execute a SELECT statement to get all the records of the table for the DAO # Example for baseball: cursor.execute(“SELECT player_name, games_played, average, salary FROM baseball_stats;”) # cursor.execute(“SELECT player_name, games_played, average, salary FROM baseball_stats”) #Select all the records from the database. for row in cursor.execute('SELECT * FROM Baseball_stats'): ''' print("player_name ", row[0]) print("salary ", row[1]) print("games_played ", row[2]) print("average ", row[3], "\n") ''' selectList.append(row) #Return them as a list of tuples. return selectList if __name__ == '__main__': salaries = defaultdict(list) create_db() connection = sqlite3.connect('baseball.db') insert(BaseballCSVReader("MLB2008.csv").__getitem__(), connection.cursor()) select(connection.cursor()) connection.commit() connection.close()
true
975e970cbe5f15972a3af0166e3605fb9fa92e2d
FebSun/Algorithm
/sort_algorithm/bubble_sort.py
861
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/4/4 9:12 # @Author : FebSun # @FileName: bubble_sort.py # @Software: PyCharm # 冒泡算法: # 第一次循环:从头到尾一次便利,比较相邻的元素,大数往后移,遍历length-1次,最大数在后面。 # 第二次循环:从头到倒数第一个依次遍历比较,次数为length-2 # . # . # 最后依次遍历:从头到第二个元素,次数为1 # 总计遍历length-1次 def bubble_sort(arr): length = len(arr) for i in range(length-1): for j in range(length-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr if __name__=="__main__": test_arr = [7, 4, 2, 5, 6, 3, 9, 1, 11, 8, 15, 10, 13, 12, 14] sorted_arr = bubble_sort(test_arr) print(sorted_arr)
false
c984180d06393db2ca8d30aeb82aa72ec9666a26
LuanCantalice/Estrutura-de-Repeticao-2-Bimestre
/Questao 2/questao2.py
265
4.125
4
usuario = input("Digite seu usuário: ") senha = input(" Agora digite sua senha: ") while (senha == usuario): print(" Sua senha é igual ao seu usuário! Digite novamente! ") usuario = input("Digite seu usuário: ") senha = input(" Agora digite sua senha: ")
false
28cb96bbd2d7c217b275a78927837a90488cd2ab
victoriandoan/number-guessing
/guessTheNumber.py
1,925
4.375
4
# May 31, 2018 - Victoria's first programming project in Python. # This is a 'Guess the Number' game. The user will be prompted to input # a number between 1 and 10. If they're correct, they win! If they're # incorrect, the game will tell them if they need to guess higher or # lower. The user will get three tries. import random # Intro print("""Welcome to 'Guess the Number'! Guess the number between 1 and 10, and you win!""") print() # Set up the iterator guessCount = 3 # Set up the RNG r = random.randint(1,11) # Print the generated number for testing purposes #print (r) # While the number of guesses is greater than zero while guessCount > 0: if guessCount == 1: print("You have " + str(guessCount) + " guess remaining.") else: print("You have " + str(guessCount) + " guesses remaining.") guess = int(input("What number do you guess? ")) # Check if the guess was correct if guess == r: print("Congratulations! You win!") break else: # Guess is too high if guess > r and guess < 11: print ("Your guess was too high.") guessCount -= 1 print() # Out of tries if guessCount == 0: print("The number was " + str(r) + ".") print("Game Over") break continue # Guess is too low elif guess < r and guess > 0: print("Your guess was too low.") guessCount -= 1 print() # Out of tries if guessCount == 0: print("The number was " + str(r) + ".") print("Game Over") break continue else: print("Sorry, your guess wasn't a number between 1 and 10.") guessCount -= 1 print() continue
true
d384bd58c3fbe828bc9b9d9a186323440f32e47a
EvertonSerpa/Curso_Guanabara_Python_Mundo01
/Exer_20.py
705
4.28125
4
'''Exercício Python 20: O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.''' print() from random import shuffle nome01 = input('Digite o nome do primeiro aluno: ') # variavel 01 nome02 = input('Digite o nome do segundo aluno: ') # variavel 02 nome03 = input('Digite o nome do terceiro aluno: ') # variavel 03 nome04 = input('Digite o nome do quarto aluno: ') # variavel 04 lista = [nome01, nome02, nome03, nome04] # variavel lista shuffle(lista) # embaralahamento do lista print(f'A ordem dos alunos que vão apresentar o trabalho é: {lista}. ') # resultado da ordem do sorteio
false
ff841f319f091e86693c3e8d9c10dc1779d2b159
Witterone/lambdata
/lambdata_witterone/puppy.py
1,385
4.21875
4
#!/usr/bin/env python # Create a class Puppy which takes a: # 1. Name # 2. Age # 3. Weight (random, default from 10-50) # ----Hint---- : __init__ method needed # Create methods for the class which will: # 1. Make the puppy name all upper case # 2. Show the puppy's name - returns: f"The puppy's name is {<puppy name>}"" # Create a child class Leech which will inherit from parent class Puppy. # Include another field for Leech called: # 1. `is_hypoallergenic` - which will be a Boolean True/False # ----Hint---- : super() method needed # Create method for Leech: # 1. `pet_puppy` - returns: f'You pet {<puppy's name>}!! Aww!!!' # Make sure each class/method includes a docstring # Make sure entire script conforms to PEP8 guidelines # Check your work by running the script # Standard Python Library import random class Puppy: # TODO class Leech(Puppy): # TODO example1 = Puppy('James', 5) example2 = Leech('Jonathan', 10, True) if __name__ == "__main__": print(example1.weight) print('---------------------') print(example1.show_name()) print('---------------------') print(example1.make_upper()) print('---------------------') print(example2.is_hypoallergenic) print('---------------------') print(example2.make_upper()) print('---------------------') print(example2.pet_puppy()) print('---------------------')
true
933475538379fc99c4b40d3cb6847fba6e378548
Amayavinod/Progrminglab
/large.py
238
4.21875
4
a=float(input("enter the 1st number : ")) b=float(input("enter the 2nd number :")) c=float(input("enter the 3rd number : ")) if a>b and a>c: print("a is largest ") elif b>c : print("b is largest") else : print("c is largest")
false
5f6e378467b160808824bcffab09929735792898
ChalidaJ/Assignment
/task2/question3T2.py
510
4.125
4
a=10 b=20 c=30 avg=int((a+b+c)/3) print("Avg = ", avg) if avg > a and avg > b and avg > c : print("Avg. is higher than a,b,c") elif avg > a and avg > b : print("Avg. is higher than a,b,c") elif avg > a and avg > c : print("Avg. is higher than a,c") elif avg > b and avg > c : print("Avg. is higher than b,c") elif avg > a : print("Avg. is just higher than a") elif avg > b : print("Avg. is just higher than b") elif avg > c : print("Avg. is just higher than c")
false
f021ea8c5bac04c77b86d9f999a6b509add797fb
Marah-uwase/Password_locker
/user.py
1,578
4.125
4
class User: user_list = [] # empty user list. def __init__(self,first_name, last_name, user_name, password): ''' __init__ method that helps us define properties for our objects. Args: first_name: New user first name. last_name : New user last name. user_name: New user username. password : New user password. ''' self.first_name = first_name self.last_name = last_name self.user_name = user_name self.password = password def save_user(self): User.user_list.append(self) def delete_user(self): ''' delete_user method deletes user objects from the user_list ''' User.user_list.remove(self) @classmethod def find_by_username(cls,username): ''' Method that takes in a username and returns a user that matches that username. Args: username: Username to search for Returns : User details of person that matches the user. ''' for user in cls.user_list: if user.user_name == username: return user @classmethod def find_by_userpassword(cls,userpassword): for password in cls.user_list: if password.password == userpassword: return password @classmethod def display_userInfo(cls): ''' test to check if we can be able to display users saved in user_list ''' return cls.user_list
true
019b5028ececd3027fa16c8d483c04bd05db61ab
cwilkins-8/6
/6.1.py
892
4.15625
4
#6.1 Dictionary Georgia = { 'name' : 'georgia', 'city' : 'leeds', 'food' : 'pasta' } print(Georgia['name']) print(Georgia['city']) favourite_numbers = { 'charlotte' : 8, 'georgia' : 24, 'richard' : 10, 'taylor' : 13, 'lucy' : 2 } print ("Charlotte's favourite number is " + str(favourite_numbers['charlotte'])) print(favourite_numbers['georgia']) print(favourite_numbers['richard']) print(favourite_numbers['taylor']) print(favourite_numbers['lucy']) glossary = { 'integer' : 'An integer is a number', 'float' : 'A float is a number with decimol point', 'string' : 'A string is text used with double quotation marks or single' } print("What is an integer?\n " + glossary ['integer']) for name, city in Georgia.items(): print(name.title() + "'s favourite city is " + city.title() + ".")
false
7af204675e12ac235b1707926129e6e89e78bf07
edenriquez/past-challenges
/morning-training/baseconvertions.py
321
4.15625
4
''' Write a function that takes a list of numbers, a starting base b1 and a target base b2 and interprets the list as a number in base b1 and converts it into a number in base b2 (in the form of a list-of-digits). ''' def to_base(x,base): new_list =[] return new_list a = [1,2,3,4,5,6,7,8,9] print to_base(a,2)
true
61ca2b4d04c8806ce7f0bc3a78918589a1f4997b
myrthedpvn/Make1.2.3
/rekenmachine.py
1,897
4.28125
4
#!/usr/bin/env python """ Rekenmachine script """ # import __author__ = "Myrthe Diepeveen" __email__ = "myrthe.diepeveen@student.kdg.be" __status__ = "Development" def add(x, y): #To add two numbers return x + y def subtract(x, y): #To subtract two numbers return x - y def multiply(x, y): #To multiply two numbers return x * y def divide(x, y): #To divide two numbers return x / y def menu(): print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") def main(): menu() while True: choice = input("Enter choice(1/2/3/4): ") #To let the user choose an input if choice in ('1', '2', '3', '4'): #To check if the choice is one of the four options num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': #To use the 'add' function print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': #To use the 'subtract' function print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': #To use the 'multiply' function print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': #To use the 'divide' function print(num1, "/", num2, "=", divide(num1, num2)) break else: print("Invalid Input") if __name__ == '__main__': # code to execute if called from command-line main()
true
970f44e60cbd65c78a692d9bac59326a8cb0c93f
leandawnleandawn/python-exercises
/Chapter 4/exercise-repetition.py
2,106
4.5625
5
# The following is a series of exercises using TurtleWorld. They are meant to be fun, but # they have a point, too. While you are working on them, think about what the point is. # The following sections have solutions to the exercises, so don’t look until you have # finished (or at least tried). # 1. Write a function called square that takes a parameter named t, which is a turtle. # It should use the turtle to draw a square. # Write a function call that passes bob as an argument to square, and then run the # program again. # 2. Add another parameter, named length, to square. Modify the body so length of # the sides is length, and then modify the function call to provide a second argu‐ # ment. Run the program again. Test your program with a range of values for # length. # 3. Make a copy of square and change the name to polygon. Add another parameter # named n and modify the body so it draws an n-sided regular polygon. # Hint: The exterior angles of an n-sided regular polygon are 360/n degrees. # 4. Write a function called circle that takes a turtle, t, and radius, r, as parameters # and that draws an approximate circle by calling polygon with an appropriate # length and number of sides. Test your function with a range of values of r. # Hint: figure out the circumference of the circle and make sure that length * n = # circumference. # 5. Make a more general version of circle called arc that takes an additional # parameter angle, which determines what fraction of a circle to draw. angle is in # units of degrees, so when angle=360, arc should draw a complete circle. import turtle import math bob = turtle.Turtle() def square(length): for i in range(4): bob.fd(length) bob.lt(90) def polygon(t, length, n, angle = 360): intn = round(n) for i in range(intn): t.fd(length) t.lt(angle/n) def circle(t, r): polygon(t, ((2 * math.pi * r) / 100), 100) def arc(t, r, angle): polygon(t, (((2 * math.pi * r) / 100) * (angle / 360)), 100, angle) square(50) polygon(bob, 100, 6) circle(bob, 50) arc(bob, 100, 180) turtle.mainloop()
true
89003bfd1fea2b57b600e2ac1a58c6b65e1e6a4c
N3r0m5ns3r/Learn-python-the-hard-way3
/Lpthehardway/readingfiles/ex15.py
438
4.15625
4
#!/usr/bin/env python3 # importing argv from sys from sys import argv # args script, filename = argv # opening the filename arg txt = open(filename) # printing and reading the file arg print(f"here's your file {filename}:") print(txt.read()) # reprinting and re reading the file arg print("Type the filename again:") file_again = input('> ') txt_again = open(file_again) print(txt_again.read()) txt.close() txt_again.close()
true
2cb7047b4c6a3223eaa07935b99a54ef7d5e2a2e
namujagtap/Namrata
/Assginment/queans.py
1,197
4.4375
4
# reverse a string and print it on console "python skills". str = "python skills" print("extract all list",str) print("reverse elements",str[::-1]) # assign string to x variable in DD-MM-YYYY format extract and print year from string x=("my birth date is 22-01-2004" ) print('extract all list',x) print('day of my birth is',22) print('month of my birth is',1) print('year of my birth is ',2004) #in a small comapany the avrage salary of three employee is rs 1000 per week if one employee earns rs 1100 and other earns rs 500,how much willthe third employee earn?solve by using java progra s3=3000-1100-500 print("the salary of 3rd employee is",s3) #write program convert a percentage to a fraction (to convert a percentage into fraction let say 30% to a fraction ) per = 30 f = 30/100 n =30 d = 100 numeritor = 30/10 denomenitor = 100/10 print(int(numeritor),"/",denomenitor) #write a program a train 340 m long is running at a speed of 45 km/hr what time will it take to cross a 160 m long tunnel? traind=340 tunneld=160 s=45 speed=45000/3600 distance=340+160 time=distance/speed print(time,"sec time required to cross a tunnel is :",time,"second")
true
8ccb82662d75d5ee108e88ac248f1788b0e2c2a7
mireilea/phyton.proj
/magicdate.py
736
4.25
4
def is_magic_date(): print("running is magic date:") month = int(input('input month value: ')) if (month >= 1) and (month <= 12): print() else: print("invalid month value") day = int(input('input day value:')) if (day >= 1) and (day <= 31): print() else: print("the day value must be 1 and 31 exclusive") year = int(input('input two digit year value:')) if (year >= 10) and (year <= 99): print() else: print("the year value must be positive and it must be two digit") if year is day * month: print("the date", month, day, year, "is magic") else: print("the date", month, day, year, "is not magic") is_magic_date()
false
713006408ac739656e0a26a97bb4e08e326cb3b7
VagnerGit/PythonCursoEmVideo
/desafio_036_aprovando_emprestimo1.py
746
4.1875
4
'''Exercício Python 36: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.''' salario = float(input('Qual o salário: R$')) casa = float(input('Valor da casa: R$')) parcela = int(input('Enquatos anos Você quer pagar: ')) vparcelas = casa / (parcela * 12) saldo = salario*0.30 if vparcelas > saldo: print(f'Com salario de \033[4;33;40m{salario}\033[m não a margem para as parcelas de \033[1;31m{vparcelas:.2f}\033[m') else: print(f'Parabens com salário de {salario} você pode fazer parcelas de {vparcelas:.2f}')
false
9e50a96e22d847349dee2a360955e56c9b80b9bc
VagnerGit/PythonCursoEmVideo
/desafio_049_tabuada_v2.0.py
300
4.15625
4
'''Exercício Python 49: Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for.''' multiplicador = int(input('Digite um Nº ára ver a tabuada: ')) for n in range(0, 11): print(f'{multiplicador} x {n:2} = {multiplicador * n}')
false
d7b5e120a406c1af1b25ea29cbf0787e28c8d901
VagnerGit/PythonCursoEmVideo
/desafio_042_analisando_triângulos_v2.0.py
703
4.15625
4
'''Exercício Python 42: Refaça o DESAFIO 35 dos triângulos,acrescentando o recurso de mostrar que tipo de triângulo será formado:''' r1 = float(input('\033[36mdigite comprimento da 1º reta ')) r2 = float(input('digite comprimento da 2º reta ')) r3 = float(input('digite comprimento da 3º reta\033[m ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os segmentos acima PODEM FORMAR um triângulo', end=' ') if r1 == r2 == r3: print('\033[1:34m EQUILÁTERO! \033[m') elif r1 != r2 != r3 != r1: print('\033[1:34m ESCALENO! \033[m') else: print('\033[1:34m ISÓSCELES! \033[m') else: print() print('\033[31m ñ é triangulo \033[m')
false
b23587cc1c251012be209308f7fe298f0b2f1b8c
muditk/D04
/HW04_ch08_ex04.py
1,957
4.28125
4
#!/usr/bin/env python # HW04_ch08_ex04 # The following functions are all intended to check whether a string contains # any lowercase letters, but at least some of them are wrong. For each # function, describe (is the docstring) what the function actually does. # You can assume that the parameter is a string. # Do not merely paste the output as a counterexample into the documentation # string, explain what is wrong. ############################################################################### # Body def any_lowercase1(s): """ This returns False when the first character of the string is an uppercase, and does not continue to search further. """ for c in s: if c.islower(): return True else: return False def any_lowercase2(s): """This script checks if the literal 'c' is lowercase, and completely fails to check the string. """ for c in s: if 'c'.islower(): return 'True' else: return 'False' def any_lowercase3(s): """Flag returns False for test string "SupporT". Script does not work. """ for c in s: flag = c.islower() return flag def any_lowercase4(s): """ Flag returns True for test string "SupporT". Script works. """ flag = False for c in s: flag = flag or c.islower() return flag def any_lowercase5(s): """This function actually checks if c is uppercase, instead of lowercase """ for c in s: if not c.islower(): return False return True ############################################################################### def main(): # Remove print("Hello World!") and for each function above that is wrong, # call that function with a string for which the function returns # incorrectly. # ex.: any_lowercase_("thisstringmessesupthefunction") print("Hello World!") if __name__ == '__main__': main()
true