blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
98442c545f269213e63e8a6f966c01db056c21f5
Moiseser/pythontutorial
/ex3.py
562
4.375
4
print "I will now count my chickens:" print 'Hens' , 25+30/6 print 'Roosters', 100-25 * 3 % 4 print 'What is 4 % 3' , 4 % 3 print 'Now I will count my eggs:' print 3 + 2 +1 -5 +4 % 2 -1 /4 + 6 print '1 divide by 4' , 1/4 print '1.0 dive by 4.0' , 1.0/4.0 print 'It is true that 3+2 < 5 - 7 ?' print 3 + 2 < 5 - 7 print "What is 3 + 2?" , 3 + 2 print 'What is 5 - 7' , 5 - 7 print "Oh, thats why it's False ." print "How about some more." print "Is it greater?" , 5 > -2 print "Is it greater or equal?" , 5 >= -2 print "Is it less or equal?" , 5<= -2
true
1f13b414cb94ff7e57a9a2a41ac470e41dfd52ba
dongjulongpy/hackerrank_python
/Strings/find_a_string.py
385
4.1875
4
def count_substring(string, sub_string): string_list = list() length = len(sub_string) for i in range(len(string)-length+1): string_list.append(string[i:i+length]) return string_list.count(sub_string) if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
true
76265670bce143a07b85821de09bab6355a40e92
LisaLen/code-challenge
/interview_cake_chals/find_rotation_point.py
1,661
4.125
4
'''I opened up a dictionary to a page in the middle and started flipping through, looking for words I didn't know. I put each word I didn't know at increasing indices in a huge list I created in memory. When I reached the end of the dictionary, I started from the beginning and did the same thing until I reached the page I started at. Now I have a list of words that are mostly alphabetical, except they start somewhere in the middle of the alphabet, reach the end, and then start from the beginning of the alphabet. In other words, this is an alphabetically ordered list that has been "rotated." For example: >>> find_rotation_point(['ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'asymptote', 'babka', 'banoffee', 'engender', 'karpatka', 'othellolagkage']) 5 Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here.''' def find_rotation_point(lst): '''return index of rotation point''' if not lst: return floor_indx = 0 ceiling_indx = len(lst) - 1 while (ceiling_indx - floor_indx) > 1: middle_indx = (ceiling_indx - floor_indx) // 2 + floor_indx if lst[middle_indx] < lst[ceiling_indx]: ceiling_indx = middle_indx else: floor_indx = middle_indx if lst[floor_indx] < lst[ceiling_indx]: return floor_indx return ceiling_indx if __name__ =='__main__': import doctest if doctest.testmod().failed == 0: print('\n***PASSED***\n')
true
0b98b66200151b0dc6bd322824f2d53b37e2329c
LisaLen/code-challenge
/primes/primes.py
927
4.28125
4
"""Return count number of prime numbers, starting at 2. For example:: >>> is_prime(3) True >>> is_prime(24) False >>> primes(0) [] >>> primes(1) [2] >>> primes(5) [2, 3, 5, 7, 11] """ def is_prime(number): assert number >= 0 if number < 2: return False if number == 2: return True if number % 2 == 0: return False n = 3 while n*n < number: if number % n == 0: return False n += 2 return True def primes(count): """Return count number of prime numbers, starting at 2.""" numbers = [] i = 2 j = 0 while j < count: if is_prime(i): numbers.append(i) j += 1 i += 1 return numbers if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. GREAT WORK!\n")
true
1c627ef942bc3401647b955fda0cd4a9139e6e57
iliakur/python-experiments
/test_strformat.py
1,311
4.125
4
"""12/08/2016 my colleague Leela reported getting a weird error. She was trying to perform an equivalent of the following string interpolation: `" a {0}, b {1}".format(some_dict["key"], ["key2"])` She had forgotten to type `some_dict` for the second argument of `format`. However the error she got was unrelated to that. She was namely told that list indices must be integers, not strings. At the time I was pretty certain Unfortunately I didn't get a chance to check her Python interpreter version, so I have to test this in both 3 and 2. """ import pytest def test_format_insert_list(): """I think what Leela was indexing as a dictionary was in fact a list. This test clearly demonstrates that .format can handle raw lists as arguments. """ tpl = "a {0}, b {1}" d = {4: 3} assert tpl.format(d[4], [3]) == 'a 3, b [3]' assert tpl.format(d[4], ["3"]) == "a 3, b ['3']" def test_format_insert_list_str_indx(): """Confirming that we should get the error Leela and I saw if we in fact index a list as if it were a dictionary. """ tpl = "a {0}, b {1}" l = [2, 3] with pytest.raises(TypeError) as exc_info: assert tpl.format(l["4"], ["5"]) == 'a 3, b ["5"]' assert str(exc_info.value) == "list indices must be integers or slices, not str"
true
e50d72ab79c96789a88454a52ceb0c54985130e9
Lusarom/progAvanzada
/ejercicio38.py
825
4.5
4
#Exercise 38: Month Name to Number of Days #The length of a month varies from 28 to 31 days. In this exercise you will create #a program that reads the name of a month from the user as a string. Then your #program should display the number of days in that month. Display “28 or 29 days” #for February so that leap years are addressed. print('List of months: January, February, March, April, May, June, July, August, September, October, November, December') month_name = input("Input the name of Month: ") if month_name == 'February': print('No. of days: 28/29 days') elif month_name in ('April', 'June', 'September', 'November'): print('No. of days: 30 days') elif month_name in ('January', 'March', 'May', 'July', 'August', 'October', 'December'): print('No. of days: 31 day') else: print('Error month name')
true
beeea37473e0c78c74d28ca618548df2fab1cf0b
Lusarom/progAvanzada
/ejercicio40.py
766
4.5
4
#Exercise 40: Name that Triangle #A triangle can be classified based on the lengths of its sides as equilateral, isosceles #or scalene. All 3 sides of an equilateral triangle have the same length. An isosceles #triangle has two sides that are the same length, and a third side that is a different #length. If all of the sides have different lengths then the triangle is scalene. #Write a program that reads the lengths of 3 sides of a triangle from the user. #Display a message indicating the type of the triang print("Input lengths of the triangle sides: ") x = int(input("x: ")) y = int(input("y: ")) z = int(input("z: ")) if x == y == z: print("Equilateral triangle") elif x==y or y==z or z==x: print("isosceles triangle") else: print('Scalene triangle")
true
32799865345f5c901d665edadf4cc0904cbaff3d
DJBlom/Python
/CS1101/Unit_7/Discussion.py
1,141
4.65625
5
""" This is a program to demonstrate how tuples can be usefull loops over lists and dictionaries. """ def listZip(): st = 'Code' li = [0, 1, 2, 3] print('Zip function demo.') t = zip(li, st) for i, j in t: print(i, j) """ The zip function is used to iterate over two or more collections/lists in a parrallel way. Furthermore, the tuple collection it returns can be very useful to navigate the list """ def listEnum(): print('\nEnumerate function demo.') for i, j in enumerate('Code'): print(i, j) """ The enumerate function will iterate over list items and it's indices. """ def listItem(): d = {0 : 'I', 1 : 'love', 2 : 'to', 3 : 'code', 4 : 'CodeForTheWin'} print('\nItem functions demo.') for i, j in d.items(): print(i, j) """ The items function will return a list of tuples/sequence of tuples that are mapped together with a key to the value of that key. """ def main(): listZip() listEnum() listItem() main()
true
4a2455564ea6478e6ea519a97befc90cc8a3aed2
nimkha/IN4110
/assignment3/wc.py
1,391
4.46875
4
#!/usr/bin/env python import sys def count_words(file_name): """ Takes file name and calculates number of words in file :param file_name: :return: number of words in file """ file = open(file_name) number_of_words = 0 for word in file.read().split(): number_of_words += 1 return number_of_words def count_lines(file_name): """ Takes file name and calculates number of lines in file :param file_name: :return: number of lines in file """ number_of_lines = len(open(file_name).readlines()) return number_of_lines def count_characters(file_name): """ Takes file name and calculates number characters in a file. This version excludes white spaces :param file_name: :return: number of characters in file excluding white spaces """ file = open(file_name) data = file.read().replace(" ", "") counter = len(data) return counter def main(): """ Main function, runs the program :return: no return value """ arguments = sys.argv[1:] for file in arguments: number_of_words = count_words(file) number_of_lines = count_lines(file) number_of_characters = count_characters(file) print(f"#characters -> {str(number_of_characters)}, #words -> {str(number_of_words)}, #lines -> {str(number_of_lines)}, file name -> {file}") main()
true
3626f86acddcde796092a53d014f8f50137ace0a
prasannatuladhar/30DaysOfPython
/day17.py
1,685
4.375
4
""" 1) Create a function that accepts any number of numbers as positional arguments and prints the sum of those numbers. Remember that we can use the sum function to add the values in an iterable. 2) Create a function that accepts any number of positional and keyword arguments, and that prints them back to the user. Your output should indicate which values were provided as positional arguments, and which were provided as keyword arguments. 3) Print the following dictionary using the format method and ** unpacking. country = { "name": "Germany", "population": "83 million", "capital": "Berlin", "currency": "Euro" } 4) Using * unpacking and range, print the numbers 1 to 20, separated by commas. You will have to provide an argument for print function's sep parameter for this exercise. 5) Modify your code from exercise 4 so that each number prints on a different line. You can only use a single print call. """ # 1 Solutions def sum_to_any_num(*anynum): return sum(anynum) print(sum_to_any_num(2,4,5)) # 2 Solutions def prnt_info(*name,**info): for n in name: print(f"Namaste! {n}") for k,v in info.items(): print(f"{k.title()}:{v}") prnt_info("Prasanna","Ram","Mahesh", occupation="Engineer", age=36, gender="Male") #3 Solutions country = { "name": "Germany", "population": "83 million", "capital": "Berlin", "currency": "Euro" } template = """ Name:{name}, Population:{population}, Capital:{capital}, Currency:{currency} """ print(template.format(**country)) #4 Solutions # def print_to_20(*num): # print(num) # print_to_20(*range(1,21)) print(*range(1,21),sep=",") #5 Solutions print(*range(1,21),sep="\n")
true
35d7c42f4c010a1e13be3938b4f5a9853ac1be3b
prasannatuladhar/30DaysOfPython
/day16.py
1,224
4.5625
5
""" 1) Use the sort method to put the following list in alphabetical order with regards to the students' names: students = [ {"name": "Hannah", "grade_average": 83}, {"name": "Charlie", "grade_average": 91}, {"name": "Peter", "grade_average": 85}, {"name": "Rachel", "grade_average": 79}, {"name": "Lauren", "grade_average": 92} ] You're going to need to pass in a function as a key here, and it's up to you whether you use a lambda expression, or whether you define a function with def. 2) Convert the following function to a lambda expression and assign it to a variable called exp. def exponentiate(base, exponent): return base ** exponent 3) Print the function you created using a lambda expression in previous exercise. What is the name of the function that was created? """ # 1 Solution def get_name(student): return student["name"] students = [ {"name": "Hannah", "grade_average": 83}, {"name": "Charlie", "grade_average": 91}, {"name": "Peter", "grade_average": 85}, {"name": "Rachel", "grade_average": 79}, {"name": "Lauren", "grade_average": 92} ] sorted_name = sorted(students, key=get_name) print(sorted_name) # 2 Solution exp = lambda bs, expo: bs ** expo # 3 Solution print(exp(2,3))
true
a6b674c546b274b86005d37f47214a4395906407
alexeysorok/Udemy_Python_2019_YouRa
/Basics/03_string.py
927
4.28125
4
greeting = "Hello!" first_name = "Jack" last_name = "White" print(greeting + ' ' + first_name + ' ' + last_name) print(len(greeting)) # длина print(greeting[-1]) print(greeting[2:5]) print(greeting[::-1]) # перевернуть строку print(greeting.upper()) print(greeting.lower()) print(greeting.split()) # разделяет по пробелам # форматирование name = "Jack" age = 23 name_and_age = "My name is {0}. I\'m {1} years old.".format(name, age) name_and_age2 = "My name is {0}. I\'m {1} years old.".format('Dan', 28) name_and_age3 = "My name is {}. I\'m {} years old.".format('Ran', 30) print(name_and_age) week_days = "There are 7 days in a week: {mon}."\ .format(mon="Monday") print(week_days) float_result = 1000 / 7 print('The result of division is {0:1.3f}'.format(float_result)) # new 3.6 name_and_age = f'My name is {name}. I\'m {age} years old' print(name_and_age)
true
2baf17cc2c72406fcc1f3b089a986727cfd25230
ztnewman/python_morsels
/circle.py
619
4.21875
4
#!/usr/bin/env python3 import math class Circle: def __init__(self,radius=1): if radius < 1: raise ValueError('A very specific bad thing happened') self.radius = radius def __str__(self): return "Circle("+str(self.radius)+")" def __repr__(self): return "Circle("+str(self.radius)+")" @property def diameter(self): return self.radius*2 @property def area(self): return (self.radius**2) * math.pi @diameter.setter def diameter(self,diameter): self.diameter = diameter self.radius = diameter / 2
true
52b40ae26017b13d5f259c7790c95987186e71bd
erinszabo/260week_5
/main.py
2,301
4.34375
4
""" Chapter 6 in Runestone Exercises: 2, 3 - Do the recursive search without slicing. 5, 6, 7, 15, 16 """ if __name__ == '__main__': print("") print("") print("2) Use the binary search functions given in the text (recursive and iterative). Generate a random, " "ordered list of integers and do a benchmark analysis for each one. What are your results? Can you explain " "them?") """ BRAINSTORMING: make 2 methods for binary search, one iterative and one recursive. then make a 'binary_race' method that times and compares the two. """ print("") print("3) Implement the binary search using recursion without the slice operator. Recall that you will need to " "pass the list along with the starting and ending index values for the sublist. Generate a random, " "ordered list of integers and do a benchmark analysis.") print("") print("5) Implement the in method (__contains__) for the hash table Map ADT implementation.") print("") print("6) How can you delete items from a hash table that uses chaining for collision resolution? How about if " "open addressing is used? What are the special circumstances that must be handled? Implement the del method " "for the HashTable class.") print("") print("7) In the hash table map implementation, the hash table size was chosen to be 101. If the table gets full, " "this needs to be increased. Re-implement the put method so that the table will automatically resize itself " "when the loading factor reaches a predetermined value (you can decide the value based on your assessment " "of load versus performance).") print("") print("15) One way to improve the quick sort is to use an insertion sort on lists that have a small length (call " "it the “partition limit”). Why does this make sense? Re-implement the quick sort and use it to sort a " "random list of integers. Perform an analysis using different list sizes for the partition limit.") print("") print("16) Implement the median-of-three method for selecting a pivot value as a modification to quickSort. Run " "an experiment to compare the two techniques.") print("")
true
1aba5ddb6b34e4f6ee1a0d11f74a20de7cf975c8
tannazjahanshahi/tamrinpy
/tamrin3.py
1,151
4.3125
4
# # for i in range(6): # # for j in range(i): # # print ('* ', end="") # # print('') # # for i in range(6,0,-1): # # for j in range(i): # # print('* ', end="") # # print('') # numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Declaring the tuple # cnt_odd=0 # odd_list=[] # cnt_even=0 # even_list=[] # for i in numbers: # if i%2==0: # cnt_even+=1 # even_list.append(i) # else: # cnt_odd+=1 # odd_list.append(i) # print(f'odd numbers are {odd_list} and count is : {cnt_odd }') # print(f'even numbers are {even_list} and count is : {cnt_even }') # 8. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. # Note : Use 'continue' statement. # Expected Output : 0 1 2 4 5 # x=0 #false # y=1 #true # if not(0): # print("yes") # def Fibonacci(n): # if n<0: # print("Incorrect input") # # First Fibonacci number is 0 # elif n==1: # return 0 # # Second Fibonacci number is 1 # elif n==2: # return 1 # else: # return Fibonacci(n-1)+Fibonacci(n-2) # # Driver Program # print(Fibonacci(25))
true
2eeee06b978d55b99a68eeffa12eb62a127ee0c3
LinhPhanNgoc/LinhPhanNgoc
/page_63_project_09.py
614
4.21875
4
""" Author: Phan Ngoc Linh Date: 02/09/2021 Problem: Write a program that takes as input a number of kilometers and prints the corresponding number of nautical miles. Use the following approximations: • A kilometer represents 1/10,000 of the distance between the North Pole and the equator. • There are 90 degrees, containing 60 minutes of arc each, between the North Pole and the equator. • A nautical mile is 1 minute of an arc. Solution: .... """ km = float(input("Enter the number of kilometers = ")) nautical = (km * 90 * 60) / 10000 print("Nautical miles =", nautical, "nauts")
true
b4f79d10f725f9ab9120f67282f4d34726f60430
hafizur-r/Python
/week_2/Problem2_5.py
1,324
4.40625
4
""" Problem 2_5: Let's do a small simulation. Suppose that you rolled a die repeatedly. Each time that you roll the die you get a integer from 1 to 6, the number of pips on the die. Use random.randint(a,b) to simulate rolling a die 10 times and printout the 10 outcomes. The function random.randint(a,b) will generate an integer (whole number) between the integers a and b inclusive. Remember each outcome is 1, 2, 3, 4, 5, or 6, so make sure that you can get all of these outcomes and none other. Print the list, one item to a line so that there are 10 lines as in the example run. Make sure that it has 10 items and they are all in the range 1 through 6. Here is one of my runs. In the problem below I ask you to set the seed to 171 for the benefit of the auto-grader. In this example, that wasn't done and so your numbers will be different. Note that the seed must be set BEFORE randint is used. problem2_5() 4 5 3 1 4 3 5 1 6 3 """ """ Problem 2_5: """ import random def problem2_5(): """ Simulates rolling a die 10 times.""" # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(171) # don't remove when you submit for grading for i in range(10): print(random.randint(1,6))
true
34e659a741a9be2903e86f40143d58e38623fa5b
hafizur-r/Python
/week_3/Problem3_4.py
1,400
4.34375
4
#%% """ Problem 3_4: Write a function that is complementary to the one in the previous problem that will convert a date such as June 17, 2016 into the format 6/17/2016. I suggest that you use a dictionary to convert from the name of the month to the number of the month. For example months = {"January":1, "February":2, ...}. Then it is easy to look up the month number as months["February"] and so on. Note that the grader will assume that month names begin with capital letters. *** Tip: In print statements, commas create a space. So you may have difficulty avoiding a space between the 7, 17, and 2016 below and the following comma. I suggest that you build the output as a single string containing the properly formatted date and then print that. You can convert any number to string by using str() and tie the parts together using +. Duplicate the format of the example output exactly. Everything you need to do this is covered in the lectures. *** Here is a printout of my run for June 17, 2016. problem3_4("July",17, 2016) 7/17/2016 """ #%% def problem3_4(mon, day, year): """ Takes date such as July 17, 2016 and write it as 7/17/2016 """ month = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") print(str(month.index(mon)+1)+'/'+str(day)+'/'+str(year))
true
885164b1fd52886a7d065fd8cdadf1b7b15d9d57
yanjun91/Python100DaysCodeBootcamp
/Day 9/blind-auction-start/main.py
978
4.15625
4
from replit import clear from art import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program.") continue_bid = True bidders = [] while continue_bid: name = input("What is your name?: ") bid = int(input("What's your bid?: $")) # Store names and bids into dictionary then into list bidder = {} bidder["name"] = name bidder["bid"] = bid bidders.append(bidder) more_bidder = input ("Are there any other bidders? Type 'yes' or 'no'.\n") if more_bidder == "no": continue_bid = False elif more_bidder == "yes": clear() def find_bid_winner(bidders_list): highest_bid = 0 winner = "" for bidder_dict in bidders_list: if bidder_dict["bid"] > highest_bid: winner = bidder_dict["name"] highest_bid = bidder_dict["bid"] print(f"The winner is {winner} with a bid of ${highest_bid}") find_bid_winner(bidders)
true
a196a7540550ffb301675dbc5138757faabf422a
MaGo1981/MITx6.00.1x
/MidtermExam/Sandbox-ExtraProblems-NotGraded/Problem9.py
928
4.59375
5
''' Problem 9 1 point possible (ungraded) Write a function to flatten a list. The list contains other lists, strings, or ints. For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5] def flatten(aList): ''' ''' aList: a list Returns a copy of aList, which is a flattened version of aList ''' ''' Click to expand Hint: How to think about this problem Recursion is extremely useful for this question. You will have to try to flatten every element of the original list. To check whether an element can be flattened, t he element must be another object of type list. Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements. Note that we ask you to write a function only -- you cannot rely on any variables defined outside your function for your code to work correctly. Code Editor 1 ''' # Paste your function here
true
f665521d39d777428e35e4c66706e0ccf5eed10d
camitt/PracticePython_org
/PP_Exercise_1.py
1,175
4.28125
4
from datetime import date # Exercise 1 # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. # Extras: # # 1. Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python) # 2. Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button) def returnYear(age): intAge = int(age) birthYear = date.today().year - intAge birthdayOccurred = input("Has your birthday already occurred this year? (Y/N): ") if birthdayOccurred.lower() == "n": birthYear -= 1 return birthYear + 100 def getInfo(): name = input("What is your name? ") age = input("Please enter your current age: ") repeat = input("Enter a number: ") return name, age, repeat def main(): name, age, repeat = getInfo() centuryAge = returnYear(age) for i in range(int(repeat)): print(name + " you will turn 100 in the year " + str(centuryAge)) main()
true
f60727bc1404c6a3631e4a9b158d847abe44afef
AnkyXCoder/PythonWorkspace
/practice.py
939
4.53125
5
# Strings first_name = "Ankit" last_name = "Modi" print(first_name) print(last_name) full_name = first_name + last_name print(full_name) # printing name with spaces full_name = first_name + ' ' + last_name print(full_name) # OR you can print it like this also # with no difference print(first_name + ' ' + last_name) # when you want to write long strings, you can use ''' or """ long_string = '''What do you want to do today evening?? let's go to theatre to watch a fun movie.... okay, let's go''' print(long_string) long_string1 = """What do you want to do today evening?? let's go to theatre to watch a fun movie.... okay, let's go""" print(long_string1) # below are the examples of string concatenation # use type() to get the type of variable print("Printing,", 'C', " and its type is ", type('C')) print("Printing,", "Hello", " and its type is ", type("Hello!")) print("Printing,", 100, " and its type is ", type(100))
true
43491586c77d23d9aba8416dd658cc7bf795f917
AnkyXCoder/PythonWorkspace
/Object Oriented Programming/Abstraction.py
1,463
4.5625
5
# Create a class and constructors # Abstraction # create an object class PersonalCharacter: # global attribute _membership = True # constructor def __init__(self, name = 'anonymous', age = 0, strength = 100): # dunder method """This is a constructor using __init__ which is called a duncder method. This constructor is called every time an object is created. It instantiates the object with the given attributes of the class. Able to access data and properties unique to each instance.""" # attributes """Protected members are those members of the class which cannot be accessed outside the class but can be accessed from within the class and it’s subclasses.""" self._name = name # to make attribute protected self._age = age # to make attribute protected """Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class.""" self.__strength = strength # to make attribute private # instantiate person1 = PersonalCharacter("Andy", 25) person2 = PersonalCharacter("Cindy", 22) # location of object in memory print(person1) print(person2) # getting details of the objects print(person1._name, person1._age, "membership", person1._membership) print(person2._name, person2._age, "membership", person2._membership)
true
180c54cc32d9d18b773f9a91e734b19f254c5014
AnkyXCoder/PythonWorkspace
/python basics/dictionary.py
2,859
4.3125
4
# Dictionary # data structure that stores data in terms of keys and values as pairs # list is a sorted data structure, list of people in queue # dictionary has no order, list of a persons belongings in wardrobe user2 = dict(name = "Johny") print(user2) # another way of creating dictionary dictionary = { # immutable keys types 'a' : 45, 'b' : 99, 'c' : True, 'd' : [1,2,3], 'e' : 'here is your string', 123 : 'hi user', True : 'hello', #[100] : True can not be used as lists are muttable, can be manipulated } # Getting values from keys print ('dictionary contains:', dictionary) print(dictionary['a']) print(dictionary['b']) print(dictionary['c']) print(dictionary['d']) print(dictionary['e']) print(dictionary[123]) print(dictionary[True]) dictionary[123] = 'hi admin' # replaces the previous value print(dictionary[123]) my_list = [ { 'a' : [1,2,3], 'b' : 'hello', 'c' : True }, { 'a' : [4,5,6], 'b' : 'there', 'c' : False } ] # Getting values from keys print(my_list[0]['a'][2]) print(my_list[1]['a'][1]) # Dictionary methods user = { 'greetings' : "hello", 'basket' : [1,2,3], 'weight' : 70, } print(user['basket']) # get method print(user.get('age')) # to check whether key 'age' is available in user or not print(user.get('age', 55)) # get age from user, if age is not available in user, then displays 55 print(user.get('weight', 60)) # get weight from user, if weight is not available in user, then display 60 # search for keys in dictionaries print("does basket available in user?",'basket' in user) print("does size available in user?",'size' in user) print("does hello available in user?",'hello' in user) # searching in keys method print("does basket available in user keys?", 'basket' in user.keys()) print("does hello available in user keys?", 'hello' in user.keys()) # searching in values method print("does basket available in user values?", 'basket' in user.values()) print("does hello available in user values?", 'hello' in user.values()) # seraching in items method print("items in user: ", user.items()) print("does hello available in user items?", 'hello' in user.items()) # copying the dictionary method user3 = user.copy() print("user3 now contains: ", user3) #clearing a dictionary user.clear() # clears dictionary print("user is now: ", user) print("user3 still contains: ", user3) # pop method print(user3.pop("weight")) # pops the item with key "weight" print(user3) # popitem method print(user3.popitem()) # randomly pops any item print(user3) # update method user3.update({'weight' : 45}) # updates key to provided value print(user3) user3.update({'age': 15}) # updates dictionary with new item if key is not available print(user3)
true
81982a4ea086b205b116518aa20113f130b6d0d8
AnkyXCoder/PythonWorkspace
/Object Oriented Programming/Modifying_Dunder_Methods.py
1,175
4.75
5
# Whenever an Object is created and instantiated, it gest access to all the basic Dunder Methods available to it as per Python # Programming Language. # By defining the Dunder Method in the Class Encapsulation, the access to Dunder Methods are modified. class SuperList(list): # Defining SuperList as the Subclass of the List Class def __len__(self): # This __len__() Dunder Method will be used and the __len__() Dunder Method provided by Python will not be used. return 1000; superlist1 = SuperList() print(len(superlist1)) # Appending Number to the Superlist superlist1.append(5) print(superlist1) # Appending Number to the Superlist superlist1.append(10) print(superlist1) # Getting Number from the Superlist print(f'superlist1[0]:{superlist1[0]}') print(f'superlist1[1]:{superlist1[1]}') # Check if SuperList is a subclass of List print(f'SuperList is a subclass of List: {issubclass(SuperList, list)}') # Check if SuperList is a subclass of Tuple print(f'SuperList is a subclass of Tuple: {issubclass(SuperList, tuple)}') # Check if SuperList is a subclass of Object print(f'SuperList is a subclass of Object: {issubclass(SuperList, object)}')
true
45c8680dc29404c7cd53bf30445d9c821705c9d4
zhjohn925/niu_algorithm
/S03_Interpolation_search.py
1,573
4.5625
5
# Interpolation search can be particularly useful in scenarios where the data being searched is uniformly # distributed and has a large range. # For example: # Large Data Sets: If you have a large data set and the elements are uniformly distributed, interpolation search # can provide faster search times compared to binary search. This is because interpolation search dynamically # adjusts the search range based on the estimated position of the target element, potentially reducing the number # of iterations required. def interpolation_search(arr, target): """ Performs interpolation search on a given sorted list to find the target element. Parameters: arr (list): The sorted list to be searched. target: The element to be found. Returns: int: The index of the target element if found, or -1 if not found. """ low = 0 high = len(arr) - 1 while low <= high and arr[low] <= target <= arr[high]: if low == high: if arr[low] == target: return low return -1 pos = low + ((target - arr[low]) * (high - low)) // (arr[high] - arr[low]) if arr[pos] == target: return pos elif arr[pos] < target: low = pos + 1 else: high = pos - 1 return -1 # Element not found # Example usage my_list = [1, 3, 5, 7, 9, 11] target_element = 7 result = interpolation_search(my_list, target_element) if result != -1: print(f"Element {target_element} found at index {result}.") else: print("Element not found.")
true
20c2f4cf45a6a501895565d2f40273263d77430c
zhjohn925/niu_algorithm
/L20_Bucket_Sort.py
2,347
4.1875
4
# Bucket Sort is a linear-time sorting algorithm on average when the input elements are uniformly # distributed across the range. # It is commonly used when the input is uniformly distributed over a range or when the range of values # is relatively small compared to the input size. def bucket_sort(arr): # Create an empty list of buckets buckets = [] # Determine the number of buckets based on the input size num_buckets = len(arr) # Initialize the buckets for _ in range(num_buckets): buckets.append([]) # Place elements into their respective buckets for num in arr: index = int(num * num_buckets) buckets[index].append(num) # Sort each bucket individually for bucket in buckets: insertion_sort(bucket) # Concatenate the sorted buckets into the final sorted array sorted_arr = [] for bucket in buckets: sorted_arr.extend(bucket) return sorted_arr # Insertion Sort works by dividing the input array into two parts: the sorted portion and the unsorted portion. # 1. Start with the first element (assume it is already sorted). # 2. Take the next element from the unsorted portion and insert it into the correct position in the sorted portion. # 3. Compare the selected element with the elements in the sorted portion, shifting them to the right until # the correct position is found. # 4. Repeat steps 2 and 3 until all elements in the unsorted portion are processed. # The insertion sort algorithm has a time complexity of O(n^2) in the worst case, # where n is the number of elements in the array. However, it performs well on small lists or # partially sorted lists, where it can have a time complexity close to O(n) and exhibit good # performance. def insertion_sort(arr): # Perform insertion sort on the given array for i in range(1, len(arr)): # sorted array is before i; unsorted array is i and after i card = arr[i] # pick i j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] # push larger than key [i] to the right j -= 1 arr[j + 1] = card # insert the card # Example usage arr = [0.8, 0.1, 0.5, 0.3, 0.9, 0.6, 0.2, 0.4, 0.7] sorted_arr = bucket_sort(arr) print("Sorted array:", sorted_arr)
true
f8ca4890c4833c2d752a3dcf14dc404089e7c85a
Aka-Ikenga/Daily-Coding-Problems
/swap_even_odd.py
527
4.21875
4
"""Good morning! Here's your coding interview problem for today. This problem was asked by Cisco. Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on. For example, 10101010 should be 01010101. 11100010 should be 11010001. Bonus: Can you do this in one line?""" def reverse_bytes(b): b = list(str(b)) for i in range(0,8,2): b[i],b[i+1] = b[i+1], b[i] return int(''.join(b)) print(reverse_bytes(11100010))
true
a26239a775b14953e7dfe6c922bbf7a95b7e6a69
juliangyurov/js-code
/matrix.py
1,170
4.71875
5
# Python3 program to find the sum # of each row and column of a matrix # import numpy library as np alias import numpy as np # Get the size m and n m , n = 3, 3 # Function to calculate sum of each row def row_sum(arr) : sum = 0 print("\nFinding Sum of each row:\n") # finding the row sum for i in range(3) : for j in range(3) : # Add the element sum += arr[i][j] # Print the row sum print("Sum of the row",i,"=",sum) # Reset the sum sum = 0 # Function to calculate sum of each column def column_sum(arr) : sum = 0 print("\nFinding Sum of each column:\n") # finding the column sum for i in range(3) : for j in range(3) : # Add the element sum += arr[j][i] # Print the column sum print("Sum of the column",i,"=",sum) # Reset the sum sum = 0 # Driver code if __name__ == "__main__" : arr = [[4, 5, 6], [6, 5, 4], [5, 5, 5]] # Get the matrix elements # x = 1 # for i in range(m) : # for j in range(n) : # arr[i][j] = x # x += 1 # Get each row sum row_sum(arr) # Get each column sum column_sum(arr) # This code is contributed by # ANKITRAI1
true
64fefed9d00b683cbbcc88668ed7d17baef8dd57
elizabethgulsby/python101
/the_basics.py
2,376
4.25
4
# print "Liz Gulsby" # name = "Liz Gulsby" # name = "Liz " + "Gulsby" # fortyTwo = 40 + 2; # print fortyTwo # fortyTwo = 84 / 2; # print fortyTwo; # array...psyche! Lists (in Python) animals = ['wolf', 'giraffe', 'hippo']; print animals print animals[0] print animals[-1] # gets the last element - hippo, here animals.append('alligator'); print animals # To delete an index, use the remove method animals.remove('wolf') print animals # del animals[0] - also deletes an index where specified # To go to a specific location: we can insert into any indice with "insert" (like splice) animals.insert(0, 'zebra') print animals #To overwrite a certain index, see directly below animals[0] = 'horse' print animals # pop works the same way - remove the last element animals.pop() print animals #split works the same way as well (below, turning a string into an array) dc_class = "Michael, Paul, Mason, Casey, Connie, Sarah, Andy" dc_class_as_array = dc_class.split(", ") print dc_class_as_array #Sorted method will sort, but not change the actual array print sorted(dc_class_as_array) print dc_class_as_array # prints array as it was declared sorted_class = sorted(dc_class_as_array) print sorted_class dc_class_as_array.sort(); #this will change the array from its original configuration print dc_class_as_array #Reverse method - reverses the array, NOT on value, but on index dc_class_as_array.reverse() print dc_class_as_array # len attribute - works like .length in JS print len(dc_class_as_array) print dc_class_as_array[0] #will print Sarah because array was previously reversed # slice in JS is [x:x] # Creates a copy of the array; does not mutate the array print dc_class_as_array[2:3] print dc_class_as_array # For loop is for>what_you_call_this_one>in>var # no brackets! for student in dc_class_as_array: # indentation matters in python! print student; for i in range(1, 10): print i; #python will create the numbers for you for i in range(0, len(dc_class_as_array)): print dc_class_as_array[i] # functions in python - not a function! It is a "definition", ergo def: def sayHello(): # just like for loops, : is the curly brace in Python for functions # indentation matters, just like the for loop print "Hello, world!"; sayHello(); def say_hello_with_name(name, state = []): print "Hello, " + name; name = "Liz" say_hello_with_name(name);
true
f4d5d91147e0a5749f7570a2fd85133fd4fcddaf
down-dive/python-practice
/maxNum.py
596
4.3125
4
# Max Num # In this activity you will be writing code to create a function that returns the largest number present in a given array. # Instructions # - Return the largest number present in the given `arr` array. # - e.g. given the following array: arr = [1, 17, 23, 5, 6]; # - The following number should be returned: # 17; def max_num(list): number = list[0] # current_num = 0 for i in list: current_num = list[i] if current_num > number: number = current_num else: continue print(current_num) max_num(arr)
true
cbc3fe3f32e2879d6594aef7746f7007dceb2743
Cwagne17/WordCloud-Generator
/WordCloud.py
2,114
4.1875
4
# Word Cloud # # This script recieves a text input of any length, strips it of the punctuation, # and transforms the words into a random word cloud based on the frequency of the word # count in the text. # # To try it - on ln20 change the .txt file to the path which youd like to use. ENJOY! import wordcloud import numpy as np from matplotlib import pyplot as plt from IPython.display import display import fileupload import io import sys #open the .txt file you want to make a word cloud for then run text_file = open("pg63281.txt", "r") file_contents = text_file.read() def calculate_frequencies(file_contents): # Here is a list of punctuations and uninteresting words you can use to process your text uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"] word_count = {} text_file = "" #Removes punctuation for char in file_contents: if char.isalpha(): text_file+=char else: text_file+=" " text_set = text_file.split() #Frequency Ctr for word in text_set: if not word.lower() in uninteresting_words: if word in word_count: word_count[word.lower()]+=1 else: word_count[word.lower()]=1 #wordcloud cloud = wordcloud.WordCloud() cloud.generate_from_frequencies(word_count) return cloud.to_array() myimage = calculate_frequencies(file_contents) plt.imshow(myimage, interpolation = 'nearest') plt.axis('off') plt.show()
true
0c05275b5642bdfaa6db3f433c2983c9f9f74c70
klivingston22/tutorials
/stingzz.py
465
4.15625
4
str = 'this is string example....wow!!!' print str.capitalize() #simply capitalises the first letter sub = 'i' print str.count (sub, 4, 40) # this should output 2 as 'i' appears twice sub = 'wow' print str.count(sub) # this should output 1 as 'wow' only appears once print len(str) # this should output 33 as there are 32 characters in our string print str.upper() # converts our string to uppercase print str.lower() # converts our string to lowercase
true
cd728160534e09d7cb8adee8b4bebaaf81d083a3
shivanikarnwal/Python-Programming-Essentials-Rice-University
/week2-functions/local-variables.py
853
4.1875
4
""" Demonstration of parameters and variables within functions. """ def fahrenheit_to_celsius(fahrenheit): """ Return celsius temperature that corresponds to fahrenheit temperature input. """ offset = 32 multiplier = 5 / 9 celsius = (fahrenheit - offset) * multiplier print("inside function:", fahrenheit, offset, multiplier, celsius) return celsius temperature = 95 converted = fahrenheit_to_celsius(temperature) print("Fahrenheit temp:", temperature) print("Celsius temp:", converted) # Variables defined inside a function are local to that function fahrenheit = 27 offset = 2 multiplier = 19 celsius = 77 print("before:", fahrenheit, offset, multiplier, celsius) newtemp = fahrenheit_to_celsius(32) print("after:", fahrenheit, offset, multiplier, celsius) print("result:", newtemp)
true
824d7672f35bf799e5ce0914c29bfed54805866d
siddeshshewde/Competitive_Programming_v2
/Daily Coding Problem/Solutions/problem002.py
1,075
4.1875
4
""" This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? """ def productExceptSelf(arr): solution = [] for i in range(0, len(arr)): product = 1 for j in range(0, len(arr)): if i==j: continue product *= arr[j] solution.append(product) return solution print (productExceptSelf([1, 2, 3, 4, 5])) == [120, 60, 40, 30, 24] print (productExceptSelf([3, 2, 1])) == [2, 3, 6] print (productExceptSelf([1])) == [1] print (productExceptSelf([10, 15, 3, 7])) == [315, 210, 1050, 450] """ SPECS: TIME COMPLEXITY: O(n^2) SPACE COMPLEXITY: O(n) """
true
725fd29a6a090a89a375b345965e88b4bbb173d8
DanishKhan14/DumbCoder
/Python/Arrays/bestTimeToBuySellStock.py
581
4.3125
4
""" Max profit that we can get in a day is determined by the minimum prices in previous days. For example, if we have prices array [3,2,5,8,1] we can calculate the min prices array [3,2,2,2,1] and get the difference in our max profit array [0,0,3,6,0]. We can see clearly the max profit is 6, which is buy from the index 1 and sell in index 3. """ def maxProfit(prices): min_seen, max_profit = float('inf'), 0 for p in prices: min_seen = min(min_seen, p) curr_profit = p - min_seen max_profit = max(curr_profit, max_profit) return max_profit
true
280a5cbb31989e73535ff4b77dc9f727ca36dd8a
ktb702/AutomateTheBoringStuff
/sum.py
854
4.15625
4
# PROBLEM STATEMENT # If we list all the natural numbers between 1 and 10 (not including 1 or 10) that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Write code using a language of your choice that will find the sum of all the multiples of 3 or 5 between 1 and 1000 (not including 1 or 1000) and display the result. # HINTS # Start small. Write code that solves this problem for all numbers below 10 first and verify the result is 23. After that, try solving it for 100, then 1000. An incremental approach will make sure you can think your way through. def main(): sum = 0 #initialize the sum i = 2 #start incrementing from 2 (as 1 and 1000 are excluded) while i < 1000: if(i%3==0 or i%5==0): sum += i i += 1 print("The sum is: " + str(sum)) main()
true
37f59db3e5bb8925c6913bf7f309c6e375da0069
gerardoxia/CRACKING-THE-CODING
/1.8.py
636
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def isSubstring(str1,str2): length1=len(str1) length2=len(str2) check=True if length1>length2: return False for index2 in range(length2-length1+1): index=index2-1 for index1 in range(length1): index=index+1 if str1[index1]!=str2[index]: check=False break check=True if check==True: break return check def isRotation(str1,str2): str3=str2+str2 return(isSubstring(str1,str3)) str1='waterbottle' str2='erbottlewate' print(isRotation(str1,str2))
true
31339c4dfd1287b66e689816a8f2ba69b4ceb88f
katherine-davis/katherine-davis.github.io
/day 12.py
1,525
4.15625
4
########################################################################### #********************************--day 12--******************************** ##Write a function called initials ##it to take in three perameters ## first name ## last name ## and middle name ## and then return their initials firstName = input ("What is your first name? ") middleName = input("What is your middle name? ") lastName = input("What is your last name? ") def initials(firstName,middleName, lastName): numLettersFirst = len (firstName) numLettersMiddle = len (middleName) numLettersLast = len (lastName) firstInitial = firstName[0] middleInitial = middleName [0] lastInitial = lastName [0] return "Your initials are: " + firstInitial + "." + middleInitial + "." + lastInitial + "." print (initials(firstName, middleName, lastName)) def fancyInitials(fromTheEnd, first, middle, last): if fromTheEnd == False: answer = initials(first, middle, last) return answer else: lastFirstInitial = first[len(first-1)] lastMiddleInitial = middle[len(middle-1)] lastLastInitial = last[len(last-1)] firs = str(lastFirstInitial) mids = str(lastMiddleInitial) lass = str(lastLastInitial) return firs + "." + mids + "." + lass + "." print (fancyInitials (True, firstName, middleName, lastName)) ## ##THIS DOESNT WORK AND I WANT LISTENING SO IM KINDA SCREW BUTS ITS FINE
true
3f70f8f5a551e0daebf6ef8f8b083fd552bff472
qzlgithub/MathAdventuresWithPython
/ex1.2CircleOfSquares.py
303
4.15625
4
# Write and run a function that draws 60 squares, turning right 5 degrees after each square. Use a loop! from turtle import * shape('turtle') speed(0) def createSquares(): for j in range(4): forward(100) right(90) for j in range(60): createSquares() right(5)
true
6333f91ccd0c372887a2367b29e3fbbb0a2b0d9c
AlexOfTheWired/cs114
/FinalProject/Final_Project.py
2,346
4.125
4
""" Final Project Proposal() Create a cash register program. - On initialize the user sets amount of Bills and Coins in register (starting bank amount) - Set Sales Tax - sales_tax = 2.3% - Then print Register status: - Amount of Coins and Bills - Total cash amount Render Transaction: (Start with empty list... dictionary?) - Input item price ( append price to list... dictionary?) transaction_0001 = { 'Item #1': 3.50, 'Item #2': 11.99, 'Item #3': 2.30, 'Item #4': 23.00 } - Calculate Sub Total ( ) - Calculate balance due/TOTAL ( use sum() on item list items + sales_tax) - Input amount tendered ( input how much of each unit was given ) - Calculate change return - Coins - Bills Print Receipt FORMAT EXAMPLE ====================================== - ( STORE NAME ) - list price ========================== - Item #1 $3.50 - Item #2 $11.99 - Item #3 $2.30 - Item #4 $23.00 -------------------------- - Sub Total $40.79 - SALES TAX $0.00 - Total $40.79 - Cash $50.00 - CHANGE ===> $9.23 ========================== Transaction Number: 0001 ===================================== - Make function that stores transaction data for later use. - Complete transaction (reset tranaction dictionary or start new tranaction list.) - Record amount of coins and bills were exchanged after transaction. - how many coins and bills were taken out of register? - how many coins and bills were taken in after transaction? Print Register status: (Audit Tally) - All Transactions ( Make function that stores transaction data? Transaction Class! Each transaction creates a new instance. ) - Amount of Coins and Bills - Total cash amount I can even make a GUI for this! !!!GUI IS A MUST NOW!!! (Destroy Register) Possible Bugs: - register runs out of bills or coins - customer pays in FUCKING PENNIES!!! - change back requires (1 five, 4 singles, 2 dimes, 3 pennies). but register does not have any fives. - """ # Setup # Input # Transform # Output
true
d60c724b32214d29b29a8cc0bf2b1fd47b82f3be
Environmental-Informatics/python-learning-the-basics-Gautam6-asmita
/Second attempt_Exercise3.3.py
1,009
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Created on 2020-01-16 by Asmita Gautam Assignment 01: Python - Learning the Basics Think Python Chapter 3: Exercise 3.3 Modified to add header and comments for resubmission on 2020-03-04 """ """ While considering th each rows of the grid we can see 2 patters of the rows The first pattern is +----+----+ and the second is | | | """ ##Defining a function first to print a first row of matrix def first(): print('+----+----+') ##Defining a function second to print a second row of matrix def second(): print('| | |') ##Defining a function grid to call a mixture of first and second function so it appears like a matrix" def grid(): first() second() second() second() second() first() second() second() second() second() first() #Displaying the function "grid" grid() """ Here the functions used are def: used to define a function, print: will print everything as indicated within the ' ' """
true
df1ee3a21892feab3d619c813550c104e702370a
fantastic-4/Sudoku
/src/Parser/validator.py
2,874
4.15625
4
class Validator: def __init__(self): self.digits = "123456789" self.rows = "ABCDEFGHI" def validate_values(self,grid): '''Function to validate the values on grid given. Return True if their values are numeric or False if their not.''' full_line="" for line in grid: full_line += (line.strip(" ").strip("\n")) chars = [c for c in grid if c in self.digits or c in "0."] return (len(chars) == 81 and len(full_line) == len(chars)) def set_matrix(self, A, B): '''__set_matrix__ product of elements in A and elements in B.''' return [a+b for a in A for b in B] def __get_ini_row_and_ini_col__(self,key): '''Function to set the top-left coordinate of the square where the number is about to fit Return 2 variables, row and column where the square begins''' row = key[0] col = key[1] if(row=="A" or row=="B" or row=="C"): ini_row = 0 elif(row=="D" or row=="E" or row=="F"): ini_row = 3 else: ini_row = 6 if(col=="1" or col=="2" or col=="3"): ini_col = 1 elif(col=="4" or col=="5" or col=="6"): ini_col = 4 else: ini_col = 7 return ini_row,ini_col def check_square(self,num,key, values): '''Function to validate if the number is already in the square 3x3 Return True if can be set on the square, False if the number is already on it''' flag = True ini_row, ini_col = self.__get_ini_row_and_ini_col__(key) lim_row = ini_row + 2 aux = ini_col lim_col = ini_col + 2 while ini_row <= lim_row and flag: ini_col = aux while ini_col <= lim_col: if(values[self.rows[ini_row]+str(ini_col)] == num and key != self.rows[ini_row]+str(ini_col) and values[self.rows[ini_row]+str(ini_col)] != "0"): flag = False break ini_col += 1 ini_row += 1 return flag def check_lines(self,num, key, values): '''Function to validate if the number is already in the row or column Return True if can be set on the cell, False if the number is already on row or column''' flag = True row = key[0] col = key[1] for i in self.digits: if(values[(row+i)] == num and not(i in key) and values[(row+i)] != "0"): flag = False break if(flag): for j in self.rows: if(values[j+col] == num and not(j in key) and values[j+col] != "0"): flag = False break return flag
true
bb521b8932abe5d21f01a144b5c384caa32daf2e
FelixFelicis555/Data-Structure-And-Algorithms
/GeeksForGeeks/Sorting/Bubble_Sort/bubble_sort.py
436
4.125
4
def bubbleSort(list,n): for i in range(0,n-1): for j in range(0,n-i-1): if list[j]>list[j+1]: #swap temp=list[j] list[j]=list[j+1] list[j+1]=temp print("Sorted Array : ",end=' ') print(list) def main(): list=[] print("Enter the numbers in the list(Enter x to stop): ") while True: num=input() if num=='x': break list.append(int(num)) bubbleSort(list,len(list)) if __name__ == '__main__': main()
true
7c9aae80093542f3b41713cdffcf3fb093407be8
jancal/jan2048python
/plot_ols.py
2,296
4.34375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Linear Regression Example ========================================================= This example uses the only the first feature of the `diabetes` dataset, in order to illustrate a two-dimensional plot of this regression technique. The straight line can be seen in the plot, showing how linear regression attempts to draw a straight line that will best minimize the residual sum of squares between the observed responses in the dataset, and the responses predicted by the linear approximation. The coefficients, the residual sum of squares and the variance score are also calculated. """ # Code source: Jaques Grobler # License: BSD 3 clause import numpy as np from sklearn import linear_model # Load the diabetes dataset # diabetes = datasets.load_diabetes() # Use only one feature # diabetes_X = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]] def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) # get the number of lines in the file returnMat = np.zeros((numberOfLines, 16)) # prepare matrix to return classLabelVector = [] # prepare labels return fr = open(filename) index = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.split('\t') returnMat[index, :] = listFromLine[0:16] classLabelVector.append(int(listFromLine[-1])) index += 1 return returnMat, classLabelVector datingDataMat, datingLabels = file2matrix('E:\PycharmProjects\machine_learning\jan2048\data.txt') diabetes_X_train = datingDataMat diabetes_y_train = datingLabels # diabetes_X_test = [[4, 4], [5, 5]] # diabetes_y_test = [4, 5] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(diabetes_X_train, diabetes_y_train) print('Coefficients: \n', regr.coef_) # print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) print(regr.predict([[16, 0, 4, 0, 16, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0], [0, 0, 0, 0, 32, 0, 0, 0, 4, 0, 0, 2, 2, 0, 4, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 2, 2, 2], [32, 2, 2, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]]))
true
2535cb0e40bc6cfdec4510b6d264a9a7f8a711c8
rachaelthormann/Project-Euler-Python
/Problem3.py
701
4.21875
4
""" File name: Problem3.py Description: This program will find the largest prime factor of the number 600851475143. Author: Rachael Thormann Date Created: 3/21/2016 Date Last Modified: 3/21/2016 Python Version: 3.4 """ def largest_prime_factor(num): """Finds the largest prime factor.""" i = 2 # largest prime factor will never be greater than square root of i # because we divide the divisors out of the number while i * i <= num: # if n divides evenly by i, replace num by num // i if (num % i == 0): num //= i # increment i else: i += 1 print(num) largest_prime_factor(600851475143)
true
3b5e0d1bf01b242fac32661aba45c6d6a0983f6c
kalnaasan/university
/Programmieren 1/PRG1/Übungen/Übung_06/Alnaasan_Kaddour_0016285_3.py
1,390
4.125
4
""" This script is the solution of Exercise Sheet No.4 - Task 3 and 4 """ __author__ = "0016285: Kaddour Alnaasan" __credits__ = """If you would like to thank somebody i.e. an other student for her code or leave it out""" __email__ = "qaduralnaasan@gmail.com" def length_list(text): length = len(text) return length def invert_list(text): new_text = "" for i in range(len(text)-1, -1, -1): new_text += text[i] print("2) The invert Text:", new_text) return True def multiplied_list(text): """""" my_default_param = 2 new_text = text * my_default_param return new_text def return_tow_character(text): """""" sobject = slice(2, 4, 1) return text[sobject] def read_text(text): """""" len_text = length_list(text) sobject = slice(len_text-4, len_text, 1) new_text = text[sobject] return return_tow_character(new_text) def main(): """ Docstring: The Main-Function to run the Program""" text = input("Geben Sie einen Text ein:") length_text = length_list(text) # 1 print("1) The Length of Text:", str(length_text)) # 1 invert_list(text) # 2 multi_text = multiplied_list(text) # 3 print("3) The multiple Text:", multi_text) # 3 tow_characters = read_text(text) # 5 print("5) The Last Tow Characters:", tow_characters) # 5 if __name__ == "__main__": main()
true
a58af9f6b048d0aa853c45a59689da0bc8abea76
olugboyegaonimole/python
/a_simple_game.py
2,907
4.4375
4
#A SIMPLE GAME class Football(): class_name='' description='' #THIS IS THE INITIAL VALUE OF THE PROPERTY objects={} #1. WHEN A SETTER IS USED, YOU MUST ASSIGN AN INITIAL VALUE TO THE PROPERTY #2. HERE FOR EXAMPLE, THE ASSIGNMENT TAKES PLACE WHEN THE PROPERTY IS DEFINED AS A CLASS ATTRIBUTE def __init__(self, name): self.name = name Football.objects[self.class_name]=self def get_description(self): print(self.class_name + '\n' + self.description) class Striker(Football): class_name = 'striker' description='scores goals' class Defender(Football): class_name='defender' description='stops striker' class Ball(Football): def __init__(self, name): self.class_name='ball' self._description='hollow spherical inflated with air' self.status=0 super().__init__(name) @property def description(self): #THIS IS THE GETTER if self.status==0: self._description='hollow spherical inflated with air' elif self.status==1: self._description = 'you beat one defender!' elif self.status==2: self._description = 'you beat another defender!' elif self.status==3: self._description = 'now you beat the goalkeeper!' elif self.status>3: self._description = 'IT\'S IN THE BACK OF THE NET!!!!!! GOALLLLLLLLLLLLLLLLLLLL!!!!!!!!!!!!!!!' return self._description #WHEN A SETTER IS USED THE GETTER MUST RETURN THE PROPERTY ITSELF (AND NOT RETURN A LITERAL VALUE) #THE SETTER DIRECTLY ASSIGNS A VALUE TO THE PROPERTY, OR IT ASSIGNS A VALUE TO SOMETHING THAT WILL DETERMINE THE VALUE OF THE PROPERTY @description.setter def description(self, value): #THIS IS THE SETTER self.status = value #HERE, THE SETTER ASSIGNS A VALUE TO SOMETHING THAT WILL DETERMINE THE VALUE OF THE PROPERTY striker1 = Striker('yekini') defender1=Defender('uche') ball01=Ball('addidas') i=0 def get_input(): global i i += 1 command = (input('enter command: ')).split(' ') verbword = command[0] if verbword in verbdict: verb = verbdict[verbword] else: print('unknown') return if len(command)>1: nounword = command[1] verb(nounword) else: verb('nothing') def say(noun): print('you said {}'.format(noun)) def examine(noun): if noun in Football.objects: Football.objects[noun].get_description() else: print('there is no {} here'.format(noun)) def kick(noun): if noun in Football.objects: item = Football.objects[noun] if type(item) == Ball: item.status += 1 if item.status == 1: print('you kicked the ball!') if 2<= item.status <=3: print('you kicked the ball again!') elif item.status>3: print('YOU\'VE SCORED!!!!!!!!!!!') else: print('you can\'t kick that') else: print('you can\'t kick that') verbdict={'say':say, 'examine':examine, 'kick':kick} while True: #while i<10: get_input()
true
02f2947e9e98e73e640aa8a46cf21878ee94bcc8
pawnwithn0name/Python3EssentialTraining
/GUI/5.event-hangling.py
728
4.1875
4
''' After the root window loads on the system, it waits for the occurence of some event. These events can be button clicks, motion of the mouse, button release, etc. These events are handled by defining functions that are executed in case an event occurs. ''' from tkinter import * def handler1(): print('White') def handler2(): print('Orange') def handler3(): print('Red') root = Tk(className = 'Event') Button(root, text='White', bg='white',fg='black', command = handler1).pack(fill = X, padx = 15) Button(root, text='Orange', bg='orange',fg='brown', command = handler2).pack(fill = X, padx = 15, pady =15) Button(root, text='Red', bg='red',fg='black', command = handler3).pack( fill = X, padx = 15) root.mainloop()
true
95d4f71e7e6a505afc4f3156a3cb57d64077db6d
pawnwithn0name/Python3EssentialTraining
/02 Quick Start/forloop.py
338
4.4375
4
#!/usr/bin/python3 # read the lines from the file fh = open('lines.txt') for line in fh.readlines(): # Print statement 'end' argument in Python 3 allows overriding the end-of-line character which # defaults to '\n'. Each line in the file already has a carriage return so the end-of-line is not needed. print(line, end = "")
true
e28e734decc6a09e159ce7105997df8d2bb1f437
dvishwajith/shortnoteCPP
/languages/python/algorithms/graphs/bfs/bfs.py
998
4.25
4
#!/usr/bin/env python3 graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } from collections import deque print("bfs first method. Using deque as a FIFO because list pop(0) is O(N)") def BFS(graph, start): node_fifo = deque([]) #using deque because pop(0) is O(N) in lists node_fifo.append(start) while len(node_fifo) != 0: traversed_node = node_fifo.popleft() print(traversed_node, " ") for connected_node in graph[traversed_node]: node_fifo.append(connected_node) BFS(graph, 'A') print("""bfs second method. Wihtout poping first element and using a list. Advantage is this store the travarsed order in nodelist as well""") def BFS(graph, start): nodelist = [] nodelist.append(start) for traversed_node in nodelist: print(traversed_node, " ") for connected_node in graph[traversed_node]: nodelist.append(connected_node) BFS(graph, 'A')
true
7cd2eef61cd8036e0e78001a306b0737f7d9e191
EfimT/pands-problems-2020
/homework 2.py
266
4.21875
4
# Write a program that asks a user to input # a string and outputs every second letter in reverse order. sentence = (input("Enter a string : ")) sentence = sentence [::-1] print ("Heres is you're string reversed and every second letter is:", sentence[::2])
true
95af810ee907a31e305afca8e4f7413807b82213
BT-WEBDEV/Volcano-Web-Map
/script.py
1,674
4.25
4
#folium - lets us generate a map within python #pandas - lets us read the csv file containing volcano locations. import folium import pandas #dataframe variable will let us read the txt file. df=pandas.read_csv("Volcanoes.txt") #map variable - this creates our map object. map=folium.Map(location=[df['LAT'].mean(),df['LON'].mean()],zoom_start=4,tiles='Stamen Terrain') #function color(elev) - determines color of map marker based on elevation def color(elev): #variable minimum to pull in the lowest elevation level minimum=int(min(df['ELEV'])) #variable step is max elevation value minus the minmum elevation value #then divided by 3 - for the 3 different elevation levels step=int((max(df['ELEV'])-min(df['ELEV']))/3) if elev in range(minimum,minimum+step): col='green' elif elev in range(minimum+step,minimum+step*2): col='orange' else: col='red' return col #fg variable is the feature group - this will let us enable volcano locations on the layer control panel. fg=folium.FeatureGroup(name="Volcano Locations") #for loop to generate through the latitude, longitude, and name of each volcano. for lat,lon,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']): #this creates our markers on the map for each volcano location. folium.Marker([lat,lon],popup=name,icon=folium.Icon(color=color(elev))).add_to(fg) #this adds the feature group to the map map.add_child(fg) #this adds the layer control panel to the map. map.add_child(folium.LayerControl()) #this generates the map into an html file. map.save(outfile='test.html')
true
74bde0e83f315810c5a80032527d31780d6e7200
DavidLohrentz/LearnPy3HardWay
/ex3.py
946
4.5
4
# print the following text print("I will now count my chickens:") # print Hens and add 25 + (30/6) print("Hens", 25 + 30.0/6) # print Roosters calc the following print("Roosters", 100 - 25.0 * 3 % 4) # print this text print("Now I will count the eggs:") # print the following calc total print(3.0 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) # print "Is it true that 3 + 2 < 5 - 7?" print("Is it true that 3 + 2 < 5 - 7?") # print True or False following calc print(3.0 + 2 < 5 - 7) # print string and total of two numbers print("What is 3 + 2?", 3.0 + 2) #print string, total of two numbers print("What is 5 - 7?", 5.0 - 7) # print string print("Oh, that's why it's False.") # print string print("How about some more.") # print string, True or False print("Is it greater?", 5 > -2) # print string, True or False print("Is it greater or equal?", 5 >= -2) # print string, True or False print("Is it less or equal?", 5 <= -2)
true
e9578f654f6e9e0c8f2d9a450bb7010814a36230
DavidLohrentz/LearnPy3HardWay
/ex15.py
740
4.375
4
# get the argv module ready # from sys import argv # tell argv what to do with the command line input #script, filename = argv # define txt; mode r is read only # save filename text to txt variable # txt = open(filename, mode = 'r') # put in a blank line at the top print("\n") # print a string with filename variable # print(f"Here's your file {filename}.") # display the text in the filename file # print(txt.read()) # close(txt) # now do the same thing from input here print("Type the filename again:") # ask for input and assign the filename to file_again variable file_again = input("\n> ") # open this second filename file txt_again = open(file_again) # display the text in this file print(txt_again.read())
true
288b48493795a69feb81d2da83d2239c977344c4
jiyifan2009/calculator
/main.py
891
4.25
4
#Calculator def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 operations = { "+": add, "-": subtract, "*": multiply, "/": divide } def calculator(): num1 = int(input("What's the first number?: ")) for symbol in operations: print(symbol) should_continue=True #Here we select "+" while should_continue: operation_symbol = input("Pick an operation: ") num2 = int(input("What's the next number?: ")) calculation_function = operations[operation_symbol] answer= calculation_function(num1, num2) print(f"{num1} {operation_symbol} {num2} = {answer}") decide=input(f"Type 'y'to continue calculating with {answer},or type 'n'to exit.") if decide=="y": num1 = answer else: should_continue=False calculator() calculator()
true
13ac170d8fa2a582b5bd2c045142f4f7973e6509
yuenliou/leetcode
/lcof/06-cong-wei-dao-tou-da-yin-lian-biao-lcof.py
1,923
4.1875
4
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- from typing import List from datatype.list_node import ListNode, MyListNode def reversePrint(head: ListNode) -> List[int]: return reversePrint(head.next) + [head.val] if head else [] def reversePrint3(head: ListNode) -> List[int]: list = [] def reverse(head: ListNode): if not head: return reverse(head.next) list.append(head.val) reverse(head) return list def reversePrint2(head: ListNode) -> List[int]: stack = [] while head: stack.append(head.val) head = head.next # list = [] # while len(stack): # list.append(stack.pop()) return stack[::-1] def reversePrint1(head: ListNode) -> List[int]: def reverse(head: ListNode) -> ListNode: pre = None cur = head while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre list = [] head = reverse(head) while head: list.append(head.val) head = head.next return list def main(): """ 思路1.翻转链表 思路2.栈 思路3.递归 """ my_list_node = MyListNode() my_list_node.addAtTail(1) my_list_node.addAtTail(2) my_list_node.addAtTail(3) my_list_node.addAtTail(4) my_list_node.addAtTail(5) ret = reversePrint(my_list_node.head) print(ret) '''剑指 Offer 06. 从尾到头打印链表 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。   示例 1: 输入:head = [1,3,2] 输出:[2,3,1]   限制: 0 <= 链表长度 <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' if __name__ == '__main__': main()
true
e6eae9ba50431852dd588b56dc975cabe2be8a98
73nko/daily-interview
/Python/matrix-spiral-print.py
2,042
4.1875
4
### # 13-12-2020 # Hi, here's your problem today. This problem was recently asked by Amazon: # You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix. # Example: # grid = [[1, 2, 3, 4, 5], # [6, 7, 8, 9, 10], # [11, 12, 13, 14, 15], # [16, 17, 18, 19, 20]] # The clockwise spiral traversal of this array is: # 1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12 ### UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 def next_direction(direction): return { RIGHT: DOWN, DOWN: LEFT, LEFT: UP, UP: RIGHT }[direction] def next_position(position, direction): if direction == RIGHT: return (position[0], position[1] + 1) elif direction == DOWN: return (position[0] + 1, position[1]) elif direction == LEFT: return (position[0], position[1] - 1) elif direction == UP: return (position[0] - 1, position[1]) def should_change_direction(M, r, c): in_bounds_r = 0 <= r < len(M) in_bounds_c = 0 <= c < len(M[0]) return (not in_bounds_r or not in_bounds_c or M[r][c] is None) def matrix_spiral_print(M): remaining = len(M) * len(M[0]) current_direction = RIGHT current_position = (0, 0) while remaining > 0: r, c = current_position print(M[r][c]) M[r][c] = None remaining -= 1 possible_next_position = next_position( current_position, current_direction) if should_change_direction(M, possible_next_position[0], possible_next_position[1]): current_direction = next_direction(current_direction) current_position = next_position( current_position, current_direction) else: current_position = possible_next_position grid = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] matrix_spiral_print(grid) # 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
true
b628c6fcf630b12388ea72c75bec610993c7fa25
73nko/daily-interview
/Python/cal-angle.py
1,087
4.34375
4
### # 16-01-2021 # Hi, here's your problem today. This problem was recently asked by Microsoft: # # Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock. ### ### # SOLUTION # This is primarily breaking down the problem into a formula. # It is more tricky than algorithmically difficult, but you might encounter questions like this as warmups. # # The key is to understand that the hour-hand makes a full rotation in 12 hours, # or 12 * 60 minutes. The minute hand makes a full rotation in 60 minutes. # # So, that gives us a factor of 360 degree / (12 * 60) for the hour hand, # and 360 degree / 60 for the minute hand. Then we can use this to compute the angle: ### def calc_angle(h, m): if h < 0 or m < 0 or h > 12 or m > 60: print('Wrong input') if h == 12: h = 0 if m == 60: m = 0 hour_angle = (360 / (12.0 * 60)) * (h * 60 + m) minute_angle = (360 / 60.0) * m angle = abs(hour_angle - minute_angle) angle = min(360 - angle, angle) return angle print(calc_angle(3, 30))
true
e0c4b786df476a43bb9210912fdc1df62cfe6601
73nko/daily-interview
/Python/falling-dominoes.py
1,465
4.125
4
### # 05-12-2020 # Hi, here's your problem today. This problem was recently asked by Twitter: # Given a string with the initial condition of dominoes, where: # . represents that the domino is standing still # L represents that the domino is falling to the left side # R represents that the domino is falling to the right side # Figure out the final position of the dominoes. If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright. ### class Solution(object): def pushDominoes(self, dominoes): N = len(dominoes) force = [0] * N # Populate forces going from left to right f = 0 for i in range(N): if dominoes[i] == 'R': f = N elif dominoes[i] == 'L': f = 0 else: f = max(f-1, 0) force[i] += f # Populate forces going from right to left f = 0 for i in range(N-1, -1, -1): if dominoes[i] == 'L': f = N elif dominoes[i] == 'R': f = 0 else: f = max(f-1, 0) force[i] -= f result = '' for f in force: if f == 0: result += '.' elif f > 0: result += 'R' else: result += 'L' return result print(Solution().pushDominoes('..R...L..R.')) # ..RR.LL..RR
true
b870fbb7bf5c9ecdefd05971e372aa1242a17113
ismailft/Data-Structures-Algorithms
/LinkedLists/LinkedList.py
746
4.21875
4
#Implementation of a linked list: class Node(object): def __init__(self, data): self.Data = data self.next = None self.prev = None class LinkedList(object): def __init__(self): self.head = None print("Linked List Created!") def addNode(self, data): node = Node(data) if self.head == None: self.head = node else: node.next = self.head node.next.prev = node self.head = node def printList(self): currentHead = self.head while currentHead != None: print(currentHead.Data) currentHead = currentHead.next l = LinkedList() l.addNode(1) l.addNode(2) l.addNode(10) l.printList()
true
87a1288436eeb85f7d485ee347c254da06855fd6
loveplay1983/daily_python
/python_module_with_example/Text/str_cap.py
543
4.1875
4
# Manually accomplish the same functionality of string.capwords() # separate text first then use a temp list add each part of the text in which each text has already been convert to captalized by for loop, then use join() to combine all together # import string text = 'hello world' def captalize(text): text_sep = text.split() text_cap = [] str_cap = ' ' for item in text_sep: each = item[0].upper() + item[1:] text_cap.append(each) return str_cap.join(text_cap) result = captalize(text) print(result)
true
01882010d5ec0d5fab6e89804a09fe05c3fb1a58
WitheredGryphon/witheredgryphon.github.io
/python/HackerRank/Regex/detect_the_email_addresses.py
936
4.15625
4
''' You will be provided with a block of text, spanning not more than hundred lines. Your task is to find the unique e-mail addresses present in the text. You could use Regular Expressions to simplify your task. And remember that the "@" sign can be used for a variety of purposes! Input Format The first line contains an integer N (N<=100), which is the number of lines present in the text fragment which follows. From the second line, begins the text fragment (of N lines) in which you need to search for e-mail addresses. Output Format All the unique e-mail addresses detected by you, in one line, in lexicographical order, with a semi-colon as the delimiter. ''' import re matches = [] for i in range(int(input())): match = re.findall("\\b(?:\w|\.){1,}@(?:\w*\.*){1,}\\b", input()) matches.extend(match) matches = (list(filter(None,matches))) matches = ';'.join(sorted(set(filter(None, matches)))) print (matches)
true
11bbb77f4b587d8863076daafee3138f29241f13
WitheredGryphon/witheredgryphon.github.io
/python/Code Wars/count_the_smiley_faces.py
1,457
4.125
4
''' Description: Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Rules for a smiling face: -Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ; -A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~ -Every smiling face must have a smiling mouth that should be marked with either ) or D. No additional characters are allowed except for those mentioned. Valid smiley face examples: :) :D ;-D :~) Invalid smiley faces: ;( :> :} :] Example cases: countSmileys([':)', ';(', ';}', ':-D']); // should return 2; countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3; countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1; Note: In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same Happy coding! ''' def count_smileys(arr): smileyCount = 0 for i in arr: if i[0] == ':' or i[0] == ';': if len(i) == 2: if i[1] == ')' or i[1] == 'D': smileyCount += 1 else: if i[1] == '-' or i[1] == '~': if i[2] == ')' or i[2] == 'D': smileyCount += 1 return smileyCount #the number of valid smiley faces in array/list
true
bb2d4ac961ebd2e517cc2e29ebcc47011e420027
ruvvet/File-Rename
/Rename.py
2,862
4.125
4
# BATCH FILE RENAMER PROGRAM # Rename all files within a folder using the folder name, a specified name, or last modified date as the prefix. import os import glob import sys import time def main(): # Input the directory with all files. # Returns all files in the folder and the # of files in the folder. filePath = str(input('Folder path: ')) print('List of files:', os.listdir(filePath)) print('with', len(os.listdir(filePath)), 'files in', filePath) choice = optionsMenu() if choice == 1: folderRename(filePath) elif choice == 2: inputRename(filePath) elif choice == 3: dateRename(filePath) else: print('Oops, try again.') optionsMenu() # Loop goAgain = str(input('Rename more files: Y or N >>> ')) while goAgain == 'Y': main() print('END') # Menu selection def optionsMenu(): # User selects 1 of 3 options. print('1. Rename files with dir name.') print('2. Rename files with user input.') print('3. Rename files with last modified date.') choice = int(input('Option 1, 2 or 3: ')) return choice # This function renames all files in the directory using the root dir name. def folderRename(absFilePath): # For each file in the directory, # Print the name of the old file # Print the name of the new file name # Rename file folderName = os.path.basename(absFilePath) for filePath in os.listdir(absFilePath): full_path = os.path.join(absFilePath, filePath) print('Old:', full_path) if os.path.isfile(full_path): new_path = os.path.join(absFilePath, folderName + "_" + filePath) print('Renamed to: ', new_path) os.rename(full_path, new_path) # This function renames all files in the directory using a user input. def inputRename(absFilePath): inputName = input('Input file rename prefix: ') for filePath in os.listdir(absFilePath): full_path = os.path.join(absFilePath, filePath) print('Old: ', full_path) if os.path.isfile(full_path): new_path = os.path.join(absFilePath, inputName + "_" + filePath) print('Renamed to:', new_path) os.rename(full_path, new_path) def dateRename(absFilePath): for filePath in os.listdir(absFilePath): full_path = os.path.join(absFilePath, filePath) dateModified = time.strftime('%m_%d_%Y', time.localtime(os.path.getmtime(full_path))) print('Old: ', full_path, ' >> Date Last Modified: ', dateModified) if os.path.isfile(full_path): new_path = os.path.join(absFilePath, dateModified + "_" + filePath) print('Renamed to:', new_path) os.rename(full_path, new_path) main()
true
f5c6213aac0f6d02789e29dd82d82b3054b7e69b
rishabhjhaveri10/Linear-Regression
/linear_regression_scipy.py
2,337
4.4375
4
#This code has its inspiration from Data Science and Machine Learning with Python course by Frank Kane on www.udemy.com. import numpy as np from matplotlib import pyplot as plt from scipy import stats #Model 1 #Generating page speeds randomly with a mean of 3, standard deviation of 0.5 and for 1000 people. page_speeds = np.random.normal(3, 0.5, 1000) #Generating amount spent by customer randomly with a mean of 70, standard deviation of 5 and for 1000 people. amount_spent = np.random.normal(70, 5, 1000) #Plotting a scatter plot of page speeds vs amount spent by customer plt.figure(1) plt.scatter(page_speeds, amount_spent) plt.title('Model 1') plt.xlabel('Time taken to load a page') plt.ylabel('Amount spent by customer') #Performing linear regression #Model: y = m*x + c : amount spent by customer = slope * page speeds + constant slope, intercept, r_value, p_value, std_err = stats.linregress(page_speeds, amount_spent) fit_line = predict(page_speeds) plt.plot(page_speeds, fit_line, c = 'r') plt.show() print 'The value of r-squared is : ' + str(r_value ** 2) good_fit(r_value) #As we can see from the value of r-squared that if we fit a line it might not be a very good fit. #Because the data is randomly generated and we do not have a linear relationship between variables. #Now we build another model in which we will explicitly give a linear relationship between variables. #Model 2 page_speeds_1 = np.random.normal(3, 0.5, 1000) #For this model we have explicitly given a linear relationship. amount_spent_1 = 100 - (page_speeds_1 + np.random.normal(0, 0.1, 1000)) * 1.5 plt.figure(2) plt.scatter(page_speeds_1, amount_spent_1) plt.title('Model 2') plt.xlabel('Time taken to load a page') plt.ylabel('Amount spent by customer') slope, intercept, r_value, p_value, std_err = stats.linregress(page_speeds_1, amount_spent_1) fit_line1 = predict(page_speeds_1) plt.plot(page_speeds_1, fit_line1, c = 'r') plt.show() print 'The value of r-squared is : ' + str(r_value ** 2) good_fit(r_value) #We define a function to fit the line. def predict(x): return slope * x + intercept #We define a function to display if it a good fit or not. def good_fit(x): y = x * x if y > 0.5: print 'It is a good fit' else: print 'It is not a good fit'
true
0778ccfd4830cb34d032acaf51f4dfd764f07cb3
marlonrenzo/A01054879_1510_assignments
/A3/character.py
1,300
4.34375
4
def get_character_name(): """ Inquire the user to provide a name. :return: a string """ name = input("What is your name?").capitalize() print(f"Nice to meet you {name}\n") return name def create_character() -> dict: """ Create a dictionary including attributes to associate to a character. :post condition: will create a character as a dictionary of attributes :return: the information of a character as a dictionary """ print("\nWelcome to the Dungeon of Kather. 'Ere are where young lads, like yourself, learn to become a warrior.\n" "It is tradition at Castor's Thrine that all younglings are placed within the walls of Kather to begin training.\n" "The Dungeon has 25 rooms for you to traverse through and eventually escape. Go forth and slash your way through \n" "young blood-seeker. There are monsters in this realm. Escape the dungeon with your life and you will be unstoppable.\n\n" "Let's begin by getting to know you.........") character = {'Name': get_character_name(), 'Alias': "You", 'HP': [10, 10], 'Inventory': [], 'position': {"x": 2, "y": 2}} return character # Test dictionary: {'Name': 'Marlon', 'Alias': 'You', 'HP': [10, 10], 'Inventory': [], 'position': {"x": 2, "y": 2}}
true
0a571afe9dc8d96a68d51d74efbd9af73adeb66c
marlonrenzo/A01054879_1510_assignments
/A4/Question_3.py
1,371
4.34375
4
import doctest def dijkstra(colours: list) -> None: """ Sort the colours into a pattern resembling dutch flag. Capitalize all letters except for strings starting with 'b' in order to sort the way we need to. :param colours: a list :precondition: colours must be a non-empty list :post condition: will return a sorted list that resembles the dutch national flag :return: a list >>> dijkstra(['blue', 'white', 'blue', 'red', 'red', 'white']) ['red', 'red', 'white', 'white', 'blue', 'blue'] >>> dijkstra(['blue', 'blue', 'blue', 'blue', 'red', 'white']) ['red', 'white', 'blue', 'blue', 'blue', 'blue'] """ for i in range(0, len(colours)): # loop through the list and capitalize if colours[i][0] != 'b': colours[i] = colours[i].title() # only capitalize strings that don't start with 'b' colours.sort() # sort the colours by ascii value, so that capital letters are first, lowercase strings following for i in range(0, len(colours)): # loop through the list of colours to lowercase the capitalized strings colours[i] = colours[i].lower() print(colours) def main(): """ Call all functions to run the program. :return: None """ doctest.testmod() dijkstra(['blue', 'white', 'blue', 'red', 'red', 'white']) if __name__ == '__main__': main()
true
cf9a22378eb8cb4bd42f5821b51ccf9123c32e4d
Saketh1196/Programming
/Python/Weather Measurement.py
367
4.21875
4
Temp=float(input("Enter the temperature in Fahrenheit: ")) Celsius=(5/9)*(Temp-32) print("The temperature in Celsius is: ",Celsius) while True: if Celsius>30: print("The Weather is too hot. Please take care") elif Celsius<10: print("The Weather is too Cold. Wear Warm Clothes") else: print("Standard Weather") break
true
5cbf031344cab3889dfa61b44b9739befd5abd29
Sumanth-Sam-ig/pythoncode
/sum of square and cube of series.py
762
4.21875
4
print ('Enter the number n') a=int(input()) print('Enter the number of the mathematical operation required') print ('') print(""" 1 - Sum of the numbers till n 2 - sum of the squares of the numbers 3 -sum of the cubes of the numbers """) print('\n') b=int(input()) if b>3: print('invalid entery') elif b==1: p=a-1 while(p>=0) : a=a+p p-=1 print('sum of n termsis',a ) elif b==2 : p=a-1 k=a**2 while(p>=0) : k=k+p**2 p-=1 print ('the sum of the square of the n numbers is ',k ) elif b==3 : p=a-1 k=a**3 while(p>=0) : k=k+p**3 p-=1 print ('the sum of the cube of the n numbers is ',k )
true
76ad14efd7fd787c72dd439f54eb6fc21fd0bb57
Anancha/Inventing-Phoenix-Getting-to-know-Raspberry-PI-Pico
/1) Blink code for Raspberry PI Pico.py
734
4.125
4
#Code created by Inventing Phoenix #1 FEB 2021 from machine import Pin # For accessing these pins using the Pin class of the machine module import time # Time module helps in creating delays led= Pin(25,Pin.OUT) # The Pin is assigned and the mode of the pin is set in this command while True: # While True is used to creating a loop that will never end led.high() # .high() will set the pin to the high logic level time.sleep(1) # time.sleep(1) will create an delay of 1 seconds. Time can be changed inside the bracket. led.low() # .low() will set the pin to the low logic level time.sleep(1) #Thank you for watch this Video Please subricbe the channel and click on the bell icon.
true
9eb18156516741b7e836d6aedfb9305a1b8a8c18
andy-j-block/COVID_Web_Scraper
/helper_files/get_todays_date.py
400
4.28125
4
from datetime import date def get_todays_date(): ################### # # This function gets today's current day and month values for later use in # the program. # ################### todays_date = str(date.today()) current_day = todays_date.split('-')[2] current_month= todays_date.split('-')[1] return current_day, current_month
true
b82235bfdb9c233787b1f791e34f293cf739c8dd
Yixuan-Lee/LeetCode
/algorithms/src/Ex_987_vertical_order_traversal_of_a_binary_tree/group_share_jiangyh_dfs.py
1,229
4.1875
4
""" DFS method Time complexity: Space complexity: O(N) """ import collections # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def verticalTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ # define a map where # the key is x coordinate # the value is a tuple of two element (y coordinate, value) group = collections.defaultdict(list) def dfs(node, x, y): # key is x coordinate # value is a tuple (y coordinate, node value) group[x].append((y, node.val)) if node.left is not None: # go to left # for sorting purpose, it changes to y+1 instead of y-1 dfs(node.left, x-1, y+1) if node.right is not None: # go to right # for sorting purpose, it changes to y+1 instead of y-1 dfs(node.right, x+1, y+1) dfs(root, 0, 0) return [[t[1] for t in sorted(group[x])] for x in sorted(group)]
true
eb0ab4d39ecbda17d7a3903c3825eeb435da3d4a
mozahid1/Easy-Calculator
/Easy_to_Calculate.py
1,155
4.1875
4
# This function adds two numbers def add(x,y): return x + y # This function subtracts two numbers def subtract(x,y): return x - y # This function multiplies two numbers def multiply(x,y): return x * y # This function divides two numbers def divide(x,y): return x / y print("Select Your Operation:-") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") while True: # Take input from the user choice = input("Enter choice(between 1 to 4): ") # Check if choice is one of the four options if choice in ('1', '2', '3', '4'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) break else: print("Try Again")
true
ba6b894681b78a1023760739eb2a1731b9aa8965
Neveon/python-algorithms
/binary_search/binary_search_intro.py
1,102
4.25
4
# Iterative Binary Search def binary_search_iterative(data, target): # array is already sorted - we split the array in half to find if the target is # in the upper half or lower half of the already sorted array low = 0 high = len(data) - 1 while low <= high: mid = (low + high) // 2 print('Indices: low is {}, mid is {}, high is {}'.format(low, mid, high)) if target == data[mid]: return True elif target < data[mid]: high = mid - 1 # low half with high point of array being below mid else: low = mid + 1 # upper half, with low point being above mid return False test_arr = [2,3,5,7,8,9,11,13,15,16,21,27,32] # print(binary_search_iterative(test_arr, 5)) # Recursive Binary Search def binary_search_recursive(data, target, low, high): # Check if low crossed high if low > high: return False else: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: return binary_search_recursive(data, target, low, mid-1) else: return binary_search_recursive(data, target, mid+1, high)
true
e9d5d74c5d6667f525866164554d59d515737a31
makennamartin97/python-algorithms
/ninjainheritence.py
1,677
4.4375
4
# As you can see, peons have limited abilities. They only have default health # point of 100 and can't attack but can only takeDamage. # Imagine that you wanted to create a new class called Warrior. You want # warrior to have everything that a Peon has. You also want the warrior to # do everything that a Peon can do. In addition, however, you want to set it # up such that # when a warrior is created, you want the default hp to be 200! # you want the warrior to have a default 'armor' of 70, which means 70% of the damage will be reduced. # you want to add a new method called attack(), which returns a random integer between 10 to 20. # you want the warrior to override the takeDamage(dmg) method. This time, its hp would only go down by 30% of dmg (as its armor would have absorbed 70% of dmg). # Finish implementing class Warrior using inheritance. import random class Peon: def __init__(self): self.hp = 100 def takeDamage(self, dmg): self.hp = self.hp - dmg def returnHP(self): return self.hp # note that we're creating a new class Warrior that EXTENDS from an existing class Peon class Warrior(Peon): def __init__(self): self.hp = 200 self.armor = 70 def attack(self): return random.randint(10,21) def takeDamage(self, dmg): self.hp = self.hp - (dmg * .30) return self.hp # testing warrior1 = Warrior() warrior2 = Warrior() print(warrior1.returnHP()) #200 print(warrior1.armor) #70 print(warrior1.attack()) print(warrior1.takeDamage(100)) #170.0 print(warrior2.takeDamage(200)) #140.0 print(warrior1.returnHP()) #170.0 print(warrior2.armor) #70
true
965fe9cd22babe11276fc0efaf1fd5389498fb0e
makennamartin97/python-algorithms
/sorts/bubblesort.py
541
4.25
4
# bubble sort # It is a comparison-based algorithm in which each pair of adjacent elements # is compared and the elements are swapped if they are not in order. def bubblesort(list): # Swap the elements to arrange in order for i in range(len(list)-1,0,-1): # start stop step for j in range(i): if list[j] > list[j+1]: temp = list[j] list[j] = list[j+1] list[j+1] = temp return list list = [19,2,31,45,6,11,121,27] bubblesort(list) print(bubblesort(list))
true
68530451a07c82d1a0c553bf6535fd0dbdf8f95f
makennamartin97/python-algorithms
/stutteringfxn.py
508
4.125
4
# Write a function that stutters a word as if someone is struggling to read it. # The first two letters are repeated twice with an ellipsis ... and space after # each, and then the word is pronounced with a question mark ?. # stutter("incredible") ➞ "in... in... incredible?" # stutter("enthusiastic") ➞ "en... en... enthusiastic?" # stutter("outstanding") ➞ "ou... ou... outstanding?" def stutter(word): new = word[0] + word[1] + '... ' return new + new + word + '?' print stutter('makenna')
true
df1eba0e96c7a622d0a7f9140d2480e83e930847
makennamartin97/python-algorithms
/sorts/mergesort.py
922
4.28125
4
# merge sort # Merge sort first divides the array into equal halves and then combines # them in a sorted manner. unsortedlist = [64, 34, 25, 12, 22, 11, 90] def mergesort(unsortedlist): if len(unsortedlist) <= 1: return unsortedlist # find middle pt and divide it mid = len(unsortedlist) //2 leftlist = unsortedlist[:mid] rightlist = unsortedlist[mid:] leftlist = mergesort(leftlist) rightlist = mergesort(rightlist) return list(merge(leftlist,rightlist)) # Merge the sorted halves def merge(left,right): res = [] while len(left) != 0 and len(right) != 0: if left[0] < right[0]: res.append(left[0]) left.remove(left[0]) else: res.append(right[0]) right.remove(right[0]) if len(left) == 0: res = res + right else: res = res + left return res print(mergesort(unsortedlist))
true
be4114feb5e61f82d58686aa757adea9a93f8296
makennamartin97/python-algorithms
/factorial.py
315
4.375
4
# Create a function that takes an integer and returns the factorial of that # integer. That is, the integer multiplied by all positive lower integers. # factorial(3) ➞ 6 # factorial(5) ➞ 120 # factorial(13) ➞ 6227020800 def factorial(num): if num < 2: return num else: return factorial(num-1) * num
true
3def48fa48e7add42ed31186c7d15327a554d68e
samuel-navarro/calendar
/date_parser.py
1,080
4.46875
4
import yearinfo def date_str_to_tuple(date_string: str): """ Calculates a date tuple (day, month, year) from a date string in the format dd.mm.yyyy :param date_string: Date string with the form dd.mm.yyyy :return: The date tuple with three integers if the parsing was successful, None otherwise """ date_fields = date_string.split('.') if len(date_fields) != 3: return None try: day, month, year = (int(field) for field in date_fields) if not _is_valid_date(day, month, year): return None return day, month, year except ValueError: return None def _is_valid_date(day, month, year): """ Determines whether a date is valid :param day: Day of the date :param month: Month of the date :param year: Year of the date :return: True if the date is valid, False otherwise """ if not 1 <= month <= 12: return False days_in_month = yearinfo.get_month_to_day_dict(year) if not 1 <= day <= days_in_month[month]: return False return True
true
09d69fb7eb61eefa361141d80f8572862de9090a
atulasati/scripts_lab_test
/user_crud/PROG1326_Lab7_VotreNom.py
2,104
4.1875
4
import getpass class User(object): """ Defined user object. create user object passing params - name, city, phone Args: name (str, mandatory): user name, to be provide during the user creation city (str, mandatory): user city, to be provide during the user creation """ def __init__(self, name, city, phone): self.name = name self.city = city self.phone = phone def display_name(self): print (self.name) def display_city(self): print (self.city) def display_phone(self): print (self.phone) def __str__(self): return "<User obj:%s>" %self.name while(True): name = input ("What is your name? ") city = input ("%s what town do you live in ? "%name) phone = input ("what is your cellphone number? ") if name.strip() == '': print("name can not be empty!") continue user = User(name, city, phone) print ("user:", user) while(True): what_to_do = """What do you want to do ? 1 – Print 2 – Modification a – The name b – Town c – Phone number m – Print the menu 3 – Print user 4 – Exit""" print (what_to_do) command = "" while (True): command = input ("Command: ") if command.strip() in ["4", "m"]: break command_list = { "1a":user.name, "1b":user.city, "1c":user.phone, "3":("Here is the information on the user \nName: %s \nTown: %s \nPhone %s") %( user.name, user.city, user.phone ) } operation = command_list.get(command.strip()) if operation: print (operation) else: if command.strip() == "2a": new_name = input ("What is your new name? : ") user.name = new_name elif command.strip() == "2b": new_city = input ("What is your new town? : ") user.city = new_city elif command.strip() == "2c": new_phone = input ("What is your new new phone number? : ") user.phone = new_phone else: print ("Incorrect command!") if command == "4": print ("Goodbye!") break input_key = input("Press Enter key to exit.") if input_key == '': break
true
3b77508b910db0d8b6781964d76f25389c9597f6
vaibhavtwr/patterns-and-quiz
/python/kmtom.py
496
4.21875
4
#Python Program to Convert Kilometers to Miles ch=int(input("enter 1 for change in kilometers to miles \n enter 2 for change in miles to kilometers")) if (ch==1): n=int(input("enter the distance in kilometers")) m=0.621371*n txt="you distance in kilometer {} and in miles {}" print(txt.format(n,m)) elif (ch==2) : n=int(input("enter the distance in miles")) km=1.60934*n txt="your distance in miles {} and in kilometers {}" print(txt.format(n,km)) else: print("you enter wrong choice")
true
1178bb0800c6b294a4462d3e08813f772341b721
dklickman/pyInitial
/Lab 8/workspace2.py
982
4.28125
4
num_date = input("Please enter a date in mm/dd/yy format: ") # Create variables to check against the month conditions # and convert to an integer so we can math on it month_check = int(num_date[0:2]) day_check = int(num_date[3:5]) year_first_value = (int(num_date[6])) year_second_value = (int(num_date[7])) year_check = year_first_value + year_second_value print(month_check, day_check, year_check) while month_check < 0 or month_check > 12: print("That is not a valid month, please re-enter the date.") num_date = input("Please enter a date in mm/dd/yy format: ") while day_check < 0 or day_check > 31: print("That is not within the range of a valid day of the month.") num_date = input("Please re-enter the date: ") while year_check != 4: print("2013 is the only valid year for entry in this program.") print() num_date = input("Please re-enter the date: ") print("Fin")
true
9cf3a51ee95373998a0f10b48714147b82a795e2
dklickman/pyInitial
/Lab 7/Notes/7.7 Returning a List from a Function.py
973
4.375
4
# This program uses a function to create a list # The function returns a reference to the list def main(): # Get a list with values stored in it numbers = get_values() # Display the values in the list print("The numbers are", numbers) # The get_values() function gets a series of numbers # from the user and stores them in a list where the # function returns a reference to the list def get_values(): # Create an empty list to fill values = [] # Create a variable to control the loop again = 'y' # Get the values from the user and add them # to the list while again == 'y' or again == 'Y': num = int(input("Enter a number: ")) values.append(num) # Prompt user to enter another value # or exit the loop again = input("Enter 'y' to enter another number.") # return the list return values # Call that sweet sweet main main()
true
e14f317d78a45ecac9a946cb0448c79a986f62e6
dklickman/pyInitial
/Lab 7/Notes/7.7 Working with Lists and Files Part D2 reading numbers to a file.py
856
4.1875
4
# While reading numbers from a file into a list; convert the number # stored as a string back into an integer so math can be performed # This program reads numbers from a file into a list def main(): # Open the file infile = open('numberlist.txt', 'r') # Read the file's content into a list numbers = infile.readlines() # Close the file infile.close() # Create a loop to convert the string values stored in the # list into integers # Create an indexerror prevention variable index = 0 while index < len(numbers): # This says the value assigned to index is equal to the # element position in the list, then we convert that to an int numbers[index] = int(numbers[index]) index += 1 print(numbers) # Call the main function main()
true
83e550b09a6b39a2ea66387520f1134f451d97ac
Adrian-Jablonski/python-exercises
/Guess_A_Number/Guess_A_Number.py
1,243
4.15625
4
import random secret_number = random.randint(1, 10) guesses_left = 5 game_over = False print("I am thinking of a number between 1 and 10") print("You have ", guesses_left, " guesses left.") while game_over == False: guess = int(input("What's the number? ")) if guess == secret_number: print("Yes! You win!") elif guess < secret_number and guess >= 1: print(guess, " is too low") guesses_left -= 1 elif guess > secret_number and guess <= 10: print(guess, " is too high") guesses_left -= 1 else: print("Invalid number. Type a number between 1 and 10") if guesses_left == 0: print("You ran out of guesses") elif guess != secret_number : print("You have ", guesses_left, " guesses left.") if guesses_left == 0 or guess == secret_number: play_again = input("Would you like to play again? (Y or N) ").lower() if play_again == "n": print("Bye!") game_over = True elif play_again == "y": print("I am thinking of a number between 1 and 10") secret_number = random.randint(1, 10) guesses_left = 5 print("You have ", guesses_left, " guesses left.")
true
e5e378fabf26fec9c650ba4d624ac2720a8bbdb8
nehayd/pizza-deliveries
/main.py
985
4.1875
4
# 🚨 Don't change the code below 👇 print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") add_pepperoni = input("Do you want pepperoni? Y or N ") add_cheese = input("Do you want extra cheese? Y or N ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 price = 15 if size == "S" else 20 if size == "M" else 25 if size == "L" else print("Please enter valid input") if size == "S" and add_pepperoni == "Y": extra_pepperoni = 2 elif (size == "M" or size == "L") and add_pepperoni == "Y": extra_pepperoni = 3 elif (size == "S" or "M" or "L") and add_pepperoni == "N": extra_pepperoni = 0 else: print("Please enter valid input") if (size == "S" or "M" or "L") and add_cheese == "Y": extra_cheese = 1 elif (size == "S" or "M" or "L") and add_cheese == "N": extra_cheese = 0 else: print("Please enter valid input") print("Your final bill is: $%s." %(price+extra_pepperoni+extra_cheese))
true
8ee2de89c9697171cbd18ff19855e37e320b3d19
VasudevJaiswal/Python-Quistions-CP
/If-Elif-Else/02 - Test/02.py
842
4.15625
4
# Write a program to accept the cost price of a bike and display the road tax to be paid according to the following criteria : # Cost price (in Rs) Tax # > 100000 15 % # > 50000 and <= 100000 10% # <= 50000 5% print("By Cost price of a bike - calculate road tax to be paid ") tax = 0 Cost_Price = int(input("Enter Cost price of Bike : ")) if(Cost_Price>100000): tax = (Cost_Price*15)/100 elif(Cost_Price>50000 and Cost_Price<=100000): tax = (Cost_Price*10)/100 elif(Cost_Price<=50000): tax = (Cost_Price*5)/100 print("tax is Payed by bike owner ", str(tax)) # For not close immediately input("Press Enter to close program")
true
45a80c99c1943ffe147270995fff4fe2eb827d4f
akhilnair111/100DaysOfCode
/Week1/String Slicing.py
542
4.125
4
""" Copeland’s Corporate Company also wants to update how they generate temporary passwords for new employees. Write a function called password_generator that takes two inputs, first_name and last_name and then concatenate the last three letters of each and returns them as a string. """ first_name = "Reiko" last_name = "Matsuki" def password_generator(first_name, last_name): new_pass = first_name[(len(first_name)-1)-2:] + last_name[(len(last_name)-1)-2:] return new_pass temp_password = password_generator(first_name, last_name)
true
3be4dc6f769698dc958ceeed3e6dc4c50deda0f2
akhilnair111/100DaysOfCode
/Week2/Delete a Key using dictionaries.py
1,131
4.15625
4
""" 1. You are designing the video game Big Rock Adventure. We have provided a dictionary of items that are in the player’s inventory which add points to their health meter. In one line, add the corresponding value of the key "stamina grains" to the health_points variable and remove the item "stamina grains" from the dictionary. If the key does not exist, add 0 to health_points. 2. In one line, add the value of "power stew" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points. 3. In one line, add the value of "mystic bread" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points. 4. Print available_items and health_points. """ available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30} health_points = 20 health_points += available_items.pop("stamina grains", 0) health_points += available_items.pop("power stew", 0) health_points += available_items.pop("mystic bread", 0) print(available_items) print(health_points)
true
6bb25eb72442be16fde69b5bba6cccfafd93010b
akhilnair111/100DaysOfCode
/Week3/part_of_speech.py
2,399
4.15625
4
""" . Import wordnet and Counter from nltk.corpus import wordnet from collections import Counter wordnet is a database that we use for contextualizing words Counter is a container that stores elements as dictionary keys 2. Get synonyms Inside of our function, we use the wordnet.synsets() function to get a set of synonyms for the word: def get_part_of_speech(word): probable_part_of_speech = wordnet.synsets(word) The returned synonyms come with their part of speech. 3. Use synonyms to determine the most likely part of speech Next, we create a Counter() object and set each value to the count of the number of synonyms that fall into each part of speech: pos_counts["n"] = len( [ item for item in probable_part_of_speech if item.pos()=="n"] ) ... This line counts the number of nouns in the synonym set. 4. Return the most common part of speech Now that we have a count for each part of speech, we can use the .most_common() counter method to find and return the most likely part of speech: most_likely_part_of_speech = pos_counts.most_common(1)[0][0] Now that we can find the most probable part of speech for a given word, we can pass this into our lemmatizer when we find the root for each word. Let’s take a look at how we would do this for a tokenized string: tokenized = ["How", "old", "is", "the", "country", "Indonesia"] lemmatized = [lemmatizer.lemmatize(token, get_part_of_speech(token)) for token in tokenized] print(lemmatized) # ['How', 'old', 'be', 'the', 'country', 'Indonesia'] # Previously: ['How', 'old', 'is', 'the', 'country', 'Indonesia'] Because we passed in the part of speech, “is” was cast to its root, “be.” This means that words like “was” and “were” will be cast to “be”. """ import nltk from nltk.corpus import wordnet from collections import Counter def get_part_of_speech(word): probable_part_of_speech = wordnet.synsets(word) pos_counts = Counter() pos_counts["n"] = len( [ item for item in probable_part_of_speech if item.pos()=="n"] ) pos_counts["v"] = len( [ item for item in probable_part_of_speech if item.pos()=="v"] ) pos_counts["a"] = len( [ item for item in probable_part_of_speech if item.pos()=="a"] ) pos_counts["r"] = len( [ item for item in probable_part_of_speech if item.pos()=="r"] ) most_likely_part_of_speech = pos_counts.most_common(1)[0][0] return most_likely_part_of_speech
true
40a07ac8623ec825f9262ff5bb2839076ca5885a
luismelendez94/holbertonschool-higher_level_programming
/0x06-python-classes/3-square.py
486
4.3125
4
#!/usr/bin/python3 """This is the class Square""" class Square: """Compute the area of the square""" def __init__(self, size=0): """Initialize variable size""" try: self.__size = size if size < 0: raise ValueError("size must be >= 0") except TypeError: raise TypeError("size must be an integer") def area(self): """Compute the area size of a square""" return self.__size ** 2
true
944a48e3b0f0714cab53057649706393df849e5e
luismelendez94/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,003
4.375
4
#!/usr/bin/python3 """This is the class Square""" class Square: """Print a square""" def __init__(self, size=0): """Initialize variable size""" self.__size = size def area(self): """Compute the area size of a square""" return self.__size ** 2 @property def size(self): """Setter: Retrieve the size""" return self.__size @size.setter def size(self, value): """Getter: Set and verify the size""" try: self.__size = value if value < 0: raise ValueError("size must be >= 0") except TypeError: raise TypeError("size must be an integer") def my_print(self): """Print the square""" if self.__size != 0: for i in range(self.__size): for i in range(self.__size): print("#", end="") if i != self.__size: print() else: print()
true
bae61c16ce9f880b3b0041b229e69deee721f74f
luismelendez94/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
445
4.3125
4
#!/usr/bin/python3 """Function that make an integer addition Verifies if it is an integer and if float, converts it to integer """ def add_integer(a, b=98): """Function that adds 2 integers""" if not isinstance(a, int) and not isinstance(a, float): raise TypeError("a must be an integer") if not isinstance(b, int) and not isinstance(b, float): raise TypeError("b must be an integer") return int(a) + int(b)
true
f71e1facae36061727ccd6673297ab8da0a09bbf
cjoelfoster/pythagorean-triple-finder
/pythagorean-triples.py
2,349
4.625
5
#! /usr/bin/env python3.6 ## Find all pythagorean triples within a specified range of values # 1) input a value, 'z' # 2) find all pythagorean triples such that x^2 + y^2 = z^2, 0<=x<=z, 0<=y<=z # 3) return the list of triples in ordered by increasing z, x, y # 4) future development: include a lower bound for 'z' such that # z1<=x<=z2, z1<=y<=z2 # setup import sys import subprocess import time def get_bounds(): """Ask user for an upper bound and returns a list containing an upper and lower bound""" lower_bound = 0 upper_bound = input("Please enter a whole number: ") domain = [lower_bound, upper_bound] return domain def find_triples(domain): """mathematical basis: pythagorean triples are tuples of whole numbers, (x, y, z) which satisfy the equation x^2 + y^2 = z^2. let z_lower-bound > zero (i.e. ignore trivial solution x = y = z = 0), then z_lower-bound <= z <= z_upper-bound is a set (i.e. list) of all pythagorean triples which satisfy z_lower-bound <= sqrt(x^2 + y^2) <= z_upper-bound. This implies that x^2 + y^2 >= (z_lower-bound)^2 AND x^2 + y^2 <= (z_upper-bound)^2. Which further implies that for x, y not equal to zero (further ignoring all trivial solutions of the form a^2 + 0^2 = z^2), we have that x, y > z_lower-bound AND x, y < z_upper-bound. Then we can incrementally look at the validity of solutions where we incrementally fix the independent variable (z) and one of the dependent variables while whe increment the other independent variable between the bounds.""" if(domain.first < domain.last): #Obviously this cannot work with x,y restricted to be within the bounds of z because even for the elementary 5,4,3 tuple if you restricted 4<z<6 our tuple would be invalid; so the domains for x and y have to be any whole number between zero and z_upper-bound exclusive. for z in range(domain.first, domain.last): for x in range(domain.first + 1, domain.last - 1): for y in range(domain.first + 1, domain.last -1) # verify import print(sys.version_info) time.sleep(0.5) # initialize screen # Begin Sandbox Initialize_sandbox(name) n = "" while(n !=':q:'): n = input(":: ") if(n==':q:'): print("Goodbye!") elif(n==' '): Initialize_sandbox(name) else: print(" " + n) #exit subprocess.call("clear")
true
ea644a40d55c45f5698fac5f0ec3148aceac4101
Gelitan/IwanskiATLS1300
/Animating with Turtles/PC02_20200131_Iwanski.py
2,797
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 31 09:41:11 2020 @author: analiseiwanski """ #======== #PC02-Animating with Turtles #Analise Iwanski #200131 # #This code creates an abstract animation of tangent circles with radii based on the fibonacci sequence, then creates a red and blue #opposite strings of semicircles to make a strand of DNA #======== from turtle import * #fetches turtle commands import numpy as np #from Dr. Z's programming mathematical equations doc window = Screen() window.setup(800, 800, 100, 100) #setting up the window window.bgcolor("black") circleWhite = Turtle() #naming and creating the first turtle circleWhite.color("white") circleWhite.shape("triangle") circleWhite.turtlesize(0.5) circleWhite.pensize(3) circleWhite.penup() circleWhite.speed(10) fibonacciNumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] #got list of fibonnaci numbers from https://www.mathsisfun.com/numbers/fibonacci-sequence.html numberOfNumbers=len(fibonacciNumbers) #gives value of the length of the list, learned from https://www.geeksforgeeks.org/find-size-of-a-ist-in-python/ circleWhite.pendown() #use for loops to create circles for the number of fibonnaci numbers for i in range(numberOfNumbers): circleWhite.circle(fibonacciNumbers[i],360) #use for loops to create circles for the number of fibonnaci numbers, but mirrored horizontally for i in range(numberOfNumbers): circleWhite.circle(-fibonacciNumbers[i],360) halfCircleRed = Turtle() #creating second turtle halfCircleRed.color("red") halfCircleRed.shape("turtle") halfCircleRed.turtlesize(0.5) halfCircleRed.pensize(3) halfCircleRed.penup() halfCircleRed.speed(8) halfCircleRed.goto(-300,0) halfCircleRed.pendown() halfCircleRed.left(90) evens = [0,2,4,6,8,10,12,14] odds = [1,3,5,7,9,11,13,15] #drawing the animation to create the red semicircles for h in range(15): #chose 15 as the number of semicircles, created semicircles that face opposite by creating different rule for evens and odds if h in evens: halfCircleRed.right(180) halfCircleRed.circle(20,180) if h in odds: halfCircleRed.left(180) halfCircleRed.circle(20,-180) halfCircleBlue = Turtle() #creating third turtle halfCircleBlue.color("blue") halfCircleBlue.shape("turtle") halfCircleBlue.turtlesize(0.5) halfCircleBlue.pensize(3) halfCircleBlue.penup() halfCircleBlue.speed(8) halfCircleBlue.goto(300,0) halfCircleBlue.pendown() halfCircleBlue.right(90) evens = [0,2,4,6,8,10,12,14] odds = [1,3,5,7,9,11,13,15] #drawing the animation to create the blue semicircles for k in range(15): if k in evens: halfCircleBlue.right(180) halfCircleBlue.circle(20,180) if k in odds: halfCircleBlue.left(180) halfCircleBlue.circle(20,-180)
true
9f68fc23bba9abef83216264a9233d696495f81f
coflin/Intrusion-Detection-System
/shaktimaan/bashmenu/HiddenPython
893
4.4375
4
#!/usr/bin/python import os #Code for searching the hidden files in the given directory path=raw_input("Enter the path : ") print("---------------------------------------------") def hiddenFile(path): for root,dirs,files in os.walk(path,topdown=False): #looping through the directory '.' means current working directory for dirname in dirs: if(dirname[0]=="."): #if the directory name starts with . print (os.path.abspath(os.path.join(root))) print(dirname) #print the directory name print("------------------------------------------") for filename in files: #looping through the files in the directory if(filename[0]=="."): #if the file starts with '.' print (os.path.abspath(os.path.join(root))) print(filename) #print file name print("------------------------------------------") if(os.path.exists(path)): hiddenFile(path) else: print "Wrong path"
true
1ef857b41c9d6449388b6026d28487716534fdd6
quezada-raul-9060/CS161_Final_Project
/CS161_project/Brick_class.py
1,048
4.15625
4
class theBrick(object): """ Created a class for the brick. The class is for a brick/rectangle created. Will make a hitbox for the brick. """ def __init__(self, x, y, width, height): """ Sets variables for the brick. This code gives the specifics of the brick. Like his dimensions location. Parameters ---------- arg1 : int Takes integer to represent coordinate x. arg2 : int Takes integer to represent coordinate y. arg3 : int Takes integer to represent the width of the brick. arg4 : int Takes integer to represent the height of the brick. """ self.x = x self.y = y self.width = width self.height = width self.hitbox = (self.x + 150, self.y + 300, 60, 20) def draw(self, window): self.hitbox = (self.x + 150, self.y + 300, 60, 20) pygame.draw.rect(window, (0, 255, 0), self.hitbox, 2)
true
e68f3a6816d2008674f8fe1f67f1fab62c97a619
HoaiHoai/btvn-vuthithuhoai
/Assignment1/2.py
320
4.15625
4
import math #library needed to use method acos pi = math.acos(-1) #get pi value 3.1459265359 (arc cosine of -1 = pi) radius = float(input("Radius? ")) #read input 'radius' from user area = radius ** 2 * pi #calculate area r^2*pi print("Area = %.2f" % area) #print out with 2 numbers after decimal point
true