blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8dc4ebaf99230ef7580ab39d1860e21dbe745b7b
andrewsanc/pythonOOP
/exerciseCatsEverywhere.py
691
4.34375
4
# Python Jupyter - Exercise: Cats Everywhere #%% #Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats #%% cat1 = Cat('Grumpy Cat', 2) cat2 = Cat('Keyboard Cat', 1) cat3 = Cat('Garfield', 5) # 2 Create a function that finds the oldest cat #%% def findOldest(): cats = [cat1, cat2, cat3] maxAge = 0 for cat in cats: if cat.age > maxAge: maxAge = cat.age return maxAge findOldest() # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 #%% print(f'The oldest cat is {findOldest()}') #%%
true
4b9764b1034df16e9a0fb1315298b8103d92184d
SiTh08/python-basics
/Exercises/Exercise1.py
1,213
4.5625
5
# Define the following variables # first_name, last_name, age, eye_colour, hair_colour first_name = 'Francis' last_name = 'Thevipagan' age = 25 eye_colour = 'Brown' hair_colour = 'Black' # Prompt user for input and Re-assign these first_name = input('What is your first name?').capitalize().strip() print(first_name) last_name = input('What is your last name?').capitalize().strip() print(last_name) age = input('What is your age?').strip() print(age) eye_colour = input('What is your eye colour?').lower().strip() print(eye_colour) hair_colour = input('What is your hair colour?').lower().strip() print(hair_colour) # Print them back to the user as a conversation - interpolation or concatenation. Interpolation used here. print(f'Hello {first_name} {last_name}, you are {age} years old, you have {eye_colour} eyes and {hair_colour} hair.') # Section 2 - Calculate in what year was the person born? Date_of_birth = (2019 - int(age)) Date_of_birth = 2019 - age print(Date_of_birth) print(f'You said you were {age}, hence you were born in {Date_of_birth}') print(f'You said you were {age}, hence you were born in {2019 - int(age)}') print(f'You said you were {age}, hence you were born in {2019 - age}')
true
278d3be29a6dc8c5af985c0fcdbe24d39a4f84f7
sharmayuvraj/cracking-the-coding-interview
/linked-lists/loop-detection.py
704
4.125
4
""" Given a circular linked list, implement an algorithm that return the node at the begining of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. Example: Input: A -> B -> C -> D -> E -> C [the same C as earlier] Output: C """ def detectCycle(head): slow = fast = head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next if slow == fast: break if fast == None or fast.next == None: return None slow = head while slow != fast: slow = slow.next fast = fast.next return fast
true
d4000957ed00bf01fdda0e8db562c2f2cd0c68f8
sharmayuvraj/cracking-the-coding-interview
/Recusrion-and-Dynamic-Programming/nth-fibonacci-number.py
809
4.21875
4
""" Compute the nth Fibonacci Number. """ # Recusive Approach # Time Complexity -> O(2^n) def fib_recursive(n): if n <= 1: return n return fib_recursive(n-1) + fib_recursive(n-2) # Top Down Approach (or Memoization) # Time Complexity -> O(n) # Space Complexity -> O(n) def fib(n): memo = [0] * (n+1) def fib_recursive(n, memo): if n <= 1: return n if memo[n] == 0: memo[n] = fib_recursive(n-1, memo) + fib_recursive(n-2, memo) return memo[n] return fib_recursive(n, memo) # Bottom Up Approach # Time Complexity -> O(n) # Space Complexity -> O(1) def fib_bottom_up(n): if n <= 1: return n a, b = 0, 1 for _ in range(2, n+1): a, b = b, a + b return b
false
afa178c6451ff803e343f8e3a238a69e0cd0369e
congnbui/Group3_Project
/Homeworkss5/Hwss4.study.4.9.8.py
246
4.28125
4
def area_of_circle(r): """area of a circle with radius r""" import math a = math.pi * (r**2) return a ##import math while True: r = int(input("Enter the radius: ")) print("The area of the circle is: ",area_of_circle(r))
true
9bc65899c5ee88b5972df5d1215b4ae85ef57db8
yogeshdewangan/Python-Excersise
/listPrograms/permutation.py
1,074
4.1875
4
""" Write a Python program to generate all permutations of a list in Python """ """ In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. These differ from combinations, which are selections of some members of a set where order is disregarded """ lst =[1,2,3,4] import itertools print len(list(itertools.permutations(lst))) print list(itertools.permutations(lst)) # Another way ini_str = "abc" # Printing initial string print("Initial string", ini_str) # Finding all permuatation result = [] def permute(data, i, length): if i == length: result.append(''.join(data)) else: for j in range(i, length): # swap data[i], data[j] = data[j], data[i] permute(data, i + 1, length) data[i], data[j] = data[j], data[i] permute(list(ini_str), 0, len(ini_str)) # Printing result print("Resultant permutations", str(result))
true
983427e4b9dbfc51060f5bfddba622c4bc9f2d9d
yogeshdewangan/Python-Excersise
/shallow_and_deep_copy/assignment_copy.py
524
4.25
4
import copy #Copy via assignment #only reference will be copied to new instance. Any modification in new one will reflect on other one #Memory location is same for both the instances print("Assignment copy ----------") l1 = [1,2,3,4] print("L1: " + str(l1)) print("Memory Location L1: "+ str(id(l1)) ) l2= l1 # will have same memory location print("L2: " + str(l2)) print("Memory Location L3: "+ str(id(l2)) ) print("adding a new value in L2") l2.append(5) print("L1: " + str(l1)) print("L2: " + str(l2))
true
0aa67f9ed7ac4bd1640768dee7cb3613beeefcfd
LofiWiz/CS-1400
/exercise3/exercise3.1.py
915
4.1875
4
# Seth Mitchell (10600367) # CS 1400 # exercise 3.1 import math # Translations: #1 print(float((3+4) * 5)) print() #2 n = float(input("define the numeric value of n; n = ")) print((n * (n-1)) / 2) print() #3 r = float(input("define the value of r (radius); r = ")) print((4 * math.pi * r ** 2)) print() #4 r = float(input("define the value of r (radius); r = ")) a = float(input("define the numeric value of a; a = ")) b = float(input("define the numeric value of a; a = ")) print(math.sqrt((r * (math.cos(a) ** 2) + (math.cos(b)) ** 2))) print() #5 print("for the following, not that x2 - x1 can NOT == 0") y_1 = float(input("define the numeric value of y1; y1 = ")) y_2 = float(input("define the numeric value of y2; y2 = ")) x_1 = float(input("define the numeric value of x1; x1 = ")) x_2 = float(input("define the numeric value of x2; x2 = ")) print((y_2 - y_1) / (x_2 - x_1))
false
d583a40e72833a31104cb1724fdcba8edb4b1c41
jdaeira/Python-Collections
/slices.py
930
4.1875
4
my_string = "Hello there" new_string = my_string[1:5] print(new_string) my_list = list(range(1,6)) print("My list is: {} ".format(my_list)) # This will get the last item of the list new_list = my_list[2:len(my_list)] print(new_list) beginning = my_list[:3] print(beginning) end = my_list[0:] print(end) all_list = my_list[:] print(all_list) print(my_list) num_list = [5, 3, 2, 1, 7] num_list.sort() print(num_list) range_list = list(range(20)) print(range_list) # From the beginning to the end of the list and add 2 steps # [start:stop:step] even_list = range_list[::2] print(even_list) # To leave off the zero and one nozero_list = range_list[2::2] print(nozero_list) state_string = "Oklahoma" second = state_string[::2] print(second) reverse = state_string[::-1] print(reverse) first_four = range_list[0:4] print(first_four) last_four = range_list[-4:] print(last_four) toget = first_four + last_four print(toget)
true
5d3b35a39d67e1158ea9440ba19230274cb6c3d7
jpmolden/python3-deep-dive-udemy
/section5_FunctionParameters/_66_extended_unpacking.py
1,801
4.34375
4
print('*** Using python >=3.5 ***') l = [1, 2, 3, 4, 5, 6] # Unpacking using slicing, : a, b = l[0], l[1:] print('\n**** Using the * Operator ***') print('\ta, *b = l') a, *b = l print("\ta={}\n\tb={}".format(a,b)) print('\tThis works with any iterable including non-sequence types (set, dict)') c, *d = (1,2,3,4,5) print('\tWe always unpack with * into a list') print("\tc={}\n\td={}".format(c,d)) print('\n*** Will pick up the rest if an iterable ***') a, b, *c, d = [1,2,3,4,5,6,7,8,9,10] print("\ta={}\n\tb={}\n\tc={}\n\td={} (Last)".format(a,b,c,d)) a, b, *c, d = "WXYYYZ" print("\n\ta={}\n\tb={}\n\tc={}\n\td={} (Last)".format(a,b,c,d)) print('\n*** Can use on the RHS ***') l1 = [1,2,3] l2 = [4,5,6] l = [*l1, *l2] print('\tCombined list') print("\t{}".format(l)) print('\n*** * Works on any iterable ***') print('\tUnpacking into a set\list') d1 = {'a': 1, 'B': 2, 'C': 34, 'd': 3 } d3 = {'F': 1, 'S': 2, 'a': 34, 'd': 3 } d2 = {'b': 1, 'L': 2, 'z': 34, 'a': 3 } s = {*d1, *d2, *d3} print("\t", s) l = [*d1, *d2, *d3] print("\t", l) print('\n*** ** Operator (Dictionary key value merge ***') print('\td3 Takes precidence!!!!') print('\tMerging dictionaries') d4 = {**d1, **d2, **d3} print("\t", d4) print('\n*** Nested Unpacking ***') l = [1, 2, [3,4]] a, b, (c, d) = l print("\ta={}\n\tb={}\n\tc={}\n\td={} (Last)".format(a,b,c,d)) print('\n\tNested unpacking with *') a, *b, (c, *d) = [1,2,3,'python'] print("\ta={}\n\tb={}\n\tc={}\n\td={} (Last)".format(a,b,c,d)) print('\n*** Set union unpacking') s1 = {1,2,3} s2 = {1,2,4} s3 = {1,2,5} s4 = {1,2,6} # Unpacking into set set5 = {*s1, *s2, *s3, *s4} print("\t", set5) # Unpacking into list list5 = {*s1, *s2, *s3, *s4} print("\t", list5)
true
2e2eacf22e11cb41a803a44c0e76827670338018
susantamoh84/Python-Learnings
/python-matplotlib.py
2,073
4.25
4
# Print the last item from year and pop print(year[-1]);print(pop[-1]) # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Make a line plot: year on the x-axis, pop on the y-axis plt.plot(year,pop) # Display the plot with plt.show() plt.show() # Change the line plot below to a scatter plot plt.scatter(gdp_cap, life_exp) # Put the x-axis on a logarithmic scale plt.xscale('log') # Show plot plt.show() # Create histogram of life_exp data plt.hist(life_exp) # Display histogram plt.show() # Build histogram with 5 bins plt.hist(life_exp, bins=5) # Show and clean up plot plt.show() plt.clf() # Build histogram with 20 bins plt.hist(life_exp, bins=20) # Show and clean up again plt.show() plt.clf() # Basic scatter plot, log scale plt.scatter(gdp_cap, life_exp) plt.xscale('log') # Strings xlab = 'GDP per Capita [in USD]' ylab = 'Life Expectancy [in years]' title = 'World Development in 2007' # Add axis labels plt.xlabel(xlab) plt.ylabel(ylab) # Add title plt.title(title) # After customizing, display the plot plt.show() # Scatter plot plt.scatter(gdp_cap, life_exp) # Previous customizations plt.xscale('log') plt.xlabel('GDP per Capita [in USD]') plt.ylabel('Life Expectancy [in years]') plt.title('World Development in 2007') # Definition of tick_val and tick_lab tick_val = [1000,10000,100000] tick_lab = ['1k','10k','100k'] # Adapt the ticks on the x-axis plt.xticks(tick_val, tick_lab) # After customizing, display the plot plt.show() plt.scatter(gdp_cap, life_exp, s = np_pop) plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c=col, alpha=0.8) # Scatter plot plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c = col, alpha = 0.8) # Previous customizations plt.xscale('log') plt.xlabel('GDP per Capita [in USD]') plt.ylabel('Life Expectancy [in years]') plt.title('World Development in 2007') plt.xticks([1000,10000,100000], ['1k','10k','100k']) # Additional customizations plt.text(1550, 71, 'India') plt.text(5700, 80, 'China') # Add grid() call plt.grid(True) # Show the plot plt.show()
true
2ef6f5b9fe8c229905b5e63bc49f46de76dcb16b
ashu20031994/HackerRank-Python
/Day-2-Python-DataStructure/4.Find_percentage.py
1,061
4.21875
4
""" The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal. Example The query_name is 'beta'. beta's average score is . Input Format The first line contains the integer , the number of students' records. The next lines contain the names and marks obtained by a student, each value separated by a space. The final line contains query_name, the name of a student to query. """ def find_percentage(query_name, student_marks): divide = len(student_marks[query_name]) total_sum = 0 for item in student_marks[query_name]: total_sum += item print("{:.2f}".format(total_sum / divide)) if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() find_percentage(query_name, student_marks)
true
9b57bb348adca0ef1d41facb467f6042a908f189
Ahmad-br-97/DataMining-Exercise-1
/Exercise_01-04.py
491
4.25
4
text = input("Please enter a comma separated string of words: ") split_text = text.split(',') output_set = set() output_list = [] for word in split_text : output_set.add(word) #Add words to a Set for remove duplicate words for word in output_set : output_list.append(word) #convert Set To List output_list.sort() #Sort List print("\nSort Unique Words Alphabetically:") for word in output_list : print(word) print("\n***Created By Ahmad Baratian (@ahmad_br_97)***")
true
1ad59660fa739a147a3284fe5cadcd4d9cb4915d
Nutenoghforme/Manatal
/Ex2.py
720
4.15625
4
#Exercise 2: Randomness Test #In a lottery game, there is a container which contains 50 balls numbered from 1 to 50. The lottery game consists in picking 10 balls out of the container, and ordering them in ascending order. Write a Python function which generates the output of a lottery game (it should return a list). Also describe which unit tests you could implement to test the output of your function. import random START = 1 END = 50 LIMIT = 11 #stop+1 = 10+1 = 11 def random_lottery_number(): number = [random.randint(START, END) for _ in range(1, LIMIT)] number.sort() return number if __name__ == '__main__': print("The List of the Lottery Number are : " , random_lottery_number())
true
e07cc6e8955978e79e261b05626758ecc334b987
j-a-c-k-goes/compound_interest
/comp_interest.py
2,818
4.15625
4
''' most investments use a compound interest formula, which is more accurate than computing simple interest. ''' def starting_amount(): starting_amount = float(input('enter investment starting amount: ')) return starting_amount def investment_time(): investment_time = float(input('enter time to invest (in years): ')) return investment_time def interest_rate(): interest_rate = float(input('enter the interest rate (example: 3.75): ')) interest_rate = interest_rate / 100 return interest_rate def monthly_contribution(): monthly_contribution = float(input('enter monthly contribution to investment: ')) return monthly_contribution def print_comp_table(): comp_table = ''' periods for compunding interest 365\tdaily 180\tevery two days 52\tweekly 12\tmonthly 6\tevery two months 4\tquarterly 2\tsemi annually 1\tyearly ''' print(comp_table) def comp_periods(): comp_periods = [365,180,52,12,6,4,2,1] return comp_periods def calc_compound_interest(starting_amount, investment_time, interest_rate, monthly_contribution, period): interest_rate = interest_rate / 100 compounded_interest = starting_amount * (1 + (interest_rate/period)) ** (period*investment_time) # with monthly contribution PMT × (((1 + r/n)^(nt) - 1) / (r/n)) compounded_interest = compounded_interest + monthly_contribution * (((1 + interest_rate/period)**(period*investment_time) - 1) / (interest_rate/period)) compounded_interest = round(compounded_interest, 2) return compounded_interest def print_compound_interest(starting_amount, investment_time, interest_rate, monthly_contribution, comp_periods): for period in comp_periods: if period == 365: p_engl = 'daily' elif period == 180: p_engl = 'twice a day' elif period == 52: p_engl = 'weekly' elif period == 12: p_engl = 'monthly' elif period== 6: p_engl = 'bimonthly' elif period == 4: p_engl = 'quarterly' elif period == 2: p_engl = 'semi annually' elif period == 1: p_engl = 'yearly' print() print(f'principal amount\t${starting_amount}') print(f'investment time\t\t{investment_time} years') print(f'monthly contribution\t${monthly_contribution}') print(f'interest rate\t\t{interest_rate * 100}%') print(f'compound rate\t\t{p_engl}') print(f'compounded interest\t${calc_compound_interest(starting_amount, investment_time, interest_rate, monthly_contribution, period)}') print(f'total contribution\t${monthly_contribution * 12 * investment_time}') print() if __name__ == '__main__': starting_amount = starting_amount() investment_time = investment_time() interest_rate = interest_rate() monthly_contribution = monthly_contribution() comp_periods = comp_periods() print_comp_table() print_compound_interest(starting_amount, investment_time, interest_rate, monthly_contribution, comp_periods)
false
b176cf4b2b6e44779848af26ccc65076d172158e
AndresRodriguezToca/PythonMini
/main.py
1,755
4.25
4
# Andres Rodriguez Toca # COP1047C-2197-15601 # 10/3/2019 #Declare variables numberOrganisms= 0 dailyPopulation = 0.0 averageIncrease = 0.0 numberDays = 0 counter = 2 #Get the number of organism print("Starting number of organisms:", end=' ') numberOrganisms = int(input()) # If necessary loop through the input until the user provive a valid entry while numberOrganisms < 2: print("The starting number of organisms must be at least 2.") print("Starting number of organisms:", end=' ') numberOrganisms = int(input()) #Get the average daily population increase print("Average daily increase:", end=' ') averageIncrease = float(input()) # If necessary loop through the input until the user provive a valid entry while averageIncrease <= 0: print("Average daily increase:", end=' ') averageIncrease = float(input()) #Get the number of days to multiply print("Number of days to multiply:", end=' ') numberDays = int(input()) # If necessary loop through the input until the user provive a valid entry while numberDays < 1: print("Number of days must be at least 1:", end=' ') numberDays = float(input()) #Header print("Day Approximate", "\t", "Population") print("-----------------------------------") #Print first day print(1, "\t", "\t", numberOrganisms) #Calculate daily increase and print result while counter <= numberDays: #Do this if average it's greater than one if averageIncrease > 1: dailyPopulation = (numberOrganisms * averageIncrease)/100 + numberOrganisms numberOrganisms = dailyPopulation #Else this if average it's less than one else: dailyPopulation = (numberOrganisms * averageIncrease) + numberOrganisms numberOrganisms = dailyPopulation print(counter, "\t", "\t", dailyPopulation) counter = counter + 1
true
bf86ec9fc09cb4caa7d9383de96b15e357d7994f
samiulla7/learn_python
/datatypes/dict.py
1,204
4.3125
4
my_dict = {'name':'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict) ####################################################################################################### # create a dictionary squares = {1:1, 2:4, 3:9, 4:16, 5:25} # remove a particular item # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # remove an arbitrary item # Output: (1, 1) print(squares.popitem()) # Output: {2: 4, 3: 9, 5: 25} print(squares) # delete a particular item del squares[5] # Output: {2: 4, 3: 9} print(squares) # remove all items squares.clear() # Output: {} print(squares) # delete the dictionary itself del squares # Throws Error # print(squares) ###################################################################################################### marks = {}.fromkeys(['Math','English','Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] list(sorted(marks.keys()))
true
1d75087f26ee00058c26ae5795c2f81af239161f
eltondornelas/hackerrank-python
/text_alignment.py
1,927
4.40625
4
""" In Python, a string of text can be aligned left, right and center. .ljust(width) This method returns a left aligned string of length width. >>> width = 20 >>> print 'HackerRank'.ljust(width,'-') HackerRank---------- .center(width) This method returns a centered string of length width. >>> width = 20 >>> print 'HackerRank'.center(width,'-') -----HackerRank----- .rjust(width) This method returns a right aligned string of length width. >>> width = 20 >>> print 'HackerRank'.rjust(width,'-') ----------HackerRank # Task You are given a partial code that is used for generating the HackerRank Logo of variable thickness. Your task is to replace the blank (______) with rjust, ljust or center. # Input Format A single line containing the thickness value for the logo. # Constraints The thickness must be an odd number. 0 < thickness < 50 # Output Format Output the desired logo. # Sample Input 5 # testes # string = 'aeuhauehueaheua' # # print(string.ljust(30, '-')) # print(string.center(30)) # print(string.rjust(30, '-')) """ def text_alignment(): thickness = int(input()) # This must be an odd number c = 'H' # Top Cone for i in range(thickness): print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) # Top Pillars for i in range(thickness + 1): print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) # Middle Belt for i in range((thickness + 1) // 2): print((c * thickness * 5).center(thickness * 6)) # Bottom Pillars for i in range(thickness + 1): print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) # Bottom Cone for i in range(thickness): print(((c * (thickness - i - 1)).rjust(thickness) + c + (c * (thickness - i - 1)).ljust(thickness)).rjust( thickness * 6)) if __name__ == '__main__': text_alignment()
true
c34a9cea2effc8d23f885d6cb2afc3c5612e819e
Stanbruch/Strong-Password-Checker
/strong_password_check.py
1,132
4.1875
4
import re #strong password passStrong = False def passwordStrength(): #Enter password passwordText = input('Enter password: ') #Strength check charRegex = re.compile(r'(\w{8,})') lowerRegex = re.compile(r'[a-z]+') upperRegex = re.compile(r'[A-Z]+') digitRegex = re.compile(r'[0-9]+') if charRegex.findall(passwordText) == []: print('Password must contain at least 8 characters, 1 lowercase, 1 uppercase and 1 number. Try again.') elif lowerRegex.findall(passwordText) == []: print('Password must contain at least 1 lowercase character, 1 uppercase and 1 number. Try again') elif upperRegex.findall(passwordText) == []: print('Password must contain at least 1 uppercase character and 1 number. Try again.') elif digitRegex.findall(passwordText) == []: print('Password must contain at least 1 number. Try again.') else: print('Your password is strong.') global passStrong #Set passStrong True, succes input. passStrong = True return while not passStrong: #Again until password is strong enough. passwordStrength()
true
27651140b12fd771972ec657b968e37b68a3d0c4
skgande/python
/pythoncoding/com/sunil/functions/print_3_times_each_character.py
832
4.34375
4
class Print3TimesEachCharacter: """ Given a string, return a string where for every character in the original there are three characters. paper_doll('Hello') --> 'HHHeeellllllooo’ paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii’ """ def __init__(self): return def print_3_times(self, given_string): result = '' for letter in given_string: temp = letter * 3 result = result + temp return result def is_palindrome(self, input_string): return input_string == input_string[::-1] if __name__ == '__main__': input_string = input('Enter input string') my_obj = Print3TimesEachCharacter() result = my_obj.print_3_times(input_string) print(f'{result}') print(f'{my_obj.is_palindrome(input_string)}')
true
dcb168a423a010ee955af5c89d337ef411b40f4d
Its-me-David/Hangman-2.0
/hangman/hangman.py
2,438
4.125
4
import output import time # Den Spieler einladen zu spielen print("Willkommen bei Hangman") name = input("Gib deinen Namen ein: ") print("Hallo " + name + ", viel Glück!") time.sleep(1) print("Lasset das Spiel beginnen!") time.sleep(2) class visualisation: def __init__(self, word): self.word = word.upper() self.shown = "" self.guessed = [] self.step = 0 for i in word: if i != " ": self.shown += "-" else: self.shown += " " def trial(self, guess): if len(guess) != 1: print("Bitte nur einen Buchstaben eingeben!") elif guess.upper() in self.guessed: print("Diesen Buchstaben hast du bereits probiert!") elif guess.upper() in self.word: s = list(self.shown) for i in range(len(self.word)): if self.word[i] == guess.upper(): s[i] = guess.upper() self.shown = "".join(s) self.guessed.append(guess.upper()) self.guessed.sort() return True else: self.guessed.append(guess.upper()) self.guessed.sort() self.step += 1 return False def print_shown(self): print(self.shown) def print_visualisation(self): for i in output.visualisation[self.step]: print(i) def print_guessed(self): if len(self.guessed) == 0: print("Du hast noch keine Buchstaben geraten...") else: tried = "Bisher versuchte Buchstaben: " for i in self.guessed: tried += i tried += " " print(tried) def is_dead(self): return self.step == len(output.visualisation) - 1 def is_won(self): return not "-" in self.shown def go(self): while not self.is_won() and not self.is_dead(): self.print_shown() self.print_visualisation() self.print_guessed() print("Rate einen Buchstaben!") guess = input(">> ") self.trial(guess) self.print_shown() self.print_visualisation() self.print_guessed() if self.is_won(): print("Gratuliere, du hast das Wort erraten!") elif self.is_dead(): print("Tut mir leid, das war wohl nichts!")
false
7e9be152c65ecbce6d997a7c7bf5c0c7e5bbd69e
alexpereiramaranhao/guppe
/args.py
594
4.28125
4
""" Entendendo o *args - É um parâmetro, como outro qualquer; - Pode chamá-lo de qualquer nome, desde que inicie com * - Por convenção, utiliza-se o *args - Guarda os valores de entrada em uma tupla """ def somar_numeros(*args): return sum(args) print(somar_numeros(1, 2)) print(somar_numeros(1, 2, 3)) print(somar_numeros(1, 2, 4, 2)) """desempacotador - o * informa ao Python que estamos passando com argumento, uma coleção de dados, assim, entende que precisa desempacotar os dados""" numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(somar_numeros(*numeros))
false
ad7d1249367d98b1570775c3adbfabaa1e83c909
Henrique-Temponi/PythonForFun
/PythonOtavio/PythonBasic/05-operators.py
781
4.34375
4
""" we have a few operators in python: +, -, *, **, /, //, %, () """ # Both + - are quite simple, the first adds, the second subtracts print(1 + 1) print(1 - 1) # note with +, you add strings together print("bana" + "na") # * = multiples print(2*2) # NOTE: you can multiply strings, with you copy x number of times a string print("bana" * 20) # ** = power to print(2**10) # 1025 (2^10) # / = division with rest print(5 / 2) # will return a real value, since 5 is even # // = division without rest print(5 // 2) # returns a int value, only getting the numbers after the dot # % = rest return print(5 % 2) # return the rest of the division # () = tells to the computer which operation to do first print(10 * (2 + 1)) # returns 30, without the parentheses it returns 21
true
93e2f9044e3c5fbd595cc325171be2892791fbc8
Henrique-Temponi/PythonForFun
/PythonOtavio/PythonBasic/17-split_join_enumerate.py
1,887
4.53125
5
""" Split - this will split a string with the chosen separator, ( default is whitespace ) Join - this will join multiple elements (eg. in a list or a string) enumerate - this will create a index for a iterable object (eg. list, string, dictionary, etc) these function covers a lot of ground when it comes to manipulate an object, simple and effective these will help you out along the way """ # the first we'll cover is the split function, using a string, we will split the whitespaces x = "Built purse maids cease her ham new seven among" list1 = x.split() # so what we've done is, when python founds a whitespace it will cut and return what was before the cut as a new object # you can see that was printed was a list with the cut elements print(list1) # now that we have separated the string, we can join it back, with join, how to use it it's quite simple as well # first the define what the separator will be separator = " " # in this case we'll use the whitespace # after that, we say that we want to use that separator to join our list y = separator.join(list1) # and finally we give the iterable object to join # so in plain english this would mean, i want to use the separator( whitespace ) to join a iterable list # now, the enumerate function, this can be used to enumerate a list or a string # let's say that you have a list and you want to get the index of each name, you could add another variable # or you could use enumerate z = ['Banana', "Mango", "Apple"] # let's put an index in each of them for index, food in enumerate(z): print(index, food) # this will give us a index right of the bat, while saving a few extras variables, quite handy # you may notice that we used 2 variables in the for, we'll get to that later, but for now, just know that # you can have two variables in for, this can give a flexible for.
true
99fef6c9ac257ed5c56df6308f37e9f16d607b3c
KostaPapa/Python_Works
/Practice/a30ClassGeneralForm.py
2,806
4.5
4
class TypeName( object ): '''This class will contain the general form of a class.''' def __init__( self, dataMember_1, dataMember_2, dataMember_3 = 3 ): # defaultValue '''This function will initialize the variables needed to be used during class design. Notice that other variables may be needed and they can be created without being passed as arguments.''' self.__dataMember_1 = dataMember_1 self.__dataMember_2 = dataMember_2 self.__dataMember_3 = dataMember_3 self.__dataMember_4 = 4 self.__dataMember_5 = None def getDataMemember_1( self, newDataMember_1 ): '''This funtion will return the newValueOfDataMemember_1 so it can be use by the programmer.''' self.__dataMember_1 = newDataMember_1 return self.__dataMember_1 def getDataMemember_2( self, newDataMember_2 ): '''This function will return a newDataMember_2 so it cab be used by the programmer.''' self.__dataMember_2 = newDataMember_2 return self.__dataMember_2 def calcValue( self ): '''This funtion will make calculations.''' self.__totalValue = self.__dataMember_1 + self.__dataMember_2 + self.__dataMember_3 + self.__dataMember_4 self.__average = self.__totalValue / 4 self.__percentage = self.__average * 100 def __str__( self ): '''This funtion will print the data memebrs.''' return 'The total value is: %s\nThe average is: %s\nThe percentage is: %s' %( self.__totalValue, self.__average, self.__percentage ) def main(): def TestingClass(): '''This funtion will test the class.''' var1 = TypeName(1,2) var1.calcValue() var2 = TypeName(1,2) var2.getDataMemember_1(1.11) var2.calcValue() var3 = TypeName(1,2) var3.getDataMemember_2(2.22) var3.calcValue() var4 = TypeName(1,2) var4.getDataMemember_1(1.11) var4.getDataMemember_2(2.22) var4.calcValue() print "The first variable is holding this information:\n",var1 print '\n' print "The second variable is holding this information:\n",var2 print '\n' print "The third variable is holding this information:\n",var3 print '\n' print "The fourth variable is holding this information:\n",var4 print '\n' # Putting in a list print "Here Begins the list thing...( # _ # )\n" listOfVar = [] listOfVar.append(var1) listOfVar.append(var2) listOfVar.append(var3) listOfVar.append(var4) for variables in listOfVar: print variables print "\n" TestingClass() main()
true
b5006fe99312946863316ce419427aad74635803
KostaPapa/Python_Works
/LAB/REC02/rec02.0 ( Box ).py
2,468
4.375
4
""" User Name: kpapa01 Programmer: Kostaq Papa Purpose of this program: This program will print a box with a certain width and character. Constrains: It will compile from left to right. The is an integer number. """ def askTheuserToenterCharacter (): '''This function will ask the user to enter a character for the box.''' character = raw_input ("Please enter a character:") return character def askTheuserToenterWidthAndNumberOfBoxes(): '''This function will ask the user to enter width.''' width = int ( raw_input("Please, enter the width of the box: ")) numberOfboxes = int (raw_input ("Please, enter the number of boxes you wish to draw: ")) return width, numberOfboxes def testThewidthAndNumberOfBoxes (width, numberOfboxes): '''This function will test if the width is positive.''' while (width < 0): print "The number entered fot the box width must be positive." print "Please try again." width = int ( raw_input("Please, enter the width of the box: ")) print "The number you entered is correct." while (numberOfboxes < 0): print "The number entered must be positive." print "Please try again." numberOfboxes = int (raw_input ("Please, enter the number of boxes you wish to draw: ")) print "The number you entered is correct." def topAndbottonLineofThebox (width, character): '''This function draws the top and the botton line of the box''' topAndBotton = (width * character) print topAndBotton def middleSpacesofThebox (width, character): ''' the middle line of the box will have a 'width' space. ''' print character + ' ' * width + character def pressAnykeyToexit(): '''This function will ask the user to exit.''' raw_input ("Please, enter any key to exit....") def main (): ''' Draws a box with a certain width and characters. Width must be numeric ''' boxCharacter = askTheuserToenterCharacter() boxWidth, boxNumber = askTheuserToenterWidthAndNumberOfBoxes () testThewidthAndNumberOfBoxes(boxWidth, boxNumber) topAndbottonLineofThebox (boxWidth, boxCharacter) middleSpacesofThebox (boxWidth, boxCharacter) middleSpacesofThebox (boxWidth, boxCharacter) middleSpacesofThebox (boxWidth, boxCharacter) middleSpacesofThebox (boxWidth, boxCharacter) topAndbottonLineofThebox (boxWidth, boxCharacter) pressAnykeyToexit() main ()
true
1701db222173b6b1c61555835dfa4d345b0cf30a
jkrobinson/crash
/Ch04/friend_pizzas.py
299
4.125
4
pizzas = ['meat lovers', 'hawaiian', 'cheesy'] pizzas.append('supreme') friend_pizzas = pizzas[:] friend_pizzas.append('bbq chicken') print("My favourite pizzas are:") for pizza in pizzas: print(pizza) print("\nMy friend's favourite pizzas are:") for pizza in friend_pizzas: print(pizza)
true
ddc554e34944d80e82ddfc5b3013a989f2026e5b
Surafel-zt/Final-website
/GUI questions.py
1,761
4.21875
4
from tkinter import * from tkinter import messagebox root = Tk() root.title('Assignment 2 GUI') question_1 = Label(root, text="Who lives in the second corner?", font=('Verdana', 12)) question_1.grid(row=0, column=0) question_2 = Label(top, text="Who lives in the middle?", font=('Verdana', 12)) question_2.grid(row=1, column=0) question_3 = Label(top, text="Who lives between B and G?", font=('Verdana', 12)) question_3.grid(row=2, column=0) question_4 = Label(top, text="Who is the neighbor of A?", font=('Verdana', 12)) question_4.grid(row=3, column=0) question_5 = Label(top, text="How many houses are there between B and E? (only numbers)", font=('Verdana', 12)) question_5.grid(row=4, column=0) entry_a = Entry(top, width=25, borderwidth=8) entry_a.grid(row=0, column=1) entry_b = Entry(top, width=25, borderwidth=8) entry_b.grid(row=1, column=1) entry_c = Entry(top, width=25, borderwidth=8) entry_c.grid(row=2, column=1) entry_d = Entry(top, width=25, borderwidth=8) entry_d.grid(row=3, column=1) entry_e = Entry(top, width=25, borderwidth=8) entry_e.grid(row=4, column=1) answer = Button(top, text='Answer', font=('Verdana', 12), command=answer) answer.grid(row=5, column=1) instruction = Label(root, text="""Read the following Scenario. If you understand the Scenario and want to continue click Yes. If you do not understand the scenario and do not want to continue click No. There is 1 house between D and F. C is between E and G. F is neighbor of G.There are two houses between A and G.""", font=('verdana, 13'), bg='white') instruction.pack() Button(root, text='Click to choose yes/no', font=('verdana, 13'), bg='#345DE4', fg='white', command=popup).pack() root.mainloop()
true
86654923966393893975ca3b0ebcb9ed3720cb09
inwenis/learn_python
/01_print.py
1,298
4.53125
5
print("Hello there human!") print("do you know you can put any text into a print()?") print("like stars *******, numbers: 1,2,42,999") # exercise 1: Use print() to display "Hello world" in the console # Do one exercise at a time. # exercise 2: Use print() to display some asterisks (this is a # asterisk -> * ) # exercise 3: Use multiple print() to display a triangle from # asterisks. # * # ** # *** # **** # As you noticed everything after a hash sign # is plain english and # is ignored by python. The hash sign # begins a comment - text # ignored by the python interpreter. # During our classes comments are used for explanations and # exercises. Usually programmers use comments to describe what the # code is intended to do, or why it was written. Comments usually # are placed above code. # Sample comments from real large scale systems: # Should be removed when all business tools uses DeleteTrade (from ETRM/Allegro) # For multi hour trades, DST long day and DST short day are currently not handled correctly (from ETRM/Allegro) # compute standard deviation for time series and add it to message # (I have no idea why, but finance department requested it) # shipping department has a bug in their system, this weird code is # a workaround, remove once shipping system is fixed!
true
b6ec41689760a4e558bd4605a5fcf99ee9139079
inwenis/learn_python
/08_interactive_shell.py
2,605
4.21875
4
# This file is not about a new part of the python language. It's # about another way to execute python code. # Till now we have execute our python scripts by invoking the python # program from terminal and passing it a script to execute. # If you use PyCharm and run scripts with "right click" + "Run ...." # PyCharm invokes python.exe and passes the path to your script file # to python.exe # Wouldn't it be great if we could test small pieces of code without # writing new scripts? # Fear no more! Because we can! # If you type "python" in your terminal and do not give python any # file to execute, python will start the interactive shell. Now you # can type pieces of python code and once you press [enter] python # will execute the code. # Terminal = cmd = Command Prompt # To run Command Prompt in Windows press Windows key, type "cmd" and # press [enter] # > python # >>> print("hello") <-- this you should type # hello <-- this python should display # How to exit a interactive shell session? # type "exit()" or press Ctrl+Z[enter] # In the interactive shell we can do anything we can do in a script: # > python # >>> a = 12 # >>> b = 34 # >>> c = a * b # >>> print(c) # 408 # >>> c <-- to see a variables value we don't # even need to type print(c) # Multi-line statements # The interactive shell allows to test multi-line statements like a # for loop. After you type the first line of the for loop the shell # will recognize you started a loop and you will be able to type # more lines before executing your code. Python remains strict about # spaces and indents so remember to use the correct indentation # level. # > python # >>> my_list = ["A", 42, 24, "monkey"] # >>> for character in my_list: # ... print(character) # ... <-- at this point if you press [enter] # leaving an empty line, your for # loop will be executed. # A # 42 # 24 # monkey # The name "interactive shell" might be somewhat confusing. # The adjective "interactive" means that we can execute code in the # terminal and immediately get results from python. As if talking to # python. # "shell" is a synonym for a layer between the user (you) and the # python interpreter or operating system (OS). # What ever you type in the "interactive shell" will be passed to the # python interpreter. The python interpreter will further pass # commands to the OS. # exercise 1: Create a list of numbers and sum them in the # interactive shell
true
68d06770e3db6145a77e8fe1c4fa8515cbbbeb0e
kannan4k/python_regex_implementation
/SubString.py
2,604
4.3125
4
"""Implementation of the Python Programming Contest 1""" from __builtin__ import range def split_string(text): """ This function will split the string into list based on the '*' as delimiter For Ex: input = "Hello*Python" Output = ['Hello', 'Python'] and Yes it will remove the \ in the string also """ previous = 0 word_list = [] for index in range(len(text)): if text[index] == '*' and text[index-1] != '\\': if text[previous:index]: word = '' for x in text[previous:index]: #strip of escape sequence char if x != '\\': word += x word_list.append(word) previous = index+1 else: word = '' for x in text[previous:]: if x != '\\': word += x word_list.append(word) return word_list def substring(pattern, text): """ main substring function which will check for the sequential lists """ pos = 0 is_valid = True msg = "%s is a substring of %s" % (pattern, text) words = split_string(pattern) for word in words: n = find_replica(text, word, pos) if n < 0: msg = "%s is not a substring of %s" % (pattern, text) is_valid = False return is_valid, msg pos = n + len(word) return is_valid, msg def find_replica(text, word, pos): """ implementation of the string find replica - simple string searching function """ is_valid = -1 length_1 = len(text) length_2 = len(word) while (pos <= length_1-length_2): for index_2 in range(length_2): if text[pos+index_2] != word[index_2]: is_valid = -1 break is_valid = True else: is_valid = pos break pos += 1 return is_valid if __name__ == "__main__": ### Inputs ### string_2 = raw_input("Enter the String1 or Just Hit Enter Key to see the results for given strings") if not string_2: string_1 = "H\*l*23" _, result = substring('Hello1', "Hello") print result _, result = substring('H\*l*23', "H*lllo123") print result _, result = substring('Hel*23', "123Hello") print result _, result = substring('Hello*How', "Hello*How are you?") print result string_1 = raw_input("Enter a Pattern (string2) or Just Hit Enter Key to see the results for given strings") _, result = substring(string_1, string_2) print result
true
34a1c766420bf8a0ad3b5074fcfd615a0ae22e06
RichHomieJuan/PythonCourse
/Dictionaries.py
388
4.15625
4
#dictionaries are indexed by keys. dictionary = {} #not very useful tel = {"Mary": 4165, "John" : 4512, "Jerry" : 5555 } print(tel) tel ["jane"] = 5432 #inserts into the dictionary print(tel) print(tel ["Jerry"]) #looks up the specified thing in dictionary del tel["Jerry"] #deletes said person or value. print(tel) #dictionaries are a lot more useful when looking up certain things.
true
96644660d0c878ea20b83c708ac773f4e0250a3c
georgetaburca/analog-clock
/analog_clock.py
1,556
4.15625
4
#simple analog clock in Python import time import turtle wn = turtle.Screen() wn.bgcolor("black") wn.setup(width=600, height=600) wn.title("Analog Clock") wn.tracer(0) #Create the drawing pen pen = turtle.Turtle() pen.hideturtle() pen.speed(0) pen.pensize(3) def draw_clock(h, m, s, pen): #Draw clock shape pen.up() pen.goto(0, 210) pen.setheading(180) pen.color("blue") pen.pendown() pen.circle(210) #Draw the lines on the circle pen.penup() pen.goto(0,0) pen.setheading(90) for _ in range(12): pen.fd(190) pen.pendown() pen.fd(20) pen.penup() pen.goto(0,0) pen.rt(30) #Draw the hour hand pen.penup() pen.goto(0,0) pen.color("white") pen.setheading(90) angle=(h/12)*360+(m/60)*30 pen.rt(angle) pen.pendown() pen.fd(100) #Draw the minute hand pen.penup() pen.goto(0,0) pen.color("white") pen.setheading(90) angle=(m/60)*360+(s/60)*6 pen.rt(angle) pen.pendown() pen.fd(180) #Draw the seconds hand pen.penup() pen.goto(0,0) pen.color("red") pen.setheading(90) angle = (s / 12) * 360 pen.rt(angle) pen.pendown() pen.fd(70) while True: h = int(time.strftime("%I")) m = int(time.strftime("%M")) s = int(time.strftime("%S")) draw_clock(h, m, s, pen) wn.update() time.sleep(1) pen.clear() wn.mainloop()
true
eb0b85afa0d48d3ffd65d74b0448e7aaa2af526e
ssharp96/Comp-Sci-350
/SSharpArithmeticMean.py
316
4.125
4
# Arithmetic Mean # author: SSharp def arithmeticMean(a,b): '''Computes and returns the arithemtic mean of a and b''' return ((a+b)/2) a = float(input("Enter a number: ")) b = float(input("Enter another number: ")) result = arithmeticMean(a,b) print("The arithmetic mean of",a,"and",b,"is",result)
true
fe8de17a88fafa45a31d22fefd6cc4404e2d219a
jeffonmac/Fibonacci-Numbers
/Search_dichotomy.py
2,149
4.3125
4
# Fonction fibonacci Sequence with loop "recursive" : mem = {} def fib(number): # print("fib" + str(number)) if number < 1: return 0 if number < 3: return 1 if number not in mem: mem[number] = fib(number - 1) + fib(number - 2) return mem[number] # With loop "for" : def fib2(): list = [0, 1] for i in range(2, 25): new_value = list[i - 1] + list[i - 2] list.append(new_value) return list # With loop "while" : def fib3(): i = 0 list = [0, 1] f = 25 while len(list) < f: new_value = list[i - 1] + list[i - 2] list.append(new_value) # i = i + 1 i = len(list) return list # Fonction dichotomous research def search_dic(numb, short_list): start = 0 end = len(short_list) - 1 middle = (start + end) // 2 while start < end: if short_list[middle] == numb: return middle elif short_list[middle] > numb: end = middle - 1 else: start = middle + 1 middle = (start + end) // 2 return start # Loop with Fibonacci Sequence and # adding in the list "fibonacciList" : fibonacciList = [] for number in range(25): a = fib(number) fibonacciList.append(a) # Fibonacci List with loop "for" : fibonacciList2 = fib2() # Fibonacci List with loop "while" : fibonacciList3 = fib3() # Displaying the top 25 values : print("List of 25 first Fibonacci Number with recursive :") print(fibonacciList) print("List of 25 first Fibonacci Number with loop for :") print(fibonacciList2) print("List of 25 first Fibonacci Number with loop while :") print(fibonacciList3) # Displaying the index of the number 17711 : index = search_dic(17711, fibonacciList) print("Index of 17711 Number fonction (- Recursive - list):", (index + 1)) # Displaying the index of the number 17711 : index = search_dic(17711, fibonacciList2) print("Index of 17711 Number fonction ( - For - list):", (index + 1)) # Displaying the index of the number 17711 : index = search_dic(17711, fibonacciList3) print("Index of 17711 Number fonction ( - While - list):", (index + 1))
false
a4e4d9ba8286920529b347b58aa34d40a065eb77
MthwBrwn/data_structures_and_algorithms
/data_structures/hash_table/hash_table.py
2,355
4.15625
4
class Hashtable: """ """ def __init__(self): self.size = 64 self.bucket = [None] * self.size def __repr__(self): return f'bucket size : {self.size}' def __str__(self): return f'bucket size : {self.size}' # A hash table should support at least the following methods: # hash key value def sum_hash(self, key): """ This hashing function takes the key and sums the ASCII values (ord) of the key and then uses mod in order to obtain the """ hash = 0 for char in key: hash += ord(char) return hash % self.size # .put(key, value) - store a value with the given key def put(self, key, value): """ put takes in two arguments key and value and hashes the key to an index int and assigns the value to that int """ hash = self.sum_hash(key) key_value = [key, value] if self.bucket[hash] is None: self.bucket[hash] = list([key_value]) return True else: for pair in self.bucket[hash]: if pair[0] == key: pair[1] == value return True self.buckets[hash].append(key_value) return True # .get(key) - get the value associated with the given key def get(self, key): """ get takes the key, and returns the value associated with that key """ hash = self.sum_hash(key) if self.bucket[hash] is not None: for pair in self.bucket[hash]: if pair[0] == key: return pair[1] # .remove(key) - delete a value associated with a key def remove(self, key): """ This method searches for the key given and if key is located in bucket will pop contents from bucket. """ hash = self.sum_hash(key) if self.bucket[hash]is None: return False for i in range(len(self.bucket[hash])): if self.bucket[hash][i][0] == key: self.bucket[hash].pop(i) return True # .keys() - return a collection of all the keys def keys(self): """ This is a simple print method for every item in bucket. """ for item in self.bucket: if item is not None: print(item)
true
87b2555f4151df0cf97d84d3dddd5639d9eb7433
OlehPalka/Algo_lab
/insertion_sort.py
1,068
4.21875
4
""" This module contains insertion sort. """ def insertion_sort(array): """ Insertion sort algorithm. """ for index in range(1, len(array)): currentValue = array[index] currentPosition = index while currentPosition > 0 and array[currentPosition - 1] > currentValue: array[currentPosition] = array[currentPosition - 1] currentPosition = currentPosition - 1 array[currentPosition] = currentValue return array def insertion_sort_comparisions(array): """ Insertion sort algorithm. """ comparisions = 0 for index in range(1, len(array)): currentValue = array[index] currentPosition = index while currentPosition > 0 and array[currentPosition - 1] > currentValue: comparisions += 2 array[currentPosition] = array[currentPosition - 1] currentPosition = currentPosition - 1 comparisions += 2 array[currentPosition] = currentValue return comparisions
true
62d6467157d0a54e20dca9a14ff9d5020c3dbe79
error-driven-dev/Hangman-game
/hangman.py
2,544
4.125
4
import random import string #open text file of words, save as a list and randomly select a word for play def new_word(): with open("words.txt", "r") as word_obj: contents = word_obj.read() words = contents.split() word = random.choice(words) return word def letters_display(secret_word): result = ["_"] * len(secret_word) print("Your new word has " + str(len(secret_word)) +" letters.") return result def remaining_letters(used, alpha): if used in alpha: alpha.remove(used) return alpha else: print("\nOK DING-DONG! You have already used that letter -- try again!") def hangman(): alpha = list(string.ascii_lowercase) count = 6 play_word = new_word() letters_list = list(play_word) result = letters_display(play_word) print(play_word) while letters_list != result: print("\nHere are the letters you have to choose from:") for letter in alpha: print (letter, end="" + " ") guess = input("\n\nGuess a letter: ").lower() if guess not in string.ascii_lowercase or guess == "": print("Uh...Letter please!") elif guess in letters_list and guess in alpha: print("\nWOOT-WOOT!! You guessed a letter!\n") for index, char in enumerate(letters_list): if char == guess: result[index] = guess for char in result: print (char, end=" ",) print("\n") remaining_letters(guess, alpha) elif count > 0 and guess in alpha: print("\nThat letter is not in the word. Try Again!") count -= 1 remaining_letters(guess, alpha) elif count == 0: print ("\nHANGMAN!") print("The word was: " + play_word) play_again() break else: remaining_letters(guess, alpha) if letters_list == result: print("NICE JOB!! YOU WON!") play_again() def play_again(): play_again = input("Do you want to play again? Type 'y' for yes, 'n' for no: ") if play_again == 'y': hangman() else: quit hangman()
true
e38f902083d53e2ecdcec7e42d6b0e1bdeb4b7af
dj5353/Data-Structures-using-python
/CodeChef/matrix 90(anticlockwise).py
523
4.375
4
#for matrix 90 degree anticlockwise rotation #and transpose the matrix #reverse matrix all column wise def matrix_rotate(m): print("Matrix before rotation") for i in (m): print(i) # Transpose matrix for row in range(len(m)): for col in range(row): m[row][col], m[col][row] = m[col][row], m[row][col] # Matrix reverse all columns m.reverse() print("matrix after rotation") for j in (m): print(j) matrix_rotate([[1,2,3],[4,5,6],[7,8,9]])
true
7f5b4896c3c47f834ff7dbb4aa5b65e2dba2437c
dj5353/Data-Structures-using-python
/CodeChef/Binary-search.py
738
4.15625
4
def binarySearch(a,n,searchValue): first = 0 last = n-1 while(first<last): mid = (first + last)//2 if(searchValue<a[mid]): last = mid-1 elif(searchValue>a[mid]): first = mid+1 else: return mid return -1 n = int(input("Enter the number of elements you want to insert")) a = [None]*n for i in range(n): a[i] = int(input("Enter the element")) searchValue = int(input("Enter the value you want to search")) index = binarySearch(a,n,searchValue) if(index == -1): print("The element {} is not present in the list".format(searchValue)) else: print("The element {} is present at index {} in the list".format(searchValue,index))
true
258d837ce4d5bfd7c4e4a7cbdc5517aec582d9e1
abusamrah2005/Saudi-Developer-Organization
/Week4/secondLesson.py
1,268
4.3125
4
# set of names , we have four names. setOfNames = {'waseem', 'ahmed', 'ali', 'dayili'} # by using len() function to calculate the number of items seted in the set print('we have ' + str(len(setOfNames)) +' names are there.') # there are two function to remove elemen in set 'remove() & discard()' print('Names: ' + str(setOfNames)) # remove element by using discard() setOfNames.discard('dayili') print('Names: ' + str(setOfNames)) # pop() function used to remove last element of the set like a stack setOfNames.pop() print('Names: ' + str(setOfNames)) # to clear all elements of the set one same time by using clear() function setOfNames.clear() if setOfNames == set([]): # set([]) mean null , no elements are there print('the set is empty.') else: print('there are elements.'+str(setOfNames)) # delete the set form the memory 'RAM - > Random access memory using for saved all instrctions of the computer.' del setOfNames # try call the set name after delete it. try: print(setOfNames) # the error becaue we're delete it from the memory by using del() function in set. # craete set of elements by using set() Constructor is main function of the set class except: setOfNamesAgain = set(('waseem', 'ahmed', 'ali', 'dayili')) print(setOfNamesAgain)
true
5066c5fccfc4e132798a0d04d59fb1de6e0f68da
AntonioRice/python_practice
/strings.py
752
4.1875
4
num = 3; print(type(num)); print(5 + 2); print(5 / 2); print(5 - 2); # exponents print(5 ** 2); # modulus print(5 % 2); print(4 % 2); # OOP print(3 * 2 + 4); print(3 * (2 + 4)); num = 1; num += 1; print(num); # absolute value print(abs(-3)); # round print(round(5.8901)); # how many digits id like to round to print(round(5.8901, 1)); # compare numbers, will return booleans num_1 = 3 num_2 = 5 print(num_1 > num_2); # false print(num_1 < num_2); # true print(num_1 == num_2); # false print(num_1 != num_2); # true print(num_1 >= num_2); # false print(num_1 <= num_2); # true # calulating string integers num_1 = '4' num_2 = '5' # CASTING, getting manipulating the int version of str num_1 = int(num_1); num_2 = int(num_2); print(num_1 + num_2);
true
d3b2a74ce570df798dc7da790b6bdfcdb20448d1
JiangRIVERS/data_structure
/LinkedBag/linked_structure.py
743
4.375
4
#定义一个单链表节点类 class Node: """Represents a singly linked node""" def __init__(self,data,next=None): """Instantiates a Node with a default next of None""" self.data=data self.next=next class TwoWayNode(Node): """Represents a doubly linked node""" def __init__(self,data,previous=None,next=None): """Instantiates a TwoWayNode""" Node.__init__(self,data,next=next) self.previous=previous #if __name__=='__main__': #Just an empty link # node1=None #A node containing data and an empty link # node2=Node("A",None) #A node containing adata and a link to node2 # node3=Node("B",node2)
true
1a51c8997f8090c61af75592596f44571005001f
JiangRIVERS/data_structure
/Calculate_arithmetic_expressions/calculate_function.py
543
4.375
4
""" Filename:calculate_function Convert string operator to real operator """ def calculate_function(string,operand1,operand2): """Raises KeyError if the string operator not in string list""" string_list=['+','-','*','/'] if string not in string_list: raise KeyError('We can\'t deal with this operator') elif string=='+': return operand2+operand1 elif string=='-': return operand2-operand1 elif string=='*': return operand2*operand1 elif string=='/': return operand2/operand1
true
00b3c3106f95ccb9059c195315d28812ec71f1f6
RMolleda/Analytics_course
/delivery/basic_functions.py
540
4.15625
4
def append_item(item, where): """ U must set the object u want to append as the value of "object" and "where" should be the list where u want to append it """ where.append(item) def remove_item_list(item, where): """ pop the input from a list it will loop arround all the list, and if the item is on it, it will be removed from the list """ while True: if item in where: where.remove(item) else: break def suma(*args): return sum(args)
true
d4c588d0811d01742dcfd25915554ea1fd06fe69
Anonymous-indigo/PYTHON
/shapes/heptagon.py
231
4.15625
4
#To draw a heptagon, you will need to have seven sides and have a 51.42 degree angle on each side. The lenth of each side will not affect the angle needed. import turtle t=turtle for n in range(7): t.forward(100) t.right(51.42)
true
6abf212d5cbd88ec6c3802cee3a9da7c4b740bcc
RuidongZ/LeetCode
/code/290.py
1,373
4.125
4
# -*- Encoding:UTF-8 -*- # 290. Word Pattern # Given a pattern and a string str, find if str follows the same pattern. # # Here follow means a full match, such that there is a bijection # between a letter in pattern and a non-empty word in str. # # Examples: # pattern = "abba", str = "dog cat cat dog" should return true. # pattern = "abba", str = "dog cat cat fish" should return false. # pattern = "aaaa", str = "dog cat cat dog" should return false. # pattern = "abba", str = "dog dog dog dog" should return false. # Notes: # You may assume pattern contains only lowercase letters, # and str contains lowercase letters separated by a single space. class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ plen = len(pattern) str = str.split(" ") slen = len(str) if plen != slen: return False d1 = {} d2 = {} for i in range(plen): if pattern[i] in d1 and str[i] in d2: if str[i] != d1[pattern[i]] or pattern[i] != d2[str[i]]: return False elif pattern[i] not in d1 and str[i] not in d2: d1[pattern[i]] = str[i] d2[str[i]] = pattern[i] else: return False return True
true
e0fa225b4ed69b3234517176b2c8c3a519b93c39
RuidongZ/LeetCode
/code/451.py
1,130
4.125
4
# -*- Encoding:UTF-8 -*- # 451. Sort Characters By Frequency # Given a string, sort it in decreasing order based on the frequency of characters. # Example 1: # Input: "tree" # Output: "eert" # # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # # Example 2: # Input: "cccaaa" # Output: "cccaaa" # # Explanation: # Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. # Note that "cacaca" is incorrect, as the same characters must be together. # # Example 3: # Input: "Aabb" # Output: "bbAa" # # Explanation: # "bbaA" is also a valid answer, but "Aabb" is incorrect. # Note that 'A' and 'a' are treated as two different characters. class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ d = {} for i in s: if i in d: d[i] += 1 else: d[i] = 1 ans = "".join(i[0] * i[1] for i in sorted(d.items(), key=lambda k: k[1], reverse=True)) return ans
true
3651948d047f7ab76cba9e74c98e2b9d53a62504
RuidongZ/LeetCode
/code/537.py
1,011
4.15625
4
# -*- Encoding:UTF-8 -*- # 537. Complex Number Multiplication # Given two strings representing two complex numbers. # You need to return a string representing their multiplication. Note i2 = -1 according to the definition. # Example 1: # Input: "1+1i", "1+1i" # Output: "0+2i" # Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. # Note: # The input strings will not have extra blank. # The input strings will be given in the form of a+bi, # where the integer a and b will both belong to the range of [-100, 100]. # And the output should be also in this form. class Solution(object): def complexNumberMultiply(self, a, b): """ :type a: str :type b: str :rtype: str """ a = a.split("+") b = b.split("+") x1 = int(a[0]) x2 = int(a[1][:-1]) y1 = int(b[0]) y2 = int(b[1][:-1]) x = x1*y1 - x2*y2 y = x1*y2 + x2*y1 return str(x)+"+"+str(y)+"i"
true
050bb7bbddb8040a778bfae81d54776c95f375c9
Dillon1john/Python
/finalreview4finishit.py
203
4.1875
4
temp=70 humid=45 if(temp<60) or (temp>90) or (humid>50): print("Stay inside") else: if (humid==100): print("It is raining outside") else: print("Do you want to take a walk?")
true
a28854b23700b3af588a06aa525c53ad503a5ad5
Dillon1john/Python
/classworkstudynov7.py
575
4.125
4
#example of input list name=[ ] ssn=[ ] age= [ ] while True: Last_name=input("Enter your last name: ") if Last_name in name: print("Your name already in the list") else: name.append(Last_name) print("I just got your registered") Social= input("Enter your SSN: ") if Social in ssn: print("Your social already in list") else: ssn.append(Social) print("SSN registered") Age=input("Enter your age: ") age.append(Age) print(name,'\t',ssn,'\t',age)
true
450a60088fd4913f56d817ef4681a9550ef12198
btgong/Cmpe131Homework-Python
/calculator.py
1,215
4.4375
4
def calculator(number1, number2, operator): ''' Returns the calculation of two decimal numbers with the given operator Parameters: number1 (float): A decimal integer number2 (float): Another decimal integer) operator (string): Math operation operator Returns: Calculation of number1 and number2 with the given operator ''' # Check which operator to use. if operator in ('+','-','*','/','//','**'): if operator == "+": return number1 + number2 elif operator == "-": return number1 - number2 elif operator == "*": return number1 * number2 # Dividing by 0 is undefined. elif operator == "/" and number2 != 0: return number1 / number2 # Dividing by 0 is undefined. elif operator == "//" and number2 != 0: return number1 // number2 elif operator == "**": return number1 ** number2 else: return False # Terminate if invalid operator is given. else: return False def parse_input(): ''' Parses user's equation input and calculates. Parameters: None Returns: None ''' # Takes user input equation = input("Enter equation") # To be able to use in calculator() list = equation.split( ) print(calculator(float(list[0]), float(list[2]), list[1]))
true
119c4153fe8a13d13ad8f522aa008623362a4218
skinisbizapps/learning-python
/ch02/loops.py
906
4.15625
4
def main(): print('welcome to loops') x = 0 # define a while loop while x < 5: print(x) x = x + 1 # define a for loop for x in range(5, 10): print(x) # use a for loop over a collection days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] for day in days: print(day) # use the break and continue statements for x in range(5, 10): # continue skip printing the x but moves on the next value if x % 2 == 0: continue # break stops any further processing and exits out of the loop if x == 9: break print(x) # using the enumerate() function to get index months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] for i, month in enumerate(months): print(month, i + 1) if __name__ == '__main__': main()
true
bcd4b4dea007d8621524af3939d45d96c482236d
jonasht/CursoEmVideo-CursoDePython3
/mundo3-EstruturasCompostas/106-sistemaInterativoDeAjuda.py
862
4.28125
4
# Exercício Python 106: # Faça um mini-sistema que utilize o Interactive Help do Python. # O usuário vai digitar o comando e o manual vai aparecer. # Quando o usuário digitar a palavra 'FIM', o programa se encerrará. # Importante: use cores. vermelho = '\033[41m' verde = '\033[42m' amarelo = '\033[43m' azul = '\033[44m' f = '\033[m' def ajudar(ajuda): print(azul) help(ajuda) print(f) def l(char='', fim=''): print(char+'=-'*30+'=', fim) def começar(): while True: l(amarelo) print('sistema de ajuda Pyhelp') l() palavra = input('[digite sair p sair]\nfuncao ou biblioteca: ') l(fim=f) if palavra.upper() == 'SAIR': print(f) break else: print(azul, f'acessando o comando {palavra}', f) ajudar(palavra) começar()
false
51e035be77493ab9fcf143b7b6bc192493fb087d
MattRijk/algorithms
/randomization_algorithm.py
508
4.1875
4
""" Randomization Algorithm - Randomizing an array. For i = 1 To N ' Pick an item for position i. j = Random number between i and N ' Swap items i and j. temp = value[i] value[i] = value[j] value[j] = temp Next i """ # python from random import randint alist = [1,2,3,4,5,6] result = [] n = len(alist) for i in range(1, n): # Pick an item for position i. j = randint(i, n-1) # Swap items i and j. alist[i], alist[j] = alist[j], alist[i] print(alist)
false
825d001f7eba45a6d8a663321370a608a7a6cbca
egalleye/katas
/two_smallest.py
659
4.1875
4
def sum_two_smallest_numbers(numbers): smallest = -1 secondSmallest = -1 for num in numbers: if ( smallest < 0 ): smallest = num else: if ( num < smallest ): secondSmallest = smallest smallest = num elif ( num < secondSmallest or secondSmallest < 0 ): secondSmallest = num return smallest + secondSmallest #print ("smallest is {0} second is {1}".format(smallest, secondSmallest)) if __name__ == "__main__": sum_two_small = 0 sum_two_small = sum_two_smallest_numbers([25, 42, 12, 18, 22]) print("result = ", sum_two_small)
true
bc69b59ed4ac02f07ca0b48a4581787feb7e6416
csouto/samplecode
/CS50x/pset6/caesar.py
1,067
4.15625
4
import sys import cs50 # Allow two arguments only, program will exit otherwise if len(sys.argv) != 2: # change error message print("Please provide one argument only") exit(1) # Use the the second argument as key k = int(sys.argv[1]) # Print instructions on screen, ask for input and calculate the length of it print("plaintext: ", end="") ptxt = cs50.get_string() n = len(ptxt) print("ciphertext: ", end="") # Iterate over each char for c in ptxt: # If the current char is in lowercase, rotate by k positions. Alpha is used to set a alphabetical order starting from zero if str.islower(c): alpha = ord(c) - 97 print(chr((alpha + k) % 26 + 97), end="") # If the current char is in uppercase, find its numeric position on alphabet, rotate by k positions and print it. Modulo is used so Z becomes A. if str.isupper(c): print(chr((ord(c) - 65 + k ) % 26 + 65), end="") # If the i'th char is not a letter print it whithout unchanged. if not str.isalpha(c): print(c, end="") # Print new line (layout) print()
true
04fb3910612a6d0bd6167dcfa7a4e7d22333522d
Wolverinepb007/Python_Assignments
/Python/prime.py
348
4.125
4
num=int(input("Enter a number: ")) i=0 n=2 while(n<num): if(num%n==0): i+=1 break n+=1 if(i==0 and num !=1 and num !=0): print(num," is a prime number.") elif(num ==1 or num ==0): print(num," is neither prime nor a composite number.") else: print(num," is not a prime number.")
true
f604a334cda7df8ebcc58e105deeb911dc62a7f8
PrashantThirumal/Python
/Basics/RandomGenEclipse.py
371
4.125
4
''' Created on May 30, 2019 @author: Prashant ''' import random #Randomly generate numbers 0 to 50 com = random.randint(0,50) user = 51 while(user != com): user = int(input("Enter your guess")) if(user > com): print("My number is smaller") elif(com > user): print("My number is bigger") print("That is my number!!")
true
5158be40ab24bb386d426c859f030ee40ab92176
happy5205205/PythonProjects
/History/day01/ProcseeControl.py
1,192
4.1875
4
#if的条件可以是数字或字符串或则布尔值True和False(布尔表达式) #如果是数字,则只要不等于0,就为True #如果是字符串,则只要不是空串,就为True #if语句 # var1 = 100 #ture输出 # if var1: # print("1-Got a ture expression value") # print(var1) # var2 = 0 #False不输出 # if var2: # print("2-Got a ture expression value") # print(var2) # print("Good bye") #if else Pratice # var = 100 # if var == 200: # print("1-Got a Ture expression value") # print(var) # elif var == 150: # print("2-Got a True expression value") # elif var == 100: # print("3-Got a True exprssion value") # else: # print("4-Got a false expression value") # print(var) # print("GoodBye") #嵌套if else var = 250.333 # if var < 200: # print("Expression value is less than 200") # if var == 150: # print("Which is 150") # elif var == 100: # print("which is 100") # elif var ==50: # print("which is 50") # elif var > 300: # print("Expression value is more than 200") # else: # print("Could not find true expression") # print("GoodBye")
false
98d5f200a0168bb4dda7ff62f14e1e4e73c016c7
golbeckm/Programming
/Python/the self-taught programmer/Chapter 14 More Object Oriented Programming/chapter_14_challenge_1.py
369
4.15625
4
# Add a square_list class variable to a class called # Square so that every time you create a new Square # object, the new object gets added to the list. class Square(): square_list = [] def __init__(self, s): self.side = s self.square_list.append((self.side)) s1 = Square(5) s2 = Square(10) s3 = Square(15) print(Square.square_list)
true
35d1c727021ecfc6c40dac30832cce0df861fb6b
golbeckm/Programming
/Python/the self-taught programmer/Chapter 3 Intro to Programming/chapter_3_challenge_5.py
323
4.25
4
# create a program that takes two varibales, # divides them, and prints the quotient. print("Give me two numbers to divide by.") variable_1 = int(input("Enter the first number: ")) variable_2 = int(input("Enter the second number: ")) print("The quotient of ", variable_1,"/", variable_2, "is", variable_1 // variable_2)
true
1f694b39cee317c3c32ea34a773a98b326d87677
golbeckm/Programming
/Python/the self-taught programmer/Chapter 3 Intro to Programming/chapter_3_challenge_2.py
303
4.28125
4
# write a program that prints a message if a variable is less than 10, # and different message if the variable is less than or equal to 10. variable = int(input("Enter a number: ")) if variable < 10: print(variable, "is less than 10") elif variable > 10: print(variable, "is greater than 10")
true
ce4905f64e2981632c19df7e2e5b0c64d0dfabaf
marianpg12/pcep-tests
/block3_flow_control/test2.py
411
4.15625
4
# What is the output of the following code snippet when the : milk_left = "None" if milk_left: print("Groceries trip pending!") else: print("Let's enjoy a bowl of cereals") # Answer: Groceries trip pending! # Explanation: If the value of a variable is non-zero or non-empty, # bool(non_empty_variable) will be be True.Hence the if clause is passed # and 'Groceries trip pending' is printed to the console
true
cc580e2311da3d5358d3710f044ba6b63df035f6
marianpg12/pcep-tests
/block4_data_collections/test1.py
298
4.15625
4
# What do you expect when the following code snippet is run: weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday") weekdays.append("Friday") print(weekdays) # Answer: AttributeError: 'tuple' object has no attribute 'append' # Explanation: Tuples are immutable and can't be amended once created
true
d34a70c3d5ba30d5fe02f360e8946b9a3a1dbdb4
marianpg12/pcep-tests
/block5_functions/test7.py
442
4.34375
4
# What is the output of the following code def fun(a = 3, b = 2): return b ** a print(fun(2)) # Answer: 4 # Explanation: The function expects two values, but if not provided, # they can be defaulted to 3 and 2 respectively for a and b. # Note that he function calculates and returns b to the power of a. # When you call the function with one value, we are setting a using the positional argument # while the value b is defaulted to 2.
true
bb45e2ba337d201916858aebe6f6433cce8d14d9
Pandaradox/LC101-WeeklyAssigns
/python/ch9weekly.py
1,333
4.15625
4
# ##################################################Chapter 9 Weekly Assignment # Function to scan a string for 'e' and return a percentage of the string that's 'e' import string def analyze_text(text): es = 0 count = 0 for char in text: if char in string.ascii_letters: count += 1 if (char.lower() == 'e'): es += 1 return("The text contains {length} alphabetic characters, of which {totalE} ({percentE}%) are 'e'.".format(length=count, totalE=es, percentE=((es / count) * 100))) def main(): text1 = "Eeeee" text2 = "Blueberries are tasteee!" text3 = "Wright's book, Gadsby, contains a total of 0 of that most common symbol ;)" # Tests 4-6: solutions using str.format should pass these text4 = "Eeeee" text5 = "Blueberries are tasteee!" text6 = "Wright's book, Gadsby, contains a total of 0 of that most common symbol ;)" print(analyze_text(text1)) print(analyze_text(text2)) print(analyze_text(text3)) # answer1 = "The text contains 5 alphabetic characters, of which 5 (100.0%) are 'e'." # answer2 = "The text contains 21 alphabetic characters, of which 7 (33.3333333333%) are 'e'." # answer3 = "The text contains 55 alphabetic characters, of which 0 (0.0%) are 'e'." if __name__ == "__main__": main()
true
13fa5532359fcf0ea526297328cb5cba1e1fe292
katrina376/or2016
/hw_3/Fibo.py
256
4.125
4
n = int(input("Please input the term n for the Fibonacci sequence: ")) print "The Fibonacci sequence = " def fibo(n) : if (n <= 2) : return 1 else : return fibo(n-1) + fibo(n-2) s = "" for i in range(1, n+1) : s += str(fibo(i)) + " " print s
false
2cb987fd5d1852847c30f7cd000ed8a1f61e0a8a
akashbhanu009/Functions
/Lambda_Function.py
667
4.34375
4
'''->Sometimes we can declare a function without any name,such type of nameless functions are called anonymous functions or lambda functions. The main purpose of anonymous function is just for instant use(i.e for one time usage)''' #normally we can use 'def' keyword def square(a): print(a*a) square(10) #now using lambda-keyword #ex:- square a=lambda n:n*n print(a(2)) #ex:- addition a=lambda x,y:x+y print(a(10,20)) #ex:- greatest number a=lambda x,y:x if x>y else y print(a(10,20)) #ex:- even or odd using 'filter' a=[1,2,3,4,5,6,7,8,9,10,11] b=list(filter(lambda a:a%2==0,a)) print(b) c=list(filter(lambda a:a%2!=0,a)) print(c)
true
0fe91c1d26853ba69130e2925e6935d5eee882f6
Adenife/Python_first-days
/Game.py
1,571
4.125
4
import random my_dict = { "Base-2 number system" : "binary", "Number system that uses the characters 0-F" : "hexidecimal", "7-bit text encoding standard" : "ascii", "16-bit text encoding standard" : "unicode", "A number that is bigger than the maximum number that can be stored" : "overflow", "8 bits" : "byte", "1024 bytes" : "kilobyte", "Picture Element. The smallest component of a bitmapped image" : "pixel", "A continuously changing wave, such as natural sound" : "analogue", "the number of times per second that a wave is measured" : "sample rate", "A bunary representation of a program" : "machine code" } print("Computing Reevision quize") print("=================") playing = True while playing == True: score = 0 num = int(input("\nHow many questions would you like: ")) for i in range(num): question = random.choice(list(my_dict.keys())) #answer = my_dict.values() answer = my_dict[question] print("\nQuestion " + str(i+1)) print(question + "?") # print(answer) guess = input(">") if guess.lower() == answer.lower(): print("Correct!") score +=1 else: print("Nope!") print("\nYour final score is: " +str(score)) again = input("Enter any key to play again, or 'q' to quit: ") if again.lower() == 'q': playing = False
true
051364e41d439c7402c6e2a7e57a5583c2bfad26
djtongol/python
/OOP/OOP.py
2,718
4.15625
4
#Basic OOP class Beach: #location= 'Cape Cod' def __init__(self, location, water, temperature): self.location= location #instance variable self.water= water self.temperature= temperature self.heat = 'hot' if temperature >80 else 'cool' self.parts= ['water' 'sand'] def add_parts(self, parts): self.parts.append(parts) def main(): update = 'Update on ' Boracay = Beach('Boracay', 'clear', 90) Boracay.add_parts('Shells') Baler= Beach('Baler', 'dark blue', 100) Baler.add_parts('rocks') Bohol= Beach('Bohol', 'crystal', 70) Baler.add_parts('tarsiers') hot_not_rocky= [] for beach in [Boracay, Baler, Bohol]: if beach.heat == 'hot' and 'rock' not in beach.parts: hot_not_rocky.append(Beach) return hot_not_rocky # if __name__ == '__main__': # beaches=main() # print([beach.location for beach in beaches]) #print(update, Boracay.location, Boracay.water, Boracay.temperature, Boracay.heat, ' '.join(Boracay.parts) + '\n') #print(update, Baler.location, Baler.water, Baler.temperature, Baler.heat, ' '.join(Baler.parts) + '\n') #print(update, Bohol.location, Bohol.water, Bohol.temperature, Bohol.heat, ' '.join(Bohol.parts)) #Inheritance and Polymorphism in Classes class Dog: def __init__(self, name, age, friendliness): self.name= name self.age= age self.friendliness= friendliness def likes_walks(self): return True def bark(self): return "Woof!" class Samoyed(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def bark(self): return "arf arf" class Poodle(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def bark(self): return "Aroooo!" def shedding_amount(self): return 0 class Bulldog(Dog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) def fetch_ability(self): if self.age < 2: return 8 elif self.age <10: return 10 else: return 7 class Budle (Poodle, Bulldog): def __init__(self, name, age, friendliness): super().__init__(name, age, friendliness) # sammy = Samoyed('Sammy', 2, 10) # print(sammy.name, sammy.age, sammy.friendliness) # print(sammy.likes_walks()) barker= Budle('barker', 10, 10) maxie =Dog('maxie', 12, 5) teddy = Samoyed('teddy', 4, 10) print(barker.bark(), maxie.bark(), teddy.bark())
true
6c010e3b0462d6ea40a5966839571ed6ab0a0355
asmitapoudel/Python_Basics-2
/qs_7.py
672
4.125
4
""" Create a list of tuples of first name, last name, and age for your friends and colleagues. If you don't know the age, put in None. Calculate the average age, skipping over any None values. Print out each name, followed by old or young if they are above or below the average age. """ lioftuples=[('Shruti','Poudel',25),('Sam','lama',22),('sr','khan',20)] l=[] total=0 for i in range(len(lioftuples)): li=lioftuples[i][2] l.append(li) print(l) for ele in range(0, len(l)): total = total + l[ele] avg=total/len(l) print(avg) for i in lioftuples: if i[2]>avg: print(i[0]+' '+i[1]+' is older') else: print(i[0]+' '+i[1]+' is younger')
true
66470c73af52ffecfa327eddf1cb32c790854aa6
mctraore/Data-Structures-and-Algorithms
/Linked Lists/linked_list.py
1,850
4.125
4
class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def get_position(self, position): current = self.head for i in range(position-1): current = current.next if not current: return None return current """Get an element from a particular position. Assume the first position is "1". Return "None" if position is not in the list.""" def insert(self, new_element, position): if position ==1: new_element.next = self.head self.head = new_element else: current = self.head for i in range(position-2): current = current.next if not current: return None temp = current.next new_element.next = temp current.next = new_element """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" pass def delete(self, value): current = self.head if current.value == value: self.head = current.next else: while current.next: if current.next.val == value: current.next = current.next.next """Delete the first node with a given value.""" pass
true
97bbcb83752b42fdb44fe31872d1e8b2e18edeec
My-Sun-Shine/Python
/Python3/Learn/Learn30.py
713
4.125
4
# 错误处理机制 try...except...else...finally... # 所有的错误类型都继承BaseException import logging try: print("try...") r = 10/int("2") print("result:", r) except ValueError as e: print("ValueError", e) except ZeroDivisionError as e: print("ZeroDivisionError", e) else: print("NO error") # 没有错误时执行 finally: print("finally....") # 最后执行 # try..except 多层捕捉错误 def foo(s): return 10/int(s) def bar(s): return foo(s)*2 def main(): try: bar("0") except Exception as e: print("Error:", e) logging.exception(e) # 把错误记录到日志文件 finally: print("finally...") main()
false
77373257b4daaa97c0703f6f92d9f7744bc5c711
drakezhu/algorithms
/random_selection/randSelect.py
1,900
4.15625
4
########################################################################## # # Tufts University, Comp 160 randSelect coding assignment # randSelect.py # randomized selection # # includes functions provided and function students need to implement # ########################################################################## # TODO: implement this function # ray is a list of ints # index is an int import random def randSelect(ray, index): if index > len(ray) or index == len(ray): raise ValueError("Rank value out of length!") print ("Looking for value with rank " + str(index) + " in the array:") print (ray) # generate random number randNum = ray[random.randint(0,len(ray)-1)] # doing partition sub_1, sub_2, randRank,identical_num = partition(ray, randNum) # three situation doing recursion if (randRank == index or randRank < index ) and (randRank + identical_num -1 == index or randRank + identical_num -1 > index): print ("Selected " + str(randNum) + " as the pivot; its rank is " + str(randRank) + " Thus, we recurse on nothing. We are done") return randNum if randRank < index: print ("Selected " + str(randNum) + " as the pivot; its rank is " + str(randRank) + " Thus, we recurse on right") return randSelect(sub_2, index-randRank) if randRank > index: return randSelect(sub_1, index) print ("Selected " + str(randNum) + " as the pivot; its rank is " + str(randRank) + " Thus, we recurse on left") return 0 def partition(ray, num): sub_1 = [] sub_2 = [] counter = 0 identical_num = 0 for i in ray: # number less than random generated number will goes to sub array 1 if i < num: sub_1.append(i) counter += 1 # otherwise go to sub array 2 if i > num or i == num: sub_2.append(i) # record the amount of identical generated random number if i == num: identical_num += 1 return sub_1, sub_2, counter, identical_num
true
0e4b3a8cc3b6cb693b030e663a1f15611669233c
dineshbalachandran/mypython
/src/gaylelaakmann/1_6.py
592
4.21875
4
def compress(txt): if len(txt) < 3: return txt out = [] currchar = txt[0] count = 0 for char in txt: if char != currchar: out.append(currchar) out.append(str(count)) currchar = char count = 1 else: count += 1 out.append(currchar) out.append(str(count)) compresstxt = ''.join(out) return compresstxt if len(compresstxt) < len(txt) else txt if __name__ == '__main__': txt = input("String to compress: ") print("Compressed string: {}".format(compress(txt)))
true
919e93118fc21b5f45a947257bee54a667752573
dakshtrehan/Python-practice
/Strings/Alternate_capitalize.py
297
4.1875
4
#Write a program that reads a string and print a string that capitalizes every other letter in the string #e.g. passion becomes pAsSiOn x=input("Enter the string: ") str1= "" for i in range(0, len(x)): if i%2==0: str1+=x[i] else: str1+=x[i].upper() print(str1)
true
1e438dd75672e236927476f9e7cfc964aba9b7f3
Minyi-Zhang/intro-to-python
/classwork/week-2/groceries.py
1,567
4.375
4
#!/usr/bin/env python3 # Built-in data type: Sequence Types # list (mutable) # groceries = list( # "apples", # "oranges", # ) groceries = [ "apples", "oranges", "pears", "kiwis", "oranges", "pears", "pears", ] # print(groceries[3:6]) # example: groceries.count(x) # Return the number of times x appears in the list (groceries). # print(groceries.count("pears")) # example: groceries.pop([index]) # Remove the item at the given position in the list, and return it. # If no index is specified, a.pop() removes and returns the last item in the list. # The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. # print(len(groceries)) # before: 6 # last_item = groceries.pop() # print(last_item) # print(len(groceries)) # after: 5 # item4 = groceries.pop(3) # print(groceries) # --- # example: list.remove # Remove the first item from the list whose value is equal to x. # groceries.remove(x) # groceries.remove("oranges") # print(groceries) # --- # list.insert(index, item) # insert at index 0 # groceries.insert(0, "grapes") # insert at end # groceries.insert(len(groceries), "mangos") # print(groceries) # --- # print(groceries) # item = input("What item do you want to add to groceries? ") # groceries.append(item) # print(len(groceries)) # print(groceries) # --- # list.sort() # groceries.sort() # print(groceries) # # --- # # looping # # print(type(groceries)) # for item in groceries: # print(item)
true
5f3c7c4bfd558d02e3788e6e1434325c22568304
atm1992/nowcoder_offer_in_Python27
/p7_recursion_and_loop/a1_Fibonacci.py
1,740
4.125
4
# -*- coding:utf-8 -*- """ 斐波那契数列。 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39 f(0)=0 f(1)=1 f(2)=1 f(3)=2 f(4)=3 f(5)=5 """ class Solution: def Fibonacci_1(self, n): """方法一:递归实现。时间复杂度为O(2^n)""" if n == 0: return 0 if n == 1: return 1 return self.Fibonacci_1(n - 1) + self.Fibonacci_1(n - 2) def Fibonacci_2(self, n): """方法二:使用for循环来代替递归。时间复杂度为O(n)""" if n == 0: return 0 if n == 1: return 1 # a保存倒数第二个子状态的数据,b保存倒数第一个子状态的数据,ret保存当前状态的数据 a, b = 0, 1 ret = 0 for _ in range(2, n + 1): ret = a + b a, b = b, ret return ret def Fibonacci_3(self, n): """方法三:使用一个列表来保存从0到n的斐波那契数。时间复杂度为O(n),空间复杂度也为O(n) 适用于需要多次获取斐波那契数的情况 """ # 初始列表保存着n为0、1时的结果 res = [0, 1] while len(res) <= n: res.append(res[-1] + res[-2]) return res[n] def Fibonacci_4(self, n): """使用一个列表来保存前两个斐波那契数。时间复杂度为O(n)""" # 初始列表保存着n为0、1时的结果 res = [0, 1] for i in range(2, n + 1): res[i % 2] = res[0] + res[1] return res[n % 2] if __name__ == '__main__': s = Solution() print(s.Fibonacci_4(100))
false
c5b17caf6c10b1879210cc1ecaba2b5c94c9e98a
satrini/python-study
/exercises/exercise-26.py
286
4.15625
4
# Calc leap year from datetime import date year = int(input("Choose a year (0 for actual year):")) if year == 0: year = date.today().year if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(f"{year} - Leap year: YES!") else: print(f"{year} - Leap year: NO!")
false
4d6c34943ae50b8df95ab0371180ea69be434981
satrini/python-study
/exercises/exercise-37.py
718
4.40625
4
# BMI weigh = float(input("How much do you weigh? KG")) height = float(input("How tall are you? (M)")) # normal, obesity morbid, under normal weight, over weigh bmi = weigh / (height ** 2) if bmi < 18.5: print(f"Your BMI is {bmi}") print("You are in the {} weight range!") elif bmi >= 18.5 and bmi < 25: print(f"Your BMI is {bmi}") print("You are in the normal weight range!") elif bmi >= 25 and bmi < 30: print(f"Your BMI is {bmi}") print("You are in the under normal weight range!") elif bmi >= 30 and bmi < 40: print(f"Your BMI is {bmi}") print("You are in the obesity weight range!") else: print(f"Your BMI is {bmi}") print("You are in the obesity morbid weight range!")
false
298f2bca4de971310d4573716715e0180f12d4b7
satrini/python-study
/exercises/exercise-55.py
201
4.1875
4
num = int(input("Calculate factorial: !")) factorial = 1 for i in range(num, 0, -1): print(f"{i}", end = "") print(" x " if i > 1 else " = ", end = "") factorial *= i print(f"{factorial}")
false
9a40697a33b75f341c3c4aeb502f4bb3051618db
RdotSilva/Harvard-CS50
/PSET6/caesar/caesar.py
1,022
4.125
4
from sys import argv from cs50 import get_string def main(): # Check command line arguments to make sure they are valid. if len(argv) == 2: k = int(argv[1]) if k > 0: print(k) else: print("NO") else: print("Invalid Input") exit(1) # Prompt user for plain text. plain_text = get_plain("plaintext: ") print("ciphertext: ", end="") # Loop through every letter in plain text. for letter in plain_text: if (letter.isalpha()): if (letter.isupper()): new_letter = (ord(letter) - ord('A') + k) % 26 print(chr(new_letter + ord('A')), end="") elif (letter.islower()): new_letter = (ord(letter) - ord('a') + k) % 26 print(chr(new_letter + ord('a')), end="") else: print(letter, end="") print() # Get plain text string. def get_plain(prompt): return get_string(prompt) if __name__ == "__main__": main()
true
946c278ccc0a1e0a26c8c87b1b10f3dd201701ec
rohanaurora/daily-coding-challenges
/Problems/target_array.py
1,098
4.34375
4
# Create Target Array in the Given Order # Given two arrays of integers nums and index. Your task is to create target array under the following rules: # # Initially target array is empty. # From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. # Repeat the previous step until there are no elements to read in nums and index. # Return the target array. # # It is guaranteed that the insertion operations will be valid. # Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] # Output: [0,4,1,3,2] # # Source - https://leetcode.com/problems/create-target-array-in-the-given-order/ class Solution: def createTargetArray(self, nums, index): output = [] for x, y in enumerate(nums): output.insert(index[x], y) return output # Alternative solution using zip() # class Solution: # def createTargetArray(self, nums, index): # output = [] # for i, j in zip(nums, index): # output.insert(j, i) # return output s = Solution().createTargetArray([0,1,2,3,4], [0,1,2,2,1]) print(s)
true
acbc16d28d1eecdf125d26a44572ee035857fb15
lungen/Project_Euler
/p30-digit-fifth-powers-0101.py
1,381
4.1875
4
<<<<<<< HEAD """ Digit fifth powers Problem 30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ ======= def digitPowersDividor(x=1634): """ Digit fifth powers Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ n = x m = str(n) p = 5 while len(m) > 0: n = n - int(m[:1]) ** p m = m[1:] if n == 0: print("ok: ", n, x) return x else: # print("nok: ", n) return 0 suma = 0 for i in range(999999, 9, -1): suma = suma + int(digitPowersDividor(i)) print("fin: ", suma) >>>>>>> f3c10f58387a00c81a288529fb1af27a8d925b0e
true
323921991a78e974ed30a01d14b01ec1b2f5ffb0
lungen/Project_Euler
/_training_/codes/001.001_recursive_memoization_fibonacci.py
885
4.34375
4
""" Published on 31 Aug 2016 Let’s explore recursion by writing a function to generate the terms of the Fibonacci sequence. We will use a technique called “memoization” to make the function fast. We’ll first implement our own caching, but then we will use Python’s builtin memoization tool: the lru_cache decorator. To learn Python, you can watch our playlist from the beginning: https://www.youtube.com/watch?v=bY6m6... """ fibonacci_cache = {} def fibonacci(n): # if value stored in cache, return it if n in fibonacci_cache: return fibonacci_cache[n] # compute the values if n == 1: value = 1 elif n == 2: value = 2 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) #cache the value and return fibonacci_cache[n] = value return value for i in range(1, 10000): print(i, ":", fibonacci(i))
true
749c0846784ae81b34c06c09115e6102b42d63d1
mikaelbeat/The_Python_Mega_Course
/The_Python_Mega_Course/Basics/Check_date_type.py
570
4.15625
4
data1 = 5 data2 = "Text" data3 = 3 print("\n***** Data is int *****\n") print(type(data1)) print("\n***** Data is str *****\n") print(type(data2)) print("\n***** Check data type *****\n") if isinstance(data3, str): print("Data is string") elif isinstance(data3, int): print("Data is interger") print("\n***** Check data type another approach *****\n") if type(data3) == int: print("Data is integer") elif type(data3) == str: print("Data is string") else: print("Data type is other than string or integer")
true
63b5273dd2d85b4b412522e61266430592ba4b30
RajeshNutalapati/PyCodes
/OOPs/Inheritence/super() or function overriding/super with single level inheritance_python3.py
1,115
4.25
4
''' Python | super() function with multilevel inheritance super() function in Python: Python super function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'. To understand Python super function we must know about the inheritance. In Python inheritance, the subclasses are inherited from the superclass. Python Super function provides us the flexibility to do single level or multilevel inheritances and makes our work easier and comfortable. Keep one thing in mind that while referring the superclass from subclass, there is no need of writing the name of superclass explicitly. Here is one example of how to call the super function in Python3: ''' # parent class also sometime called the super class class Parentclass(): def __init__(self): pass # derived or subclass # initialize the parent or base class within the subclass class subclass(Parentclass): def __init__(self): # calling super() function to make process easier super()
true
48626c838ebc03ddbf36ea98d78c7186359a332e
RajeshNutalapati/PyCodes
/OOPs/Inheritence/super() or function overriding/super with multilevel inheritence_python3.py
1,727
4.40625
4
''' Python super() function with multilevel inheritance. As we have studied that the Python super() function allows us to refer the superclass implicitly. But in multi-level inheritances, the question arises that there are so many classes so which class did the super() function will refer? Well, the super() function has a property that it always refers the immediate superclass. Also, super() function is not only referring the __init__() but it can also call the other functions of the superclass when it needs. Super has following properties The method being called upon by super() must exist Both the caller and callee functions need to have a matching argument signature Every occurrence of the method must include super() after you use it Here is the example of explaining the multiple inheritances. ''' # Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)
true
a22d680571411459964d7db525fe155ab2fe09b6
RajeshNutalapati/PyCodes
/DataAlgorithms/LinkedLists/single linked list.py
701
4.25
4
# make node class #creating singly linked list class Node: def __init__(self,data): self.data = data self.next = None #initializing next to null class LinkedList: def __init__(self): self.head = None #This will print the contents of the linked list #starting from head def printlist(self): temp = self.head print(self.head) while(temp): print (temp.data) temp= temp.next if __name__ == "__main__": #start with empty list llist= LinkedList() print (llist) llist.head=Node(1) second = Node(2) third=Node(3) llist.head.next=second second.next=third llist.printlist()
true
9ea49d349b93a71d8db360525968a065e08d71fc
johanna-w/hello-world
/plane.py
1,296
4.3125
4
""" Programmet skriver, och tar höjd, hastighet och temperatur i m, km/h och Celcius som input från användaren. Värdena användaren skriver in används för att skapa mått som är konverterade till feet, mph och Farenheit. """ höjd = input("Höjd över havet (meter): ") # Användaren matar in höjd hastighet = input("Hastighet (km/h): ") # Användaren matar in hastighet temperatur = input("Temperatur utanför flygplanet (Celcius): ") # Användaren matar in temperatur konverterad_höjd = str(float(höjd) * 3.28084) konverterad_hastighet = str(float(hastighet) * 0.62137) konverterad_temperatur = str(float(temperatur) * (9 / 5 + 32)) # Konverterar värden som matats in till feet, MPH och Farenheit. # Eftersom höjd, hastighet och temperatur är av typen int måste de först konverteras till sträng. output1 = ("Höjd över havet (feet):" + " " + str(konverterad_höjd)) output2 = ("Hastighet (mph):" + " " + str(konverterad_hastighet)) output3 = ("Temperatur utanför flygplanet (Farenheit):" + " " + str(konverterad_temperatur)) # Sätter ihop "Höjd", "Hastighet" och "Temperatur" med konverterade värden som visas för användaren genom print nedan print(output1) print(output2) print(output3) # Ger output till användaren i konverterad form. Utan print ges ingen output.
false
534d5357b9157fd8f63b8576226e003b4f132806
lare-cay/CSCI-12700
/10-16-19.py
1,217
4.25
4
#Name: Clare Lee #Email: Clare.Lee94@myhunter.cuny.edu #Date: October 16, 2019 #This program modifies a map according to given amount of blue crating a new image import numpy as np import matplotlib.pyplot as plt blue = input("How blue is the ocean: ") file_name = input("What is the output file: ") #Read in the data to an array, called elevations: elevations = np.loadtxt('elevationsNYC.txt') #Take the shape (dimensions) of the elevations # and add another dimension to hold the 3 color channels: mapShape = elevations.shape + (3,) #Create a blank image that's all zeros: blueMap = np.zeros(mapShape) for row in range(mapShape[0]): for col in range(mapShape[1]): if elevations[row,col] <= 0: blueMap[row,col,2] = blue #Set the blue channel to user specified elif elevations[row,col] % 10 == 0: blueMap[row,col,0] = 0.0 blueMap[row,col,1] = 0.0 blueMap[row,col,2] = 0.0 else: blueMap[row,col,0] = 1.0 blueMap[row,col,1] = 1.0 blueMap[row,col,2] = 1.0 #Save the image: plt.imsave(file_name, blueMap) print("Thank you for using my program!") print("Your map is stored", file_name)
true
151dcc61aadad894cfffbd9f28deb772f130d578
clush7113/code-change-test
/linearSearch.py
357
4.1875
4
testString = "" searchChar = "" newChar= "" while testString == "" and len(searchChar) != 1 and newChar=="": testString = input("Please enter some text to search : ") searchChar = input("Enter a character to search for : ") newChar = input("What would you like to replace the character with? : ") print(testString.replace(searchChar,newChar))
true
6fe4268d4b54cb1f6b0281e078402fb4115d07ad
SurajMondem/PythonProgramming
/Day_4/DucksAndGoats.py
735
4.125
4
# There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. # Write a Python program to find number of goats and ducks in the farm # You can use Cramer’s rule to solve the following 2 × 2 system of linear equation: # ax + by = e # cx + dy = f # # x = (ed – bf) / (ad – bc). # y = (af – ec) / (ad – bc). numOfEye = 62 numOfFoot = 90 goatLegs = 4 goatEyes = 2 duckLegs = 2 duckEyes = 2 numOfGoats = ((numOfEye * duckLegs) - (duckEyes * numOfFoot)) / ((goatEyes * duckLegs) - (duckEyes * goatLegs)) numOfDucks = ((goatEyes * numOfFoot) - (numOfEye * goatLegs)) / ((goatEyes * duckLegs) - (duckEyes * goatLegs)) print("THE NUMBER OF GOATS: ", numOfGoats) print("THE NUMBER OF DUCKS: ", numOfDucks)
false
cddc867538535903d69e4795aaf554bb3260c602
puntara/Python-
/Module3/m1_m2_concat_dict.py
445
4.4375
4
#1) Write a Python script to concatenate following dictionaries to create a new one. dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} result1={**dic1, **dic2, **dic3} print(result1) #2) Write a Python script to generate and print a dictionary that contains a number # (between 1 and n) in the form (x, x*x). number =int(input('enter a number: ')) my_dict =dict() for val in range(1,number+1): my_dict[val]=val*val print(my_dict)
true
465bae6eadd928fbd7fd9cf3c80fc8de3dbbb0b7
UjjwalSaini07/Tkinter_Course_1
/Tkinter_13.py
983
4.46875
4
# https://www.codewithharry.com/videos/python-gui-tkinter-hindi-19 # todo : Sliders In Tkinter Using Scale() from tkinter import * import tkinter.messagebox as tmsg root = Tk() root.geometry("455x233") root.title("Slider tutorial") # get(): This method returns the current value of the scale. # set(value): It sets the scale's value. For example, if we give set(30) the initial scale value will show 30 (the scale will starts from 30). def getdollar(): print(f"We have credited {myslider2.get()} dollars to your bank account") tmsg.showinfo("Amount Credited!", f"We have credited {myslider2.get()} dollars to your bank account") # myslider = Scale(root, from_=0, to=100) # myslider.pack() Label(root, text="How many dollars do you want?").pack() myslider2 = Scale(root, from_=0, to=100, orient=HORIZONTAL, tickinterval=50) # myslider2.set(34) myslider2.pack() Button(root, text="Get dollars!", pady=10, command=getdollar).pack() root.mainloop()
true
e23c1a608d0172466d94f7619215a3df61b0bd84
RandyKline/Self_Paced-Online
/students/ian_letourneau/Lesson03/slicing_lab.py
2,973
4.25
4
## Ian Letourneau ## 4/26/2018 ## A script with various sequencing functions def exchange_first_last(seq): """A function to exchange the first and last entries in a sequence""" middle = list(seq) middle[0] = seq[-1] middle[-1] = seq[0] if type(seq) is str: return "".join(middle) elif type(seq) is tuple: return tuple(middle) else: return middle def remove_every_other(seq): """A function to remove every other entry in a sequence""" middle = [] for index in range(len(seq)): if not index%2 or index == 0: middle.append(seq[index]) if type(seq) is str: return "".join(middle) elif type(seq) is tuple: return tuple(middle) else: return middle def remove_four(seq): """A function that removes the first 4 and last four entries in a sequence, and then removes every other entry in the remaining sequence""" middle = list(seq) del middle[0:4] del middle[-4:len(seq)] if type(seq) is str: return "".join(remove_every_other(middle)) elif type(seq) is tuple: return tuple(remove_every_other(middle)) else: return remove_every_other(middle) def reverse(seq): """A function that reverses a seq""" middle = list(seq) count = -1 for index in range(len(seq)): middle[index] = seq[count] count -= 1 if type(seq) is str: return "".join(middle) elif type(seq) is tuple: return tuple(middle) else: return middle def thirds(seq): """A function that splits a sequence into thirds, then returns a new sequence using the last, first, and middle thirds""" middle = list(seq) one = middle[0:int(len(seq)/3)] two = middle[int(len(seq)/3):int(len(seq)/3*2)] three = middle[int(len(seq)/3*2):len(seq)] a_new_sequence = three + one + two if type(seq) is str: return "".join(a_new_sequence) elif type(seq) is tuple: return tuple(a_new_sequence) else: return a_new_sequence if __name__ == '__main__': """A testing block to ensure all functions are operating as expected""" a_string = "this is a string" a_tuple = (2, 54, 13, 15, 22, 63, 75, 20, 8, 12, 5, 32) s_third = "123456789" t_third = (1, 2, 3, 4, 5, 6, 7, 8, 9) assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == (32, 54, 13, 15, 22, 63, 75, 20, 8, 12, 5, 2) assert remove_every_other(a_string) == "ti sasrn" assert remove_every_other(a_tuple) == (2, 13, 22, 75, 8, 5) assert remove_four(a_string) == " sas" assert remove_four(a_tuple) == (22, 75) assert reverse(a_string) == "gnirts a si siht" assert reverse(a_tuple) == (32, 5, 12, 8, 20, 75, 63, 22, 15, 13, 54, 2) assert thirds(s_third) == "789123456" assert thirds(t_third) == (7, 8, 9, 1, 2, 3, 4, 5, 6) print("All tests passed my fellow coders!")
true
14537d1a3dfbd4423de9ae80124510d697435069
leelu62/PythonPractice
/BirthdayDictionary.py
336
4.53125
5
#store family and friend's birthdays in a dictionary #write a program that looks up the birthday of the person inputted by the user birthdays_dict = {"Amon":"10/03/2016","Christopher":"12/18/1983","Jenna":"6/2/1985"} person = input("Whose birthday would you like to look up? ") print(person + "'s birthday is",birthdays_dict[person])
true
f0a1e316b9c2c0f0d740326ab98c0a6040460f6b
leelu62/PythonPractice
/StringLists.py
374
4.5
4
# ask user to input a word, then tell user whether or not the word is a palindrome word = input("Please enter a word for palindrome testing: ") letters_list = [] for letter in word: letters_list.append(letter) reverse = letters_list[::-1] if letters_list == reverse: print("Your word is a palindrome!") else: print("Your word is not a palindrome. Try again.")
true
9b64132ab776ebaaee149d27ca892421a5d9c0b7
Abhinesh77/python_intern
/task4.py
393
4.1875
4
#list a=[1,2,3,4] for x in a: print(x,end=""); print("") a.append(5); for x in a: print(x,end=""); print("") a.remove(2); for x in a: print(x,end=""); print("") max=max(a); min=min(a); print("largest element is",max); print("smallest element is",min); #tuple b=(6,7,8,9,10); print(b[::-1]) c=("a","b","c","d"); d=list(c) print(d)
false