blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a7745492208033ac49f8d0285ff7c141eed19a70
gatherworkshops/programming
/_courses/tkinter2/assets/zip/pythonchallenges-solutions/eventsdemo.py
2,908
4.21875
4
import tkinter import random FRUIT_OPTIONS = ["Orange", "Apple", "Banana", "Pear", "Jalapeno"] window = tkinter.Tk() # prints "hello" in the developer console def say_hello(event): name = name_entry.get() if len(name) > 0: print("Hello, " + name + "!") else: print("Hello random stranger!") # adds a random fruit to the fruit list, # only allowing a maximum of 8 fruit def add_fruit(event): if fruit_list.size() >= 8: return random_index = random.randrange(0, len(FRUIT_OPTIONS)) random_fruit = FRUIT_OPTIONS[random_index] fruit_list.insert(tkinter.END, random_fruit) # deletes the selected fruit from the list, # if one is selected def delete_fruit(event): selected_fruit = fruit_list.curselection() fruit_list.delete(selected_fruit) # generates a smoothie recipe from the fruit # selection made by the user def generate_recipe(event): fruit_counter = {} # count the number of each type of fruit # using a dictionary chosen_fruit = fruit_list.get(0, tkinter.END) for fruit in chosen_fruit: if fruit in fruit_counter: fruit_counter[fruit] += 1 else : fruit_counter[fruit] = 1 # generate recipe text using the dictionary recipe_text = "Recipe:\n\n" for fruit_type in fruit_counter: recipe_line = str(fruit_counter[fruit_type]) + " x " + fruit_type + "\n" recipe_text += recipe_line # delete the old recipe if there was one recipe_display.delete("1.0", tkinter.END) # display the new recipe recipe_display.insert(tkinter.END, recipe_text) # name prompt name_prompt = tkinter.Label(window) name_prompt.config(text="What is your name?") name_prompt.grid(row=0, column=0) # name input name_entry = tkinter.Entry(window) name_entry.bind("<Return>", say_hello) name_entry.grid(row=1, column=0) # hello button hello_button = tkinter.Button(window) hello_button.config(text="Click Me!") hello_button.bind("<Button>", say_hello) hello_button.grid(row=2, column=0) # fruit list fruit_list = tkinter.Listbox(window) fruit_list.grid(row=0, column=1, columnspan=2, sticky="nesw") # add fruit button add_fruit_button = tkinter.Button(window) add_fruit_button.config(text="Add Random Fruit") add_fruit_button.bind("<Button>", add_fruit) add_fruit_button.grid(row=1, column=1, sticky="ew") # delete fruit button delete_fruit_button = tkinter.Button(window) delete_fruit_button.config(text="Delete Fruit") delete_fruit_button.bind("<Button>", delete_fruit) delete_fruit_button.grid(row=1, column=2, sticky="ew") # recipe button create_recipe_button = tkinter.Button(window) create_recipe_button.config(text="Generate Recipe") create_recipe_button.bind("<Button>", generate_recipe) create_recipe_button.grid(row=1, column=3) # recipe display recipe_display = tkinter.Text(window) recipe_display.grid(row=0, column=3) window.mainloop()
true
d6eb76e86a7c77ce7f875289e87562990ed2bd58
karramsos/CipherPython
/caesarCipher.py
1,799
4.46875
4
#!/usr/bin/env python3 # The Caesar Cipher # Note that first you will need to download the pyperclip.py module and # place this file in the same directory (that is, folder) as the caesarCipher.py file. # http://inventwithpython.com/hacking (BSD Licensed) # Sukhvinder Singh | karramsos@gmail.com | @karramsos import pyperclip # the string to be encrypted/decrypted message = 'This is my secret message.' # the encryption/decryption key key = 13 # tells the program to encrypt or decrypt mode = 'encrypt' # set to 'encrypt' or 'decrypt' # every possible symbol that can be encrypted LETTERS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' # stores the encrypted/decrypted form of the message translated = '' # capitalize the string in message #message = message.upper() # run the encryption/decryption code on each symbol in the message string for symbol in message: if symbol in LETTERS: # get the encrypted/decrypted number for this symbol num = LETTERS.find(symbol) # get the numbor of the symbol if mode == 'encrypt': num += key elif mode == 'decrypt': num -= key # handle the wrap-around if num is larger than the length of # LETTERS or less than 0 if num >= len(LETTERS): num -= len(LETTERS) elif num < 0: num += len(LETTERS) # add encrypted /decrypted number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/decrypting translated += symbol # print the encrypted/decrypted string to the screen print(translated) # copy the encrypted/decrypted string to the clipboard pyperclip.copy(translated)
true
2ea42b749ee8320df5a7eda34a07e3bc683101b3
40168316/PythonTicketApplication
/TicketApplication.py
2,257
4.375
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 # Create a function that calculates the cost of tickets def calculate_cost_of_tickets(num_tickets): # Add the service charge return (num_tickets * TICKET_PRICE) + SERVICE_CHARGE # Run this code continuously until we run out of tickets while tickets_remaining >= 1: # Output how many tickets are remaining using the tickets_remaining variable print("There are {} tickets remaining.".format(tickets_remaining)) # Gather the user's name and assign it to a new variable name = input("What is your name? ") # Prompt the user by name and ask how many tickets they would like num_tickets = input("How many tickets would you like, {}? ".format(name)) # ADD A TRY EXCEPT AS USER CAN ENTER A STRING HERE try: # Convert num_tickets to int num_tickets = int(num_tickets) # Raise a value error if the request is for more tickets than available if num_tickets > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as err: # Deal with error print("Issue with input. {}. Please try again!".format(err)) else: # Calculate the price (number of tickets multiplied by the price) and assign it to a variable amount_due = calculate_cost_of_tickets(num_tickets) # Output the price to the screen print("The total due is ${}".format(amount_due)) # Prompt user if they want to proceed. Y/N? should_proceed = input("Do you want to proceed? Y/N ") # If they want to proceed if should_proceed.lower() == "y": # print out to the screen "SOLD!" to confirm purchase # TODO: Gather credit card information and process it. print("SOLD!") # and then decrement the tickets remaining by the number of tickets purchased tickets_remaining -= num_tickets # Otherwise.... else: # Thank them by name print("Thank you anyways, {}!".format(name)) # Notify user that the tickets are sold out print("Sorry the tickets are all sold out!!! :(")
true
b49ea3e976180eecf26802fe0a6a198ce6e914fb
aabidshaikh86/Python
/Day3 B32.py
1,119
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: fullname = 'abid sheikh' print(fullname ) # In[ ]: # Req: correct the name format above by using the string method. # In[3]: print(fullname.title()) # Titlecase ---> first Letter of the word will be capital # In[ ]: # In[ ]: # Req: I want all the name to be in capital. # In[4]: print(fullname.upper()) ### Uppercase # In[ ]: # In[ ]: # Req: I want all the name to be in smallcase.. # In[5]: print(fullname.lower()) ### Lowercase # In[ ]: # In[ ]: *** Introduction to f strings in python.*** # In[ ]: # In[ ]: firstname = 'abid' lastname = 'sheikh' # In[ ]: # Req: get me a fullname. # In[ ]: General syntax of a f string f" custom string {placeholder1} {placeholder2} ......{nplaceholder}" ----> refercing point of the above variable created. # In[16]: x = f"{firstname} {lastname}" print(x) # In[17]: print(x.title()) # In[ ]: # In[ ]: req : i want to appreciate Abid for sending the practice file URL daily on time. # In[18]: print(f"keep up the goodwork, {x.title()}") # In[ ]:
true
626aea1dbd007cc33e1c79e6fa7a35848f313cc5
aabidshaikh86/Python
/Day7 B32.py
1,888
4.375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: list Continuation : # In[ ]: # In[1]: cars = ['benz','toyota','maruti','audi','bnw'] # In[ ]: ## Organising the list datatype # In[ ]: req : i want to organise the data in the alphabetical order !!! A to Z # In[ ]: Two different approcahes : 1. Temp approch -------> sorted 2. Permanent approch -------> sort # In[ ]: ## In the sorted (temp) approach we will be having the orginal order of the list!! ## In the sort (permanenet) approch we will not be having the original order back!! # In[8]: print(sorted(cars)) ## Temp approach # In[10]: print(cars) ## Original Approch # In[11]: cars.sort() ## permanent approach print(cars) # In[12]: print(cars) # In[ ]: *** Interview : what is the diff bet sorted and Sort?? *** # In[ ]: # In[ ]: get_ipython().set_next_input('Req: i want to print the list in the reverse order');get_ipython().run_line_magic('pinfo', 'order') # In[13]: print(cars) # In[14]: cars.reverse() ## Reverse Order print(cars) # In[ ]: ## How do you count the no of Elements in a list?? ## # In[15]: len(cars) ## Count method # In[ ]: ## introduction to slicing of the lists:: # In[17]: students = ['mohini','rachana','uma','swapna','vidhya','naveena'] # In[18]: print(students) # In[19]: type(students) # In[ ]: ## General syntex of slicing: -------FORMULA----------- var[startvalue:stopvalue:step count] ------> this is the formula. Note : Last value is always exclusive..!! # In[28]: print(students[0:1]) # In[29]: print(students[0:2]) # In[36]: print(students[4:6]) ## Last value is always exclusive and it will not be considered!! # In[38]: print(students[0:6:2]) ## Alternare name of the students..!! # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
true
cba0e3df6ccef062a345234650ddb61b3e54a96a
ShahzaibSE/Python-Babysteps
/marksheet_maker.py
1,136
4.25
4
marks = [] eng_marks = int(input("Enter marks for English:")) marks.append(eng_marks) # chemistry_marks = int(input("Enter marks for Chemistry:")) marks.append(chemistry_marks) # computer_marks = int(input("Enter marks for Computer:")) marks.append(computer_marks) # physics_marks = int(input("Enter marks for Physics:")) marks.append(physics_marks) # math_marks = int(input("Enter marks for Math:")) marks.append(math_marks) # # marks = [87, 86, 98, 99, 80] total = 0 for mark in marks: total += mark print(f"Total marks: {total}") # # Calculate percentage. percentage = total / len(marks) print(f"Percentage: {percentage}") # # Grading student. if percentage >= 80: print("Grade: A+") elif percentage >= 70 and percentage <80: print("Grade: A") elif percentage >= 60 and percentage <70: print("Grade: B") elif percentage >= 50 and percentage <60: print("Grade: C") elif percentage >= 40 and percentage <50: print("Grade: D") elif percentage >= 30 and percentage <40: print("Grade: E") else: print("Failed!") number = 12 print(type(number)) numbers_in_words = {1: "one"} print(type(numbers_in_words))
false
8d778b4cf8872d0c928d6a55933fcdfa86d0847d
Jasmine582/guess_number
/main.py
468
4.125
4
import random random_number = random.randrange(100) correct_guess = False while not correct_guess: user_input = input("Guess a number between 0 and 100:") try: number = int(user_input) if number == random_number: correct_guess = True elif number > random_number: print("You guessed too high") elif number < random_number: print("You guessed too low") except: print("Not a number!") print("You guessed the right number!")
true
686d03d60a541f88178f065fb15790c836507c19
ringotian/LP14_homework
/additional_homework/string_challenges.py
951
4.1875
4
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1]) # Вывести количество букв "а" в слове word = 'Архангельск' print(word.lower().count('а')) # Вывести количество гласных букв в слове word = 'Архангельск' print(len([x for x in word.lower() if x in 'ауоыэяюёе'])) # Вывести количество слов в предложении sentence = 'Мы приехали в гости' print(len(sentence.split())) # Вывести первую букву каждого слова на отдельной строке sentence = 'Мы приехали в гости' for i in sentence.split(): print(i[0]) # Вывести усреднённую длину слова. sentence = 'Мы приехали в гости' print(sum([len(x) for x in sentence.split()])/len(sentence.split()))
false
e00da369443f92f2e42d580635302cdf96ffa59b
Goku-kun/1000-ways-to-print-hello-world-in-python
/using-user-input.py
272
4.4375
4
# A program to print 'Hello, World!' by force typing it by the user himself def hello_world(): str = input("Enter 'Hello, World!' exactly: ") if str == 'Hello, World!': print(str) else: print('Try Again!') hello_world() hello_world()
false
f8390e1a672802dd30b581fb71a50b1a2d3fbcd5
kristopher-merolla/Dojo-Week-3
/python_stack/python_fundamentals/type_list.py
1,418
4.46875
4
# Write a program that takes a list and prints a message for each element in the list, based on that element's data type. # Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'. # Here are a couple of test cases (l,m,n below) # #input l = ['magical unicorns',19,'hello',98.98,'world'] # #output # "The array you entered is of mixed type" # "String: magical unicorns hello world" # "Sum: 117.98" # # input m = [2,3,1,7,4,12] # #output # "The array you entered is of integer type" # "Sum: 29" # # input n = ['magical','unicorns'] # #output # "The array you entered is of string type" # "String: magical unicorns" # ------------------------------------------------- k = l mySum = 0 myStr = "" for i in range (0,len(k)): if (type(k[i]) is str): myStr += k[i] myStr += " " elif (type(k[i]) is int): mySum += k[i] elif (type(k[i]) is float): mySum += k[i] if (myStr!="" and mySum!=0): print "The array you entered is of mixed type" print myStr print mySum elif (myStr=="" and mySum!=0): print "The array is of integer type" print mySum else: print "The array is of string type" print myStr
true
3caf05cc3eb9cee2e9e0d7ad2ef9882a32a8668d
niteeshmittal/Training
/python/basic/Directory.py
1,490
4.125
4
#Directory try: fo = open("phonenum.txt") #print("phonenum.txt exists. We are good to go.") except IOError as e: if (e.args[1] == "No such file or directory"): #print("File doesn't exists. Creating a phonenum.txt.") fo = open("phonenum.txt", "w") finally: fo.close() opt = input("1 for store and 2 for read: ") print(f"You chose {opt}") #if (opt == '1'): # name = input("Enter you name: ") # print(f"You entered {name}") # fo = open("phonenum.txt", "a") # #fo.write("\n" + name) # fo.write(name + "\n") # fo.close() #elif (opt == '2'): # print("You chose to read and display the file.") # fo = open("phonenum.txt") # str = fo.read() # print(str) # fo.close() #else: # print("Functionality under development.") namelist = [] if (opt == '1'): while (opt == '1'): name = input("Enter your name: "); print(f"You entered {name}"); namelist.append(name); opt = input("1 to coninue saving more names\n2 to display the current list\n3 to display file content: "); print(namelist); fo = open("phonenum.txt", "a"); for i in namelist: fo.write(i + "\n"); fo.close(); if (opt == '2'): print();print("You chose to display the current list of names given by user.\nCurrent list: {0}".format(namelist)); opt = input("3 to display file content: "); if (opt == '3'): print();print("You chose to read and display the file."); fo = open("phonenum.txt"); str = fo.readlines(); #print(str); for x in str: print(x.strip()); fo.close(); else: print("You chose to exit.");
true
3dde22d71aab3f343ef9f0aa6707e7b6a9220a61
rjcmarkelz/python_the_hard_way
/functional_python/chp1_1.py
1,619
4.15625
4
# chapter 1 of functional python book def sum(seq): if len(seq) == 0: return 0 return seq[0] + sum(seq[1:]) sum([1, 2, 3, 4, 1]) sum([1]) # recursive def until(n, filter_func, v): if v == n: return [] if filter_func(v): return [v] + until(n, filter_func, v+1) else: return until(n, filter_func, v+1) # now use lambda for one line functions mult_3_5 = lambda x: x % 3 == 0 or x % 5 == 0 mult_3_5(3) mult_3_5(5) # combine until(10, lambda x: x % 3 == 0 or x % 5 == 0, 0) # nested generator expression sum(n for n in range(1, 10) if n % 3 == 0 or n % 5 == 0) # object creation # plus operator is both commutative and associative 1 + 2 + 3 + 4 # can also be # fold values left to right # create intermediate values 3 and 6 ((1 + 2) + 3) + 4 # fold values right to left # intermediate objects 7 and 9 are created 1 + (2 + (3 + 4)) # slight advantage working left to right import timeit timeit.timeit("((([] + [1]) + [2]) + [3]) + [4]") timeit.timeit("[] + ([1] + ([2] + ([3] + [4])))") #### # Important functional design that + has no hidden side effects #### # stack of turtles # CPUs are generally procedural not functional or OO # three main layers of abstraction # 1) applications will be functions all the way down until # we hit the objects # 2) Underlying Python runtime environment that supports functional # programming is objects- all the way down- until we hit turtles # 3) The libraries that support python are a turtle on which python stands # # The OS and hardware form thier own stack of turtles # Nearing the end.
true
40f54f4122729cba200e3ede71fcbab9ad4481f3
alexspring123/machine-leaning-study
/scikit-lean/linear-models/Ordinary-Least-Squares/OrdinaryLeastSquares.py
1,076
4.1875
4
''' 普通最小二乘法 根据商品历史销量预测未来销量 ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model def get_data(file_name): "获取训练数据" # https://chrisalbon.com/python/pandas_dataframe_importing_csv.html data = pd.read_csv(file_name) x = np.array(data[['week']]) y = np.array(data['qty']) return x, y def create_linear_model(x, y): regr = linear_model.LinearRegression() regr.fit(x, y) return regr def show_linear_line(x, y, model): plt.scatter(x, y, color='black') # 样本 plt.plot(x, model.predict(x), color='blue') # 预测函数 plt.show() # 显示图形 def predict(model, x): predict_out = model.predict(x) print('预测结果:第', x, '周销量=', predict_out) def main(): "主函数" print(__doc__) x, y = get_data('data.csv') model = create_linear_model(x, y) # 预测30周销量 predict(model, 30) show_linear_line(x, y, model) if __name__ == '__main__': main()
false
b9b22be77a2ec061bba9dea6a8967e6f18e1da3c
cumtqiangqiang/leetcode
/top100LinkedQuestions/5_longest_palindromic_sub.py
783
4.125
4
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" ''' def longestPalindrome(s: str) -> str: start = 0 end = 0 for i in range(len(s)): len1 = getTheLengthOfPalindrome(s,i,i) len2 = getTheLengthOfPalindrome(s,i,i+1) maxLen = max(len1,len2) if maxLen > end - start: start = i - (maxLen - 1)//2 end = i + maxLen//2 return s[start:end+1] def getTheLengthOfPalindrome(s,left,right): while(left >= 0 and right <= len(s) and s[left:left+1] == s[right:right+1]): left -= 1 right += 1 return right - left -1 if __name__ == '__main__': s = longestPalindrome("acbbcd") print(s)
true
560f616083f33b95ba075a311d5c0a799f7c466b
Afraysse/practice_problems_II
/HB_warm_ups.py
1,889
4.28125
4
""" REVERSE A STRING RECURSIVELY """ def reverse_string(string): output = "" if len(string) == 0: return output output += string[-1] return output + reverse_string(string[:-1]) """ REVERSE STRING WITH INDEXES """ def reverse_string_indexes(string): return string[::-1] """ SUM ITEMS IN A LIST - BRUTE FORCE """ def sum_items_in_lst(lst): sum_items = 0 for i in lst: sum_items += i return sum_items """ SUM ITEMS RECURSIVELY """ def sum_items_in_lst_recurse(lst): sum_items = 0 if lst == []: return sum_items sum_items += lst[0] return sum_items + sum_items_in_lst_recurse(lst[1:]) """ MERGE SORT SORTED LISTS """ # lst1 = [1, 2, 3] # lst2 = [4, 5, 6] def merge_sort(lst1, lst2): """ Merge together two sorted lists. """ x = 0 y = 0 results = [] while True: if y >= len(lst1): results.extend(lst1[x:]) return results if x >= len(lst2): results.extend(lst2[y:]) return results if lst1[x] <= lst2[y]: results.append(lst1[x]) x += 1 if lst2[y] <= lst1[x]: results.append(lst2[y]) y += 1 """ POLISH NOTATION CALCULATOR. """ # s = "/ 6 - 4 2" def polish_notation(s): """ Calculate (s) where s as a string is the equation.""" # iterate through list - see if int or symbol # keep seperate stacks - operators and numbers # pop last num off to start - perform backwards # operators = [/, -] # numbers = [6, 4, 2] # combining as we go, popping backwards operators = [] numbers = [] t = s.split(" ") operand2 = int(t.pop()) while tokens: # grab the right-most number operand1 = int(t.pop()) # grab the right-most operand operator = t.pop() # do
false
f1386a1b5ff8705938dbdd96f11c954fdf1dfd3c
diceitoga/regularW3PythonExercise
/Exercise8.py
339
4.125
4
#Exerciese 8: 8. Write a Python program to display the first and last colors from the following list. Go to the editor #color_list = ["Red","Green","White" ,"Black"] color_list = ["Red","Green","White" ,"Black"] lengthof=len(color_list) print("First Item: {}".format(color_list[0])) print("Last Item: {}".format(color_list[lengthof-1]))
true
cf2a4e7217f251ae3b854f5c5c44eaa3ea3f140b
diceitoga/regularW3PythonExercise
/Ex19_is.py
413
4.21875
4
#Ex 19: Write a Python program to get a new string from a given string where "Is" has been added to the front. #If the given string already begins with "Is" then return the string unchanged print("test") sentence_string = input("Please enter a short sentence and I will add something: ") first_l = sentence_string.split(' ') if first_l[0] == 'Is': print(sentence_string) else: print("Is " + sentence_string)
true
84fee185f3fbf9a59cf1efe89ca7ff5472e97691
diceitoga/regularW3PythonExercise
/Ex21even_odd.py
388
4.46875
4
#Ex21. Write a Python program to find whether a given number (accept from the user) is even or odd, #print out an appropriate message to the user. def even_odd(num): even_odd = '' if num%2==0: even_odd = 'even' else: even_odd = 'odd' return even_odd what_isit =even_odd(int(input("Please enter an integer between 1-100 and I will tell you if even or odd: "))) print(what_isit)
true
d83882634e4db5e59edfbb1c760ef0483010fd3b
joqhuang/si
/lecture_exercises/gradepredict.py
2,003
4.40625
4
# discussion sections: 13, drop 2 # homeworks: 14, drop 2 # lecture exercise: 26, drop 4 # midterms: 2 # projects: 3 # final project: 1 # get the data into program # extract information from a CSV file with all the assignment types and scores # return a data dictionary, where the keys are assignment groups and values are lists of scores def get_data(): pass # identify and drop the lowest grades for discussion, homework, lecture # takes a list of scores and drops the lowest number specified def drop_lowest(list_of_scores, num_to_drop): pass #take the list for all the scores in a single assignment group and returns the group total def compute_group_total(list_of_scores): pass # adds up total points across categories # convert from points to percentage # convert to letter grade def compute_grade(total_score): pass def test_functions(): #test drop_lowest list1 = [10,9,8,7,6] expected_return1 = [10,9,8] expected_return1 = [10] #test compute_group_total list2= [1,1,1,1] expected_return3 = 4 passed = 0 failed = 0 if drop_lowest(list1,2)==expected_return1: #test passed passed += 1 else: #test tailed failed += 1 print("failed test 1") if drop_lowest(list1,4)==expected_return2: #test passed passed += 1 else: #test tailed failed += 1 print("failed test 2") if compute_group_total(list2) == expected_return3: passed += 1 else: failed += 1 print("failed test 3") data_dict = get_data() # homework_scores = drop_lowest(data_dict['homeworks'],2) # lecture_scores = drop_lowest(data_dict['lectures'],4) # discussion_scores = drop_lowest(data_dict['discussion'],2) # etc for each assignment types # use compute_group_total for each group, and append those values to a list # use compute_group_total on the list of group totals to calculate the total_score # grade = compute_grade(total_score) # print(grade)
true
0abe0e63e9cd588267c456a87ea6ce6068e3da15
Tonyqu123/data-structure-algorithm
/Valid Palindrome.py
720
4.3125
4
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # # For example, # "A man, a plan, a canal: Panama" is a palindrome. # "race a car" is not a palindrome. # # Note: # Have you consider that the string might be empty? This is a good question to ask during an interview. # # For the purpose of this problem, we define empty string as valid palindrome. class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) != 0: result = [char.lower() for char in s if char.isalnum()] return result == result[::-1] else: return True
true
8c7569bf644859b9a51d0a6b06935c0dcbbfd509
chococigar/Cracking_the_code_interview
/3_Stacks_and_Queues/queue.py
598
4.1875
4
#alternative method : use lists as stack class Queue(object) : def __init__(self): self.items = [] def isEmpty(self): return (self.items==[]) def enqueue(self, item): self.items.insert(0, item) def dequeue(self): self.items.pop() #first in first out. last item is first. def size(self): return len(self.items) def show(self): print("top "), for elem in self.items: print elem, ", ", print("bottom (first out)") s = Queue() s.enqueue(1) s.enqueue(2) s.enqueue(3) s.enqueue(4) s.enqueue(5) s.show()
true
93b706571c7b3451f5c677cc7d9ddb1dffa67f13
blkbrd/python_practice
/helloWorld.py
2,330
4.15625
4
print ("hello World") ''' #print('Yay! Printing.') #print("I'd much rather you 'not'.") #print('I "said" do not touch this.') print ( "counting is fun") print ("hens", 25 + 30 / 6) print ("Is it greater?", 5 > -2) #variables cars = 100 space_in_a_car = 4 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers = passengers / cars_driven print("There are", cars, "cars available.") print("There are only", drivers, "drivers available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers, "in each car.") #strings my_name = 'Lillian' my_age = 24 /3 # not a lie my_height = 67 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Blonde' print(f"Let's talk about {my_name}.") print(f"She's {my_height} inches tall.") print(f"She's {my_weight} pounds heavy.") #print("Actually that's not too heavy.") print(f"She's got {my_eyes} eyes and {my_hair} hair.") print(f"Her teeth are usually {my_teeth} depending on the coffee.") total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.") types_of_people = 10 x = f"There are {types_of_people} types of people." binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." print(x) print(y) print(f"I said: {x}") print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_evaluation.format(hilarious)) w = "This is the left side of..." e = "a string with a right side." print(w + e) print("Its fleece was white as {}.".format('snow')) print("." * 10) # what'd that do? formatter = "{} and a {} and a {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "a", "b", "c", "d" )) ''' x = input("something: ") #print((int)x + 4) #how do i take int input????
true
64f31b62c4a464b495cf051d73c26b67b37cc8bb
padma67/guvi
/looping/sum_of_first_and_last_digit_of_number.py
342
4.15625
4
# Program to find First Digit and last digit of a Number def fldigit(): number = int(input("Enter the Number: ")) firstdigit = number while (firstdigit >= 10): firstdigit = firstdigit // 10 lastdigit = number % 10 print("sum of first and last digit of number is {0}".format(firstdigit+lastdigit)) fldigit()
true
df2c4134cb5454aac257dcb270cc651595b3a8c4
padma67/guvi
/looping/Calculator.py
865
4.1875
4
#Calculator #get the input value from user num1=float(input("Enter the number 1:")) num2=float(input("Enter the number 2:")) print("1.Add") print("2.Sub") print("3.Div") print("4.Mod") print("5.Mul") print("6.Expo") #get the function operator from uuer ch=float(input("Enter your choice:")) c=round(ch) if(c==1): print("The output of ",num1,"and",num2,"is",num1+num2) elif(c==2): print("The output of ",num1,"and",num2,"is",num1-num2) elif(c==3): if(num2==0): print("The output of ",num1,"and",num2,"is Infinity") else: print("The output of ",num1,"and",num2,"is",num1/num2) elif(c==4): print("The output of ",num1,"and",num2,"is",num1%num2) elif(c==5): print("The output of ",num1,"and",num2,"is",num1*num2) elif(c==6): print("The output of ",num1,"and",num2,"is",num1**num2) else: print("Invalid choice")
true
451744ff93bd4ee503af5d2f28e1bf8d89f16517
padma67/guvi
/looping/Print_even_numbers_from_1_to_100.py
264
4.1875
4
#To print all even numbers between 1 to 100 def Even(): #declare the list for collect even numbers even=[] i=1 while(i<=100): if(i%2==0): even.append(i) i=i+1 print("even numbers between 1 to n",even) Even()
true
6e135b53bbde0cd65bdf7c36815195dd29e6ec66
Nitin26-ck/Scripting-Languages-Lab
/Part B/Lab 5/Prg5_file_listcomprehension.py
2,064
4.1875
4
""" Python File Handling & List Comprehension Write a python program to read contents of a file (filename as argument) and store the number of occurrences of each word in a dictionary. Display the top 10 words with the most number of occurrences in descending order. Store the length of each of these words in a list and display the list. Write a one-line reduce function to get the average length and one-line list comprehension to display squares of all odd numbers and display both. """ import sys import os from functools import reduce dict = {} wordLen = [] if(len(sys.argv) != 2): print ("Invalid Arguments") sys.exit() if(not(os.path.exists(sys.argv[0]))): print ("Invalid File Path") sys.exit() if(sys.argv[1].split('.')[-1] != "txt"): print ("Invalid File Format. Only TXT files allowed") sys.exit() with open(sys.argv[1]) as file: for line in file: for word in line.split(): dict[word] = dict.get(word,0) + 1 print (dict) # Display the top 10 words with most number of occurrences in descending order. # Food for thought - Does a dictionary maintain order? How to print 10 words with most frequency? # Ans - extract dict items as Tuples and sort them based on value in dictionary #(second item of the tuple / index 1) sortedDict = sorted(dict.items(), key=lambda dictItem: dictItem[1], reverse=True) for i in range(len(sortedDict)): print(sortedDict[i]) for i in range(10): try: wordTuple = sortedDict[i] wordLen.append(len(wordTuple[0])) print (wordTuple[0], ", Frequency: " , wordTuple[1] , ", Length " , len(wordTuple[0])) except IndexError: print ("File has less than 10 words") break print ("Lengths of 10 most frequently occuring words:") print (wordLen) # Write a one-line reduce function to get the average length sum = reduce(lambda x,y: x+y, wordLen) print ("Average length of words: " , sum/len(wordLen)) # Write a one-line list comprehension to display squares of all odd numbers squares = [x**2 for x in wordLen if x%2 != 0] print ("Squres of odd word lengths: ") print (squares)
true
221fdeb75e2f6db401901b5755e991bdffdcee75
Nitin26-ck/Scripting-Languages-Lab
/Part B/Lab 1/Prg1c_recursion_max.py
809
4.15625
4
""" Introduction to Python : Classes & Objects, Functions c) Write a recursive python function that has a parameter representing a list of integers #and returns the maximum stored in the list. """ #Hint: The maximum is either the first value in the list or the maximum of the rest of #the list whichever is larger. If the list only has 1 integer, then its maximum is this #single value, naturally. Demonstrate with some examples. def Max(list): if len(list) == 1: return list[0] else: m = Max(list[1:]) return m if m > list[0] else list[0] def main(): try: list = eval(input("Enter a list of numbers: ")) print ("The largest number is: ", Max(list)) except SyntaxError: print ("Please enter comma separated numbers") except: print ("Enter only numbers") main()
true
901e5ae13f821c2e3da9df9b46d9a1d7e7cc003c
KodingKurriculum/learn-to-code
/beginner/beginner_3.py
1,789
4.78125
5
# -*- coding: utf-8 -*- """ Beginner Script 3 - Lists, and Dictionaries Functions allow you to group blocks of code and assign it a name. Functions can be called over and over again to perform specific tasks and return values back to the calling program. """ """ 1.) Lists (also known as an Array) are great for storing a series of information. You can iterate the list to access its contents, or specify a single value. Python is zero-based, in that each position in the array is given a number from 0 to the last element. c Add your name to the list, then have the script print your name. """ my_list = ['Karl', 'Karly', 'Kristoph', 'Kurt'] # print(...) """ 2.) You may iterate the list using the "for loop" again. Iterate the list of names and print out. """ # for name in ...: """ 2.) Dictionaries are even more useful in that they can store key/value pairs of information. As you may notice, the dictionary below looks a lot like an Excel header with a list of values below. Add my_list to the dictionary """ my_dict = { "Numbers": [1, 2, 3, 4, 5], "Fruit": ["Apple", "Orange", None, "Orange", "Peach"] } """ 3.) Dictionaries have key/value pairs which is useful for looking information up based on a known key. You can do this using the syntax my_dict['key']. Look up the list of fruits from my_dict, and print the first fruit out. """ # fruits = ... """ 4.) Python is an object-oriented language, and every variable has a group of functions that you may call. To iterate the list of dictionary key/value pairs, we need to call the dictionary's .items() function, such as my_dict.items(). Iterate the list of key/value pairs and print them out. """ def printValues(dict): # for key, value in ...: # print("My favorite {0} is {1}".format(key, value))
true
0f882e8b74773b888de20be38564c13642cd306a
ijuarezb/InterviewBit
/04_LinkedList/K_reverse_linked_list.py
2,527
4.125
4
#!/usr/bin/env python3 import sys #import LinkedList # K reverse linked list # https://www.interviewbit.com/problems/k-reverse-linked-list/ # # Given a singly linked list and an integer K, reverses the nodes of the # # list K at a time and returns modified linked list. # # NOTE : The length of the list is divisible by K # # Example : # # Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2, # # You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5 # # Try to solve the problem using constant extra space. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param A : head node of linked list # @param B : integer # @return the head node in the linked list def reverseList(self, A, B): # swap the List >> in Groups << of B items head = last = None while A: start = A prev = A A = A.next for i in range(1, B): next = A.next A.next = prev prev = A A = next if last: last.next = prev last = start if not head: head = prev if last: last.next = None return head def print_list(self, head): temp = head while temp: print(temp.val, end=' ') temp = temp.next print("") # swap K pairs def swapPairs(self, A, B): fake_head = ListNode(0) fake_head.next = A tmp, i = fake_head, 0 while tmp and tmp.next and tmp.next.next and i < B: nxt = tmp.next tmp.next = tmp.next.next nxt.next = tmp.next.next tmp.next.next = nxt tmp = tmp.next.next i += 1 return fake_head.next # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if __name__ == '__main__': s = Solution() # Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2, # You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5 n = ListNode(1) n.next = ListNode(2) n.next.next = ListNode(3) n.next.next.next = ListNode(4) n.next.next.next.next = ListNode(5) n.next.next.next.next.next = ListNode(6) s.print_list(n) #h = s.swapPairs(n, 2) h = s.reverseList(n, 3) s.print_list(h)
true
0e8330781cac465d3bae07379fa9d2435940d03e
Ekimkuznetsov/Lists_operations
/List_split.py
309
4.25
4
# LIsts operations # For each line, split the line into a list of words using the split() method fname = input("Enter file name: ") fh = open(fname) fst = list() for line in fh: x = line.split() for word in x: if word not in fst: fst.append(word) fst.sort() print(fst)
true
e6ecd5211b15b6cb201bdd2e716a7b4fec2db726
markcurtis1970/education_etc
/timestable.py
1,693
4.5
4
# Simple example to show how to calculate a times table grid # for a given times table for a given length. # # Note there's no input validation to check for valid numbers or # data types etc, just to keep the example as simple. Plus I'm not # a python developer :-) # Ask user for multiplier and max range of times table # the input statement asks for a value and loads it into the variable # on the left tt_num = input("Enter times table number: ") # this is the times table number you want tt_len = input("Enter times table length: ") # this is the length of the above times table # loop 1: we execute this loop every time up to the times table number. # Note the range statement will execute up to 1 less than the maximum set, # for more info see: https://docs.python.org/2/library/functions.html#range # this is what makes each row for tt_val in range(1,tt_num + 1): # reset the results each time we execute this loop to the starting # value of the row, note the str() changes the integer to a string type # so we can do things like concatenation later results = str(tt_val) # loop 2: we execute this loop up to the value of the times table length # this is what makes each column in a given row. Note we start the range # at 2, this is because the intial value is already loaded into the string # variable above when we reset it for multiplier in range(2,tt_len + 1): result = tt_val * multiplier # calculate the result results = str(results) + "\t" + str(result) # concatenate the string, the "\t" is a tab character # print the results out once all columns are calculated and before moving to the next row print results
true
1a024d3e345afbcc0b8cfa354e14416401f9c565
dogac00/Python-General
/generators.py
1,253
4.46875
4
def square_numbers(nums): result = [] for i in nums: result.append(i*i) return result my_nums = square_numbers([1,2,3,4,5]) print(my_nums) # will print the list # to convert it to a generator def square_numbers_generator(nums): for i in nums: yield i*i my_nums_generator = square_numbers_generator([1,2,3,4,5]) print(my_nums_generator) # will print the generator object print(next(my_nums_generator)) print(next(my_nums_generator)) print(next(my_nums_generator)) print(next(my_nums_generator)) print(next(my_nums_generator)) # do it manually by next # can't do it one more time because it will give the error StopIteration # since it has 5 elements # another way is this for num in my_nums_generator: print(num) # much more readable with generators # another way is with the list comprehenstion my_nums_list_comprehension = [x*x for x in [1,2,3,4,5]] # you can create a generator as taking out brackets and putting paranthesis my_nums_comprehension_generator = (x*x for x in [1,2,3,4,5]) print(my_nums_comprehension_generator) # will print the generator object print(list(my_nums_comprehension_generator)) # you lose the advantages of performance and memory # when you pass the generator to a list like above
true
f7eaadb3ee801b8011e2fddd03a055902f2da614
sohanjs111/Python
/Week 3/For loop/Practice Quiz/question_2.py
608
4.375
4
# Question 2 # Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with # the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all # integers before it. For example, the factorial of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!) # is equal to 1. def factorial(n): result = 1 for x in range(1, n): result = result * x return result for n in range(0,10): print(n, factorial(n+1))
true
7a22126b7d66730558314ad8295c087559ee4b41
sohanjs111/Python
/Week 4/Graded Assessment/question_1.py
1,463
4.5
4
# Question 1 # The format_address function separates out parts of the address string into new strings: house_number and street_name, # and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the # street name which may contain numbers, but never by themselves, and could be several words long. For example, # "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function. def format_address(address_string): # Declare variables house_no = '' street_name = '' # Separate the address string into parts address_words = address_string.split(" ") # Traverse through the address parts for word in address_words: # Determine if the address part is the # house number or part of the street name if word.isdigit(): house_no = word else: street_name += word street_name += " " # Does anything else need to be done # before returning the result? # Return the formatted string return "house number {} on street named {}".format(house_no, street_name) print(format_address("123 Main Street")) # Should print: "house number 123 on street named Main Street" print(format_address("1001 1st Ave")) # Should print: "house number 1001 on street named 1st Ave" print(format_address("55 North Center Drive")) # Should print "house number 55 on street named North Center Drive"
true
6adef0926886b9f6406f056fb9faef6640068338
sohanjs111/Python
/Week 4/Lists/Practice Quiz/question_6.py
957
4.40625
4
# Question 6 # The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the # sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), # ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works # as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that. def guest_list(guests): for i in guests: g_name = i[0] g_age = i[1] g_job = i[2] print("{} is {} years old and works as {}".format(g_name, g_age, g_job)) guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) #Click Run to submit code """ Output should match: Ken is 30 years old and works as Chef Pat is 35 years old and works as Lawyer Amanda is 25 years old and works as Engineer """
true
3918f8ff48585ae65b1949cc709a8da345d26b93
sohanjs111/Python
/Week 4/Strings/Practice Quiz/question_2.py
593
4.3125
4
# Question 2 # Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y # km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2km". def convert_distance(miles): km = miles * 1.6 result = "{} miles equals {:.1f} km".format(miles, km) return result print(convert_distance(12)) # Should be: 12 miles equals 19.2 km print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km print(convert_distance(11)) # Should be: 11 miles equals 17.6 km
true
615c579433bd2c31eacc75412eafb19a325f0306
AlinesantosCS/vamosAi
/Módulo - 1/Módulo 1-7 - Mamma Mia!/stem_comparacao.py
1,356
4.28125
4
# Se não me engano .title() retorna a string como se fosse um título, ou seja, a primeira letra maiuscula def sobre_marie(): print("{0:^60}".format('Marie Curie')) print('Cientista responsável por descrever os elementos químicos Polônio e o Rádio e primeira mulher a ganhar um Prêmio Nobel — Física (1903) e Química (1911).') def comparacao(): idade = int(input('Qual é o seu ano de nascimento ? ')) pais = input('Qual é o país de nascimento ? - sem acentos ') estado = input('Qual é o estado de nascimento ? - sem acentos ') if idade > 1934: idade = idade - 1934 print(f'Você é mais novo(a) que a Marie Curie diferença de {idade} anos') elif(idade < 1934): print(f'Você é mais velho(a) que a Marie Curie diferença de {idade} anos') if (pais == 'polonia'): print(f'Você nasceu no mesmo país que se chama {pais.capitalize()} que a Marie Curie. ') else: print(f'Você nasceu({pais.capitalize()}) em um pais diferente da Marie Curie, ela nasceu na Polônia. ') if (estado == 'varsovia'): print(f'Você nasceu no mesmo país que se chama {pais.capitalize()} que a Marie Curie. ') else: print(f'Você nasceu({estado.capitalize()}) em um estado diferente da Marie Curie, da qual foi Varsóvia. ') sobre_marie() comparacao()
false
11e2d96faa001bcceb225b58f1121b8b4e2cd4ed
AlinesantosCS/vamosAi
/Módulo - 1/Módulo 1-5 - Sem condições!/stem.py
1,672
4.125
4
acertou = 0 print(' JOGO DE ADIVINHAÇÃO DA MARIE CURIE') print('Digite qual alternativa é verdadeira A, B ou C.') pergunta_1 = input(' Pergunta 1 - Qual área ela trabalhou ?\n A - Engenharia\n B - Ciência\n C - Tecnologia\n Escolha uma alternativa: ') pergunta_2 = input(' Pergunta 1 - A causa da morte de Marie Currie está relacionado ao trabalho dela, qual foi a doença ?\n A - Aids\n B - Leucemia\n C - Pneumonia\n Escolha uma alternativa: ') pergunta_3 = input(' Pergunta 1 - Quais dessas alternativas é verdadeira ?\n A - Ela não tinha nenhum admirador conhecido na área, inclusive Albert Einstein criticava Marie.\n B - Os cadernos dela não são radioativos\n C - Ela foi educada em segredo\n Escolha uma alternativa: ') if pergunta_1.upper() == 'B': print("Acertou! Ela foi uma cientista bem foda!") acertou+= 1 else: print("Errou! Ela foi uma cientista bem foda!") if pergunta_2.upper() == 'B': print("Acertou! Ela morreu de leucemia em decorrência de contato constante com radiotividade.") acertou+= 1 else: print("Errou! Ela morreu de leucemia em decorrência de contato constante com radiotividade.") if pergunta_3.upper() == 'C': print("Acertou! Isso ocorreu porque na época os russos consideravam educar mulheres uma atividade ilegal :/ ") acertou+= 1 else: print("Errou! Isso ocorreu porque na época os russos consideravam educar mulheres uma atividade ilegal :/ ") print(f'Você acertou {acertou} questões!') print('MARIE CURIE') print('cientista responsável por descrever os elementos químicos Polônio e o Rádio e primeira mulher a ganhar um Prêmio Nobel — Física (1903) e Química (1911).')
false
e34200e7aa655e007745ff77b1c58c6ce62b525d
AlinesantosCS/vamosAi
/Módulo - 1/Módulo 1-14- Listas pra que te quero!/reverse-string.py
536
4.1875
4
def reverse_string(str): str = str[::-1] return (str) str = ["1", "2", "3", "4"] reverse_string (str) '''O reverse de listas em Python reverte a lista in place, alterando os valores da lista ao invés de criar uma lista nova escrita ao avesso. Como strings em Python são imutáveis, não faz muito sentido que elas suportem o método reverse. Um slice como "abcdefghijklm"[1:9:2] pega os elementos da posição 1 até a 9, de 2 em 2. O slice [::-1], pega os elementos do início ao fim, andando de trás pra frente. '''
false
838632c00192ddd52a00f2f5cfb1794e57cd1424
AlinesantosCS/vamosAi
/Módulo - 2/Módulo 2-8 - Cada um no seu quadrado!/modulo.py
805
4.1875
4
import math from math import sqrt,floor # Biblioteca random da classe random - # Numéros aleátorios de 0 a 1 em float import random import emoji num = int(input("Digite um numero: ")) """ floor - arrendona para baixo """ # Raiz quadrada - Arrendona pra cima raiz = math.sqrt(num) print('A raiz de {} é igual a {}'.format(num,math.ceil(raiz))) numero_1 = random.random() # Números inteiros numero_2 = random.randint(1,10) print(numero_1) print(numero_2) # Py Pi é um indice de pacotes extras do Python print(emoji.emojize("Olá mundo :bowtie:", use_aliases=True)) print(emoji.emojize("Python é :polegar_para_cima:", language='pt')) print(emoji.emojize("Python is fun :red_heart:")) print(emoji.emojize("Python is funnn :heart_eyes:")) print(emoji.emojize("Python is fun :broken_heart:"))
false
8a99ecb567725253701a8f4f53a11452d0087e87
AlinesantosCS/vamosAi
/Módulo - 2/Módulo 2-1 - Qual é o significado/ordena_dicionario.py
590
4.15625
4
# dicionario = {"a": 2, "b": 3, "c": 1} # # O método items() dos dicionários retorna o par (chave, valor) # # como tuplas de tamanho 2 # print (dicionario.items()) # print(sorted(dicionario.items(), key=lambda x: x[1])) # def ordena_dicionario(dicionario): # # Implemente a lógica da função aqui # ordena = (sorted(dicionario.items(), key=lambda x: x[1]) # for ordernas in ordena: # print(ordernas) # return ordenas dicionario = {"a": 2, "b": 3, "c": 1} # ordena_dicionario(dicionario) for item in sorted(dicionario, key = dicionario.get): print(dicionario[item])
false
beb66ab0fd7d03e14479037c4634da4e96a6ffb8
vitorhenriquesilva/python-introduction
/zip.py
357
4.25
4
#Funo .zip #Essa funo utilizada para a concatenao de duas ou mais listas lista1 = [1, 2, 3, 4 ,5] lista2 = ["abacate", "bola", "cachorro", "dinheiro", "elefante"] lista3 = ["R$2,00", "R$5,00", "No tem preo", "No tem preo", "No tem preo"] for numero, nome, valor in zip(lista1, lista2, lista3): print(numero, nome, valor)
false
69fd417b735877ae844880c2f8ed10f80d33413a
khayes25/recursive_card_sorter
/merge_sort.py
1,634
4.125
4
""" Merge Sort Algorithm """ #Class Header class Merge_Sort : def merge_sort(list, left, right) : if(left < right) : middle = (left + right) / 2 merge_sort(list, left, middle) merge_sort(list, middle + 1, right) merge(list, left, middle, right) def sort(list) : merge_sort(list, 0, len(list) - 1) """ Merges two partitions of an array together, in the correct order. """ def merge(list, left, middle, right) : lower_counter = 0 upper_counter = 0 merge_counter = left lower_size = middle - left + 1 upper_size = right - middle temp_lower = [] temp_upper = [] for i in range(0, lower_size) : temp_lower.insert(i, list[left + 1]) for i in range(0, upper_size) : temp_upper.insert(i, list[middle + 1 + I]) while(lower_counter < lower_size and upper_counter < upper_size) : if(temp_lower[lower_counter] <= temp_upper[upper_counter]) : list[merge_counter] = temp_lower[lower_counter] lower_counter += 1 else : list[merge_counter] = temp_upper[upper_counter] upper_counter += 1 merge_counter += 1 while(lower_counter < lower_size) : list[merge_counter] = temp_lower[lower_counter] lower_counter += 1 merge_counter += 1 while(upper_counter < upper_size) : list[merge_counter] = temp_upper[upper_counter] upper_counter += 1 merge_counter += 1
true
b16802cea3e32892e7953167eb4932457c6e41bb
mr-akashjain/Basic-Python-Stuff-For-Fun
/pigLatin.py
2,301
4.125
4
from time import sleep sentence = input("Hi, They call me latin pig translator. Enter a sentence to have fun with me:") sleep(4) print("Thanks for the input!! Fasten your seatbelt as you are about to enter into my world") sleep(3) print("I know my world is small, but it is mine!") sleep(2) say_something = input("Are you having Fun or not? Type(F/NF)") if say_something in "Ff": print("You are great!") sleep(1) print("Now comes the translation") sleep(1) #real code # split sentence into words words=sentence.strip().lower().split() new_words=[] #check for each word' for word in words: #check if the word start with a vowel if word[0] in "aeiou": #add 'Yay' to the word and add the word to a new list new_word = word +"Yay" new_words.append(new_word) else: vowel_pos = 0 for letter in word: if letter not in "aeiou": vowel_pos = vowel_pos+1 else: break new_word = word[vowel_pos:]+word[:vowel_pos]+"Ay" new_words.append(new_word) new_sentence = " ".join(new_words) print(new_sentence) else: print("You are rude!") sleep(1) print("It is my duty to serve. wait for another 2 seconds to get the translation") sleep(1) print("But don't get any ideas,coz I don't like you") sleep(2) #real code # split sentence into words words=sentence.strip().lower().split() new_words=[] #check for each word' for word in words: #check if the word start with a vowel if word[0] in "aeiou": #add 'Yay' to the word and add the word to a new list new_word = word +"Yay" new_words.append(new_word) else: vowel_pos = 0 for letter in word: if letter not in "aeiou": vowel_pos = vowel_pos+1 else: break new_word = word[vowel_pos:]+word[:vowel_pos]+"Ay" new_words.append(new_word) new_sentence = " ".join(new_words) print(new_sentence)
true
2bc6e15c932be59832de9e40960dc14c4de17c4f
AidaQ27/python_katas_training
/loops/vowel_count.py
777
4.21875
4
""" Return the number (count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces. --- We are starting with exercises that require iteration through the elements of a structure, so it will be good to dedicate some time to learn how they work https://www.learnpython.org/en/Loops Link to codewars exercise http://www.codewars.com/kata/vowel-count """ def get_count(input_str): num_vowels = 0 # your code here return num_vowels # Test methods below assert get_count("magic") == 2, "Vowel count is not correct" assert get_count("abracadabra") == 5, "Vowel count is not correct" assert get_count("let's get lost") == 3, "Vowel count is not correct"
true
42b2eac7097ededd9d87d2746afaeb5f8fc9b240
Nalinswarup123/python
/class 6/bio.py
658
4.125
4
'''biologists use seq of letter ACTC to model a genome. A gene is a substring of gnome that starts after triplet ATG and ends before triplet TAG , TAA and TGA. the length of Gene string is mul of 3 and Gene doesnot contain any of the triple TAG , TAA and TGA. wap to ask user to enter a genone and display all genes in genone. if no gene is found in seq then display no gene found.''' s=input('enter model') for i in range(len(s)): if(s[i:i+3]=="ATG"): for j in range(i+3,len(s)): if(s[j:j+3]!="TAG" or s[j:j+3]!="TAA" or s[j:j+3]!="TGA"): print(s[i+3:j]) else: print('no gene found')
true
470cd5e72d7a9147a6d2fc4835040fb3446f1dcc
Nalinswarup123/python
/calss 1/distance between two points.py
275
4.125
4
#distance between two points print('enter first point') x,y=int(input()),int(input()) print('enter second point') a,b=int(input()),int(input()) x=((x-a)**2+(y-b)**2)**0.5 print('distance between the given points=',x) #print('{} is the required distance'.format(x))
true
fd60a484b60b1f34dc3e5e2893b2a8ca5102688b
chandan-singh-007/Demo
/second.py
504
4.15625
4
#write a program to check whether a number is prime or not def prime(n): if (n>1): for i in range(2,n): if(n%i)==0: print(n ,"is not prime") break else: print(n,"is prime") # def prime(n): # if n>1: # for i in ran5ge(2,n): # if (n%i) == 0: # print("not prime") # break # else: # print("prime") number = int(input("enter the number :")) prime(number)
false
6692daa627b01842e018d078fac7b64354d9a968
smritta10/PythonTraining_Smritta
/Task3/Task3_all_answers.py
1,906
4.125
4
Task -3 #Question 1 diff_list= [10,'Smritta', 10.5,'1+2j', 20,'Singh', 113.0, '3+4j', 100, 'Python_learning'] print(diff_list) ----------------------------------------------------- #Question 2 list1= [10,20,30,40,50] s1= list1[ :5] #actual list s2= list1[ : :-1] # lists items in reverse order s3= list1[1:5:2] # lists item from 0 to 4 skipping 2nd item print('Different slicing results: ', s1, ',', s2, ',', s3) -------------------------------------------------- # Question 3 L1= [2,4,6,8] total= sum(L1) # find the sum print('Sum of all items in list is: ', total) result= 1 for i in L1: result= result *i print('Multiplication output is:', result) ------------------------------------------------------- #Question 4 myList= [2,4,6,8,10] print('Max number from the list is:', max(myList)) print('Min number from the list is:', min(myList)) ----------------------------------------------------- #Question 5 x= filter(lambda x: x%2==0,[5,10,15,20,25,30]) print(list(x)) ------------------------------------------------- #Ex-6 l= [] for i in range(1,31): l.append(i**2) print('First 5 elements square is: ', l[:5]) print('Last 5 elements square is: ', l[-5:]) ------------------------------------------------- #Ex-7 list1= [2,4,6,8,10] list2= [1,3,5] list1.pop() print('List after removing last item:', list1) list1.extend(list2) print('Final list after adding a list:', list1) ------------------------------------------------- #Ex-8 d= {} # empty dictionary dict1= {1:10, 2:20} dict2= {3:30, 4:40} d.update(dict1) d.update(dict2) print('Concatenated dictonary is:', d) ------------------------------------------------- #Ex-9 num= int(input('Input a number:')) dict= {} for i in range(1,num+1): dict[i]= i*i print('My dictionary is:', dict) -------------------------------------------------- #Ex-10 item = input('Enter a list of numbers: ') list1= item.split(',') print(list1)
true
c91f0044d88593f20382a5dd1122504d9fbf8c1d
sindhupaluri/Python
/count_string_characters.py
425
4.34375
4
# Please write a program which counts and returns the numbers of each character in a string input. # count_characters( "abcdegabc" ) # { 'a':2, 'c':2, 'b':2, 'e':1, 'd':1, 'g':1 } def count_characters(string): char_count = {} for char in string: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 print(char_count) count_characters("abcdegabc")
true
cc9f5557da6e2a296a670be87749e2cb7ac3c7b3
Jasjot784/Python
/for.py
348
4.21875
4
primes=[2,3,5,7] for num in primes: print(num) print("Outside the for loop") list1 = ["Apple","Bananas","Cherries"] tup1 = (13,12,15) for item in list1: print(item) for item in tup1: print(item) for i in range(1,11): print(i) for i in range(0,11,2): print(i) for i in range(0,5): for j in range(0,3): print(i*j)
false
8481e9764f727ca62824cd86691a537d71c38d3d
Xpf123131123/python_study_demo
/pak/io_input.py
447
4.15625
4
def reverse(text): return text[::-1] def isHuiWen(text): text1 = '' for item in text: if item >= 'a' and item <= 'z': text1 += item if item >= 'A' and item <= 'Z': text1 += item print(text1) return text1 == reverse(text1) text = input('输入内容,判断是否回文:') if isHuiWen(text): print('{} is hui wen'.format(text)) else: print('{} is not hui wen'.format(text))
false
05b0deda5e25686a6082b289b46594a1b57e7ea3
RAmruthaVignesh/PythonHacks
/Foundation/example_*args_**kwargs.py
845
4.53125
5
#When the number of arguments is unknown while defining the functions *args and **kwargs are used import numpy as np def mean_of_numbers(*args): '''This function takes any number of numerical inputs and returns the mean''' args = np.array(args) mean = np.mean(args) return mean print "The mean of the numbers :" , mean_of_numbers(2,3,4.1,5,8) def string_concat(*args,**kwargs): '''This function takes any number of arguments and keyword arguments. Converts into string and concatenates them''' string_input_args= [str(i) for i in args] args_out = ''.join(string_input_args) input_kwargs = [kwargs[j] for j in kwargs] kwargs_out = ''.join(input_kwargs) return args_out+kwargs_out string_out= string_concat(1,2, a="Hi" , b= "howdy?" ) print "The concatenated string output are " , string_out
true
f24bcde3c27bf62a63df4e2e2d6d76925ac51352
RAmruthaVignesh/PythonHacks
/Foundation/example_list_comprehension.py
651
4.71875
5
#Example 1 : To make a list of letters in the string print "This example makes a list of letters in a string" print [letter for letter in "hello , _world!"] #Example 2: Add an exclamation point to every letter print "\nExample 2: Add an exclamation point to every letter" print [letter+"!" for letter in "hello , world !"] #Example 3 : To generate multiplication table of 9 print "\nExample 3: A multiplication table for the 9's" print [num*9 for num in range(1,13)] #Example 4 : To print letters if they are not o print "\nExample 4: Make a list of letters in a string if they're not 'o'" print [letter for letter in "hello_world" if letter!="o"]
true
9d4b2995f00b605030a1d763f133a01c83965681
RAmruthaVignesh/PythonHacks
/MITCourse/MITcourse_hw1.py
938
4.1875
4
# Name: Amrutha # Date:12.17.2016 # hw1.py ##### Template for Homework 1, exercises 1.2-1.5 ###### print "Hello , World!" # Do your work for Exercise 1.2 and 1.3 here tictac = " | |" toe = "--------" print "Printing tictactoe board" print tictac + '\n'+ toe + '\n' + tictac + '\n' + toe + '\n' + tictac print "********** Exercise 1.4 **********" print "********* Part II *************" a = (3*5)/(2+3) b= ((7+9)**(1.0/2)) c= (4-7)**3 d=(-19+100)**(1.0/4) e=6%4 print a , b , c , d, e print "********* Part III *************" a= (3.0*5)/(2+3) b= 3*(5.0/2)+3 print "(3*5)/(2+3) = " , a print "3*(5.0/2)+3 =" ,b print "********** Exercise 1.5 **********" firstname = raw_input("Enter your first name :") lastname = raw_input("Enter the last name :") month = raw_input("Enter your date of birth \n month?") day = raw_input("Day?") year = raw_input("Year?") print firstname , lastname ,"was born on " + month , day + "," + year
false
9095e434cabe1afd4d287c4db9885bbf0d7b4515
RAmruthaVignesh/PythonHacks
/OOPS/class_inheritance_super()_polygons.py
1,891
4.78125
5
#This example explains the super method and inheritance concept class polygons(object): '''This class has functions that has the functionalities of a polygon''' def __init__(self,number_of_sides):#constructor self.n = number_of_sides print "The total number of sides is" , self.n def interior_angle(self): '''This function calculates the interior angle of a polygon''' return (180*(self.n-2))/self.n def exterior_angle(self): '''This function calculates the exterior angle of a polygon''' return 360/self.n def number_of_diagonals(self): '''This function calculates the number of diagonals in a polygon''' return ((self.n**2) - (3*self.n))/2 class rectangle(polygons): '''This class inherits all the functionalities of a polygon''' def __init__(self,length,breadth): number_of_sides = 4 self.l = length self.b = breadth super(rectangle,self).__init__(number_of_sides) def interior_angle(self): '''This function calculates the interior angle of a rectangle''' return super(rectangle,self).interior_angle() def area(self): '''This function calculates the area''' return self.l*self.b class square(rectangle): '''This class inherits all the functionalities of rectangle class''' def __init__(self,side): self.side=side super(square,self).__init__(self.side,self.side) def interior_angle(self): return super(square,self).interior_angle() def area(self): return super(square,self).area() class rhombus(square): pass #Testcases rect= rectangle(5,4) print "The interior angle of the rectangle is" ,rect.interior_angle() sq = square(5) print "The interior angle of the square is" ,sq.interior_angle() rh = rhombus(10) print "The area of the rhombus is" ,rh.area()
true
7e06219cc161ddfb37e3f72d261c9c256ea20414
RAmruthaVignesh/PythonHacks
/MiscPrograms/number_of_letters_in_word.py
354
4.3125
4
#get the word to be counted word_to_count = 'hello_world!' print ("the word is" , word_to_count) # iniliatize the letter count letter_count = 0 #loop through the word for letter in word_to_count: print("the letter", letter, "#number" , letter_count) letter_count = letter_count+1 print ("there are", letter_count, " letters in", word_to_count)
true
0fff4ced9ebbb6852543fb009386e49bee3c352a
AlanDTD/Programming-Statistics
/Week 2/Week 2 exercises - 2.py
909
4.125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 29 20:05:57 2021 @author: aland """ #Loops and input Processing nums = tuple(input("Enter at least 5 numbers separated by commas!")) print(len(nums)) print(nums) sum_num = 0 count = 0 if type(nums) == tuple: #Checks if ithe value is a tuple while len(nums) < 5: #Checks the tuples lengeth is at least 5 print("You do not have enough number") nums = tuple(input("Please try again, at least 5")) #reruns the loop until the right number else: for i in range(len(nums)): #iterates and sums the numbers if type(nums[i]) == int: sum_num = sum_num + nums[i] else: count = count + 1 print("The total sum of the numbers are %d with and %d NaN" %(sum_num, count)) else: print("This is not a tuple") nums = tuple(input("Please use commas to seprate"))
true
ed04c33b0bd58feb0e53c7970ee6ec5de1511481
mvessey/comp110-21f-workspace
/lessons/for_in.py
382
4.46875
4
"""An example of for in syntax.""" names: list[str] = ["Madeline", "Emma", "Nia", "Ahmad"] # example of iterating through names using a while loop print("While output:") i: int = 0 while i < len(names): name: str = names[i] print(name) i += 1 print("for ... in output") # the following for ... in loops is the same as the while loop for name in names: print(name)
true
e5f1266fb875f2d61be8ef72c382cf8cfa10b5de
Sam-Coon/Chapter_8
/challenge2.py
2,575
4.1875
4
#Colaboration on Chapter 8 with Sam Coon and Tyler Kapusniak #2/10/15 class TV(object): def __init__(self, channel = 0, volume = 0): self.__channel = channel self.__volume = volume def choose_channel(self): print( """ Channels: 1. Action 2. Comedy 3. Romance 4. History """) self.__channel = int(input("Choose the channel you want to watch: ")) if self.__channel == 1: print("\nYou are on channel 1, the Action channel.") print("Your volume is on " + str(self.__volume) + ".\n") elif self.__channel == 2: print("\nYou are on channel 2, the Comedy channel.") print("Your volume is on " + str(self.__volume) + ".\n") elif self.__channel == 3: print("\nYou are on channel 3, the Romance channel.") print("Your volume is on " + str(self.__volume) + ".\n") elif self.__channel == 4: print("\nYou are on channel 4, the History channel.") print("Your volume is on " + str(self.__volume) + ".\n") else: print("That is not an available please choose a different channel.") def choose_volume(self): self.__volume = int(input("What do you want to set the volume to?(max 100) ")) if self.__volume <= 100 and self.__volume >= 0: if self.__volume < 50: print("Your volume is at "+ str(self.__volume) + ".") elif self.__volume >= 50 and self.__volume <= 100: print("Your volume is a little loud!") elif self.__volume <= 0 and self.__volume >= 100: print("Can't do that.") print("You're on channel " + str(self.__channel) + ".") def main(): chan = TV() menu = 19 while menu != 0: print( """ 0. Turn off TV 1. Change channel 2. Change volume """) menu = int(input("Enter the number of what you want to do: ")) if menu == 0: print("The TV is off.") elif menu == 1: chan.choose_channel() elif menu == 2: chan.choose_volume() elif menu == "": print("That is not a valid option please try again") else: print("That is not a valid option please try again.") main()
false
78f53c4a130daf34adc2ef48ec7e37be90c0a3b1
klcysn/free_time
/climb_staircase.py
452
4.3125
4
# There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. # For example, if N is 4, then there are 5 unique ways: # 1, 1, 1, 1 # 2, 1, 1 # 1, 2, 1 # 1, 1, 2 # 2, 2 n = int(input("How many steps are there ? : ")) def steps(n): return n if n <= 3 else (steps(n-1) + steps(n-2)) steps(n)
true
94ebe7be385aa68e463c7cdc89bd1e257b9ecdbe
klcysn/free_time
/fizzbuzz.py
799
4.71875
5
# Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz". # If the number is a multiple of 3 the output should be "Fizz". # If the number given is a multiple of 5, the output should be "Buzz". # If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz". # If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below. # The output should always be a string even if it is not a multiple of 3 or 5. def fizzy() : num = int(input("Please enter your number to see FizzBuzz : ")) print("Fizz") if num % 3 == 0 and num % 5 != 0 else print("Buzz")\ if num % 3 != 0 and num % 5 == 0 else print("FizzBuzz") if num % 3 == 0 and num % 5 == 0\ else print(num) fizzy()
true
f82a0f9537ee9ec944bdf9e95ea691a5f06e1bf3
Chetancv19/Python-code-Exp1-55
/Lab2_5.py
701
4.125
4
#Python Program to Check Prime Number #chetan velonde 3019155 a = int(input("Enter the number for checking whether it is prime or not:")) if a > 1: for x in range(2, a): if a % x == 0: print(str(a) + " is not a prime number.") break else: print(str(a) + " is a prime number.") #main princple - every number has it two factors, 1 and the number itself-->then divisibilty test #we initialize the code by checking the value of the input integer... then use range() for checking the divisibility of that #input number #if all the test cases are passed for divisibility check from 2 to the input integer, the number is declared as not a prime number
true
db68815532b75593db14d95d1cc5bfda962102da
jessemcastro/respostas_estrutura_de_decisao
/05.py
798
4.21875
4
#Faça um programa para a leitura de duas notas parciais de um aluno. # O programa deve calcular a média alcançada por aluno e apresentar: #A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; #A mensagem "Reprovado", se a média for menor do que sete; #A mensagem "Aprovado com Distinção", se a média for igual a dez. nota_1 = float(input("Digite sua nota parcial 1")) nota_2 = float(input("Digite sua nota parcial 2")) media = (nota_1+nota_2)/2 if media == 10: print("A média foi ", media, "e o aluno está APROVADO COM DISTINÇÃO") elif media>= 7.0 and media<10: print("A média foi ", media, "e o aluno está APROVADO") elif media< 7.0: print("A média foi ", media, "e o aluno esta REPROVADO") else: print("Notas inválidas")
false
56987b36b796816bbf61315b11be60fc6bed2aee
ljkhpiou/test_2
/ee202/draw.py
642
4.1875
4
import turtle myPen = turtle.Turtle() myPen.shape("arrow") myPen.color("red") #myPen.delay(5) #Set the speed of the turtle #A Procedue to draw any regular polygon with 3 or more sides. def drawPolygon(numberOfsides): exteriorAngle=360/numberOfsides length=2400/numberOfsides myPen.penup() myPen.goto(-length/2,-length/2) myPen.pendown() for i in range(0,numberOfsides): myPen.forward(length) myPen.left(exteriorAngle) # Collect events until released #with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener_m: # listener_m.join() drawPolygon(6)
true
08435281ef189434c121be0f66540830b0e2f006
NectariosK/email-sender
/email_sender.py
2,438
4.375
4
#This piece of code enables one to send emails with python #Useful links below ''' https://www.geeksforgeeks.org/simple-mail-transfer-protocol-smtp/ https://docs.python.org/3/library/email.html#module-email https://docs.python.org/3/library/email.examples.html ''' ''' import smtplib #simple mail transfer protocol (smtp) from email.message import EmailMessage email = EmailMessage() email['from'] = 'NAME' #Name of sender email['to'] = 'EMAIL ADDRESS' #Email address the email will be sent to email['subject'] = 'WINNER' email.set_content('I am a Python Master.') #Well, atleast I think I am :) with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:#hosts port value differ/check your email server smtp.ehlo() #protocol of the method ##here I connected to the server smtp.starttls()#to connect securely to the server ##connected to the server smtp.login('EMAIL ADDRESS', 'PASSWORD')#login to your account smtp.send_message(email)#send the email print('All good boss!') ''' #MORE ON SENDING EMAILS ''' This is an improvement of the program above. Instead of just sending a generic email, I want to customize it to each individual Imagine having a database of users with their email addresses and first names. Ideally I woudld be able to customize the email to each specific person. And that can be done by using an html based email. So I can send text emmails(that just have text) or even something more dynamic like html ''' import smtplib from email.message import EmailMessage from string import Template #making good use of the string.template class from pathlib import Path #this is similar to the os.path and it enables me to access the 'index.html' file(attached to project) html = Template(Path('index.html').read_text()) #read_text() to read the 'index.html' path email = EmailMessage() email['from'] = 'NAME' email['to'] = 'EMAIL ADDRESS' email['subject'] = 'You won 1,000,000 dollars!'#Familiar spam email subject? email.set_content(html.substitute({'name': 'TinTin'}), 'html') ''' Assigned 'name' which is in the 'index.html' file as TinTin-could me anything really. The second parameter 'hmtl' confirms that this is in hmtl ''' with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('EMAIL ADDRESS', 'PASSWORD') smtp.send_message(email) print('All good boss!')
true
e0d3302b71739f6e5210d6c0e377afe0ecb27329
raviMukti/training-python-basic
/src/Dictionary.py
290
4.3125
4
customer = {"name":"Ravi", "umur":25, "pekerjaan":"Programmer"} name = customer["name"] age = customer["umur"] job = customer["pekerjaan"] print(f"Hello My Name is {name} i am {age} years old, and im a {job}") for key in customer: value = customer[key] print(f"{key} : {value}")
false
8d64c60833a9b781e2b4e1243e1e987f08030c41
dwbelliston/python_structures
/generators/example.py
683
4.4375
4
# Remember, an Iterable is just an object capable of returning its members one at a time. # generators are used to generate a series of values # yield is like the return of generator functions # The only other thing yield does is save the "state" of a generator function # A generator is just a special type of iterator # Like iterators, we can get the next value from a generator using next() # for gets values by calling next() implicitly def simple(): yield 1 yield 2 yield 3 og = simple() print(og) print(next(og)) print(next(og)) print(next(og)) def get_primes(number): while True: if is_prime(number): yield number number += 1
true
24d69d7df270af8673070ef7079cbcd3254d9bd7
valakkapeddi/enough_python
/comprehensions_and_generators.py
1,353
4.6875
5
# Comprehension syntax is a readable way of applying transforms to collection - i.e., creating new collections # that are modified versions of the original. This doesn't change the original collection. # For instance, given an original list like the below that contains both ints and strings: a_list = [1, 2, 3, 4, 'a', 'b', 'c'] print(a_list) # You can use a comprehension to filter the list, pulling out only the integers. ints_list = [element for element in a_list if isinstance(element, int)] print(ints_list) # Comprehensions work by running the code inside the []'s for each element in the list - this code gets # executed immediately when the comprehension is declared. For large collections, this may not be what you want. # Generators are sort of like comprehensions in that they can transform collections into other collections, but # unlike comprehensions, the generator expression gets executed only when you access its elements with an iterator # or a for-loop. ints_comprehension = (element for element in a_list if isinstance(element, int)) print(ints_comprehension) # note that it doens't print a list - just the comprehension object. # You can access the elements of a comprehension using an iterator, or a for loop. print(next(ints_comprehension)) print(next(ints_comprehension)) for each in ints_comprehension: print(each)
true
861db59c044985dc0b8e4d71dbff92d480b40ef1
Jones-Nick-93/Class-Work
/Binary Search Python.py
1,284
4.25
4
#Nick Jones #DSC 430 Assignment 7 Time Complexity/Binary Search #I have not given or received any unauthorized assistance on this assignment #YouTube Link import random '''function to do a binary search to see if 2 #s from a given list sum to n''' def binary_search(array, to_search, left, right): # terminating condition if right < left: return -1 # compute mid mid = (left+right)//2 # element found if array[mid] == to_search: return mid # current element is greater than element to search elif array[mid] > to_search: # move left return binary_search(array, to_search, left, mid-1) # current element is less than element to search else: # move right return binary_search(array, to_search, mid + 1, right) # ask user for i i = int(input("Enter i: ")) # ask user for n n = int(input("Enter n: ")) # generate a random list of i items numbers = [] for j in range(i): numbers.append(random.randint(0, 100)) # for every element in numbers for number in numbers: # if there is a element in list which is n-number if binary_search(numbers, n-number, 0, len(numbers)) != -1: print("Found:", number, n-number) exit(0) print("Not found")
true
e41b72f54d45718b0680fbbb7f61a3d0761f527f
Ameen-Samad/number_guesser
/number_ guesser.py
1,426
4.15625
4
import random while True: secret_number = random.randrange(1, 10, 1) limit = 3 tries = 0 has_guessed_correctly = False while not has_guessed_correctly: user_guess = int(input("Guess a number: ")) print(f"You have guessed {user_guess}") limit = limit - 1 tries = tries + 1 print(f"You have {limit} more tries left") difference = secret_number - user_guess difference = abs(difference) print(f"This is your {tries} attempt") if difference == 0: print("You have guessed correctly!") has_guessed_correctly = True exit() else: if limit == 0: print("Game over") print("Do you want to try again?") to_continue = input("yes/no ") if to_continue.strip() == "yes": to_continue = True else: to_continue = False if not to_continue: exit() else: has_guessed_correctly = True if difference <= 2: print("You are very close!") elif difference <= 5: print("Ypu are halfway there!") else: print("You are more than halfway there!") print("You have guessed incorrectly, try again!") print("\n")
true
307e85576dc78d29ecf9077c70776c3498e1a60c
LizaPersonal/personal_exercises
/Programiz/sumOfNaturalNumbers.py
684
4.3125
4
# Python program to find the sum of natural numbers up to n where n is provided by user def loop_2_find_sum(): num = int(input("Enter a number: ")) if num < 0: num = int(input("Enter a positive number")) else: sum = 0 # use while loop to iterate until zero while num > 0: sum += num num -= 1 print("The sum is", sum) def equation_2_find_sum(): num = int(input("Enter a number: ")) if num < 0: num = int(input("Enter a positive number")) else: sum = num * (num + 1) / 2 print("The sum is", sum) if __name__ == '__main__': loop_2_find_sum() equation_2_find_sum()
true
c2c6f67a9b28aed58419e949dd1071d714a4ec92
LizaPersonal/personal_exercises
/Programiz/celsiusFahrenheit.py
512
4.125
4
def celsius2fahrenheit(): celsius = float(input("Enter value in celsius: ")) fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius, fahrenheit)) def fahrenheit2celsius(): fahrenheit = float(input("Enter value in fahrenheit: ")) celsius = (fahrenheit - 32) / 1.8 print('%0.1f degree Fahrenheit is equal to %0.1f degree Celsius' %(fahrenheit, celsius)) if __name__ == '__main__': celsius2fahrenheit() fahrenheit2celsius()
false
35ab0ae28ae798f5fd4317432d082e164b5815ef
zenthiccc/CS5-ELECTIVE
/coding-activities/2ndQ/2.5-recursive-binary-search.py
1,311
4.15625
4
# needle - the item to search for in the collection # haystack - the collection of items # NOTE: assume the haystack is ALWAYS sorted, no need to sort it yourself # the binary search function to be exposed publicly # returns the index if needle is found, returns None if not found def binary_search(needle, haystack): if len(haystack) == 0: return None; else: return _binary_search_rec(needle, haystack, 0, len(haystack) - 1) # the recursive binary search function (not public) # returns the index if needle is found, returns None if not found def _binary_search_rec(needle, haystack, start_index, end_index): # IMPLEMENT! if start_index > end_index: return None else: mid_index = (start_index + end_index) // 2 if needle == haystack[mid_index]: return mid_index elif needle < haystack[mid_index]: return _binary_search_rec(needle, haystack, start_index, mid_index-1) else: return _binary_search_rec(needle, haystack, mid_index+1, end_index) # SAMPLE TESTS: print(binary_search(2, [])) # None print(binary_search(2, [2, 4, 6])) # 0 print(binary_search(2, [1, 2, 3])) # 1 print(binary_search(10, [4, 6, 10, 7, 9])) # 2 print(binary_search(4, [4, 6, 10, 7, 9])) # 0 print(binary_search(8, [3, 4, 6, 7])) # None
true
e3b267c428b62ae5e579a8d9b2446a85443ba889
hyerynn0521/CodePath-SE101
/Week 1/fizzbuzz.py
683
4.46875
4
# # Complete the 'FizzBuzz' function below. # # This function takes in integer n as a parameter # and prints out its value, fizz if n is divisible # by 3, buzz if n divisible by 5, and fizzbuzz # if n is divisible by 3 and 5. # """ Given an input, print all numbers up to and including that input, unless they are divisible by 3, then print "fizz" instead, or if they are divisible by 5, print "buzz". If the number is divisible by both, print "fizzbuzz". """ def FizzBuzz(n): # Write your code here for i in range(1, n+1): if i%3 == 0 and i%5 == 0: print("fizzbuzz") elif i%3 == 0: print("fizz") elif i%5 == 0: print("buzz") else: print(i)
true
52673f2e5435fb7d724b5028a3f64c61398d3c47
hyerynn0521/CodePath-SE101
/Week 5/longest_word.py
816
4.4375
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'longestWord' function below. # # The function is expected to return a STRING. # The function accepts STRING_ARRAY words as parameter. # This function will go through an array of strings, # identify the largest word, and return that word. # ''' given array of strings (that could have multiple words) return the longest word. ''' def longestWord(sentences): # Write your code here longest = "" longest_length = 0 for strings in sentences: words = strings.split(" ") for word in words: if len(word) > longest_length: longest = word longest_length = len(word) return longest if __name__ == '__main__':
true
1f4d1b56a04d8189a8d62af0775eb55e6d1195dc
wangdan377/Test_01
/智神/UI自动化/py/py01/Test_setttle3/lizhi/1_内建函数.py
1,792
4.25
4
''' #内建函数 print('abc'.capitalize()) #把字符串得第一个字母大写 str1= "abc" print(str1.center(6,"1")) #str.center(width,fillchar) fillchar为填充字符,只能一个字符 str2 = "hello python world" print(str2.count("o",5,30)) #"str.count(sub, start=0,end=len(string) ) str3 = 'name.py' suffix = '.py' print(str3.endswith(str3, 0, 20)) # True str1 = 'I\'m\tfine,thank you! ' print(str1) # I'm fine,thank you! print(str1.expandtabs(10)) # I'm fine,thank you! str1 = '小明,小红,小花 ' str2 = '小花' str3 = '小张' print(str1.find(str2, 2), str1.find(str3, 2)) # 6 -1 str1包含str2 print(str2.find(str1, 1)) #st2不包含str1 所以为-1 str1 = input('请输入一个字符串:') print(str1.islower()) str1 = input('请输入一个字符串:') print(str1.isnumeric()) str1 = input('请输入一个字符串:') print(str1.istitle()) str1 = ' 1' str2 = 'abc' print(str1.join(str2)) # a b c ''' ''' 区别:isdigit() isdecimal() isnumeric() isdigit() True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字 False: 汉字数字 Error: 无 isdecimal() True: Unicode数字,,全角数字(双字节) False: 罗马数字,汉字数字 Error: byte数字(单字节) isnumeric() True: Unicode数字,全角数字(双字节),罗马数字,汉字数字 False: 无 Error: byte数字(单字节) ''' """ """ name_score= dict(A=77,B=69,C=88,D=99,E=65,F=61) ''' 假设一个班级没有重名的学生,一个字典记录了班级的学生姓名和分数,找出最高分和最低分 ''' min_score = max(zip(name_score.values(),name_score.keys())) max_score = zip(name_score.values(),name_score.keys()) max_score = min(zip(name_score.values(),name_score.keys())) print(max_score,min_score)
false
48108b1d24bc92d1d52af57f50fed1f7e06b45a9
brivalmar/Project_Euler
/Python/Euler1.py
202
4.125
4
total = 0 endRange = 1000 for x in range(0, endRange): if x % 3 == 0 or x % 5 == 0: total = total + x print "The sum of numbers divisible by 3 and 5 that are less than 1000 is: %d " % total
true
96d1013baf191fdc17c8e134d7e68886803aa689
Vagelis-Prokopiou/python-challenges
/codingbat.com/String-2/end_other.py
719
4.125
4
#!/usr/bin/python3 # @Author: Vagelis Prokopiou # @Email: drz4007@gmail.com # @Date: 2016-04-02 17:33:14 # @Last Modified time: 2016-04-02 17:55:41 # Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. # end_other('Hiabc', 'abc') → True # end_other('AbC', 'HiaBc') → True # end_other('abc', 'abXabc') → True def end_other(a, b): a = a.lower() b = b.lower() if a == b: return True if (a[(-len(b)):] == b) or (b[(-len(a)):] == a): return True else: return False print(end_other('xyz', '12xyz'))
true
cd30d28c86f297f670283b00daefe319032a2e61
Haowen-Zhong/Python-Learning
/May/Tkinter/11.py
685
4.125
4
from tkinter import * root = Tk() Label(root,text="作品:").grid(row = 0, column = 0) Label(root,text="作者:").grid(row = 1, column = 0) e1 = Entry(root) e2 = Entry(root) e1.grid(row = 0,column = 1, padx = 10, pady = 5) e2.grid(row = 1,column = 1, padx = 10, pady=5) def show(): print("作品:《%s》"%e1.get()) print("作者: %s"%e2.get()) Button(root,text="获取信息",width = 10,command = show)\ .grid(row=3,column = 0,sticky=W,padx=10,pady = 5) Button(root,text="退出",width = 10, command = root.quit)\ .grid(row=3,column = 1,sticky=E,padx=10,pady = 5) # e = Entry(root) # e.pack(padx=10,pady=10) # e.delete(0,END) # e.insert(0,"默认文本...") mainloop()
false
dc0aaec53f5565f1396c8cb1907070f4b1f9527d
divyaprakashdp/DSA-with-Python
/merge_sort.py
1,422
4.3125
4
def merge_sort(listToSort): """ sorts a list in descending order Returns a new sordted list """ if len(listToSort) <= 1: return listToSort leftHalf, rightHalf = split(listToSort) left = merge_sort(leftHalf) right = merge_sort(rightHalf) return merge(left, right) def split(listToSplit): """ Divide the unsorted list at midpoint into sublists Return two sublists left and right """ mid = len(listToSplit) // 2 left = listToSplit[:mid] right = listToSplit[mid:] return left, right def merge(leftList, rightList): """ Merges two lists(arrays), sorting them in process :returns a new merged list """ l = [] i = 0 j = 0 while i < len(leftList) and j < len(rightList): if leftList[i] < rightList[j]: l.append(leftList[i]) i += 1 else: l.append(rightList[j]) j += 1 while i < len(leftList): l.append(leftList[i]) i += 1 while j < len(rightList): l.append(rightList[j]) j += 1 return l def verify_Sorted(listToTest): n = len(listToTest) if n == 0 or n == 1: return True else: return listToTest[0] < listToTest[1] and verify_Sorted(listToTest[1:]) aList = [56, 23, 45, 98, 100, 112, 7, 21] a = merge_sort(aList) print(a) print("Is the list sorted:- ", verify_Sorted(a))
true
27e6c78de9ae2f6ff0c91d470bbf175bd9b7e7cc
mashpolo/leetcode_ans
/700/leetcode706/ans.py
1,235
4.125
4
#!/usr/bin/env python # coding=utf-8 """ @desc: @author: Luo.lu @date: 2019-01-09 """ class MyHashMap: def __init__(self): """ Initialize your data structure here. """ self.key = [] self.value = [] def put(self, key, value): """ value will always be non-negative. :type key: int :type value: int :rtype: void """ if key in self.key: index = self.key.index(key) self.value[index] = value else: self.key.append(key) self.value.append(value) def get(self, key): """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int """ if key not in self.key: return -1 else: return self.value[self.key.index(key)] def remove(self, key): """ Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: void """ if key in self.key: self.value.pop(self.key.index(key)) self.key.remove(key)
true
36a29f204892487912c3e60c6766a68a3a23a7b5
iQaiserAbbas/artificial-intelligence
/Lab-01/Lab-01.py
921
4.125
4
__author__ = "Qaiser Abbas" __copyright__ = "Copyright 2020, Artificial Intelligence lab-01" __email__ = "qaiserabbas889@yahoo.com" # Python Program - Calculate Grade of Student print("Please enter 'x' for exit."); print("Enter marks obtained in 5 subjects: "); subject1 = input(); if subject1 == 'x': exit(); else: subject1 = int(subject1); subject2 = int(input()); subject3 = int(input()); subject4 = int(input()); subject5 = int(input()); sum = subject1 + subject2 + subject3 + subject4 + subject5; average = sum/5; if(average>=85 and average<=100): print("Your Grade is A+"); elif(average>=80 and average<85): print("Your Grade is A-"); elif(average>=75 and average<80): print("Your Grade is B+"); elif(average>=71 and average<75): print("Your Grade is B-"); elif(average>=51 and average<=60): print("Your Grade is C+"); else: print("Your Grade is F");
true
f2c41e4f2cbef4b9d331b423a27dd93e259b0329
cardigansquare/codecademy
/learning_python/reverse.py
221
4.1875
4
#codeacademy create function the returns reversed string without using reversed or [::-1] def reverse(text): new_text = "" for c in text: new_text = c + new_text return new_text print reverse("abcd!")
true
556e83e3f35ac103b07d064083e1288293ebc1f9
roseORG/GirlsWhoCode2017
/GWC 2017/story.py
1,154
4.25
4
start = ''' Rihanna is in town for her concert. Help her get to her concert... ''' print(start) done = False left= False right= False while not done: print("She's walking out of the building. Should she take a left or right?") print("Type 'left' to go left or 'right' to go right.") user_input = input() if user_input == "left": print("You decided to go left and ran into the paprazzi.") # finished the story by writing what happens done = True left= True elif user_input == "right": print("You decided to go right and ran into fans.") # finished the story writing what happens done = True right= True else: print("Wrong Option") done = False done = False while left: print("paprazzi are here!") print("Do you want to fight the paprazzi or run?") user_input = input() if user_input == "fight": print("Let's get it!") left = False elif user_input == "run": print("You broke your ankle") left = False else: print("Wrong Option") left= True
true
17dccb7a8621b306bbae0dd58f64c23e17c746c8
shamramchandani/Code
/Python/chapter 3.py
410
4.15625
4
def collatz(num): if num%2 == 0: print(num / 2) return (num / 2) else: print((num *3) +1) return (num *3) +1 try: number = int(input("Please enter a number")) print(number) if number <= 1: print('Please input a number greater than 1') else: while number > 1: number = collatz(number) except (NameError, ValueError): print('Error: Please Enter a Number')
true
a4630580b5fa0a5bc3f480cd7d4ff6ef63ee9640
GajananThenge/Assignment1
/Assignment1.8.py
759
4.375
4
''' Write a Python Program to print the given string in the format specified in the sample output. WE, THE PEOPLE OF INDIA, having solemnly resolved to constitute India into a SOVEREIGN, SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC and to secure to all its citizens Sample Output: WE, THE PEOPLE OF INDIA, having solemnly resolved to constitute India into a SOVEREIGN, ! SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC and to secure to all its citizens: ''' print(r'WE, THE PEOPLE OF INDIA,{0} {1}' r'having solemnly resolved to constitute India into a SOVEREIGN, !' r'{2}{3}{4}SOCIALIST, SECULAR, DEMOCRATIC REPUBLIC{5} {6} {7} and to secure to all its citizens:'. format('\n','\t','\n','\t','\t','\n','\t','\t'))
false
771aafb570437f9bdbd5bc60ea6b4106b22c2541
hperry711/dev-challenge
/chapter2_exercises.py
1,534
4.21875
4
# Exercises for chapter 2: # Name: Hunter Perry # Exercise 2.1. # zipcode = 02492 generates a SyntaxError message because "9" is not within the octal number system. When an integer is lead with a zero in Python it generates the Octal representation for that number. >>> zipcode = 02132 only contains numbers between 0 and 7 therefore generating 1114 as the octal representation. # Exercise 2.2. # Below is the statement in the Python interpreter. >>> 5 5 >>> x = 5 >>> x + 1 6 # Below is the statement modified into a print statement. >>> print 5 5 >>> x = 5 >>> print x + 1 6 # Exercise 2.3. width = 17 height = 12.0 delimiter = '.' # 1. width/2 - Value = 8, Type = Integer # 2. width/2.0 - Value = 8.5, Type = Variable # 3. height/3 - Value = 4, Type = Integer # 4. 1 + 2 * 5 - Value = 11, Type = Integer # 5. delimiter * 5 - Value = '.....', Type = String # Exercise 2. 4. # 1. >>> r = 'radius' >>> v = 'volume' >>> v = 1.333 * pi * 5 ** 3 >>> v 523.4678759043992 # 2. >>> p = 'cover price' >>> d = 'discount' >>> s1 = 'shipping cost' >>> s2 = 'shipping cost for additional copy' >>> n = 'number of copies' >>> t = 'total' >>> p =24.95 >>> p = 24.95 >>> d = .6 >>> s1 = 3.00 >>> s2 = .75 >>> n = 60 >>> t = ((n - 1) * (p * d + s2) + (p * d + s1)) >>> t = ((60 - 1) * (24.95 * .6 + .75) + (24.95 * .6 + 3.00)) >>> t 945.4499999999999 # 3. >>> t = 'return time' >>> t = (412.00 / 60.00) + (8.25 / 60.00 ) + (7.20 / 60.00) + (7.20 / 60.00) + (7.20 / 60.00)+ (8.25 / 60.00 ) >>> t 7.501666666666667 # t = 7 hours 30 minutes 10 seconds
true
1435bd56f23473cad0d00c81ce9434afd56f945a
mylin95/learnpython
/demo/basic/DictAndSet.py
1,494
4.28125
4
# dict # dict全称dictionary,在其他语言中也称为map. # 使用键-值(key-value)存储,具有极快的查找速度。 # dict的键值对存放是 无序的 # dict初始化,取值 dict1 = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(dict1['Michael']) print(dict1) # 增、替换 dict1['Amy'] = 100 print(dict1['Amy']) # 删 delEle = dict1.pop('Amy') print(delEle) print(dict1) # 取值1:不存在key,报错 # print(dict1['Jack']) # 可判断是否存在key print('Amy' in dict1) # 取值2:get()方法 print(dict1.get('Amy')) print(dict1.get('Jack')) #dict取值,为空则返回None print(dict1.get('Jack', -1)) #dict取值,为空则返回默认值 # set # set和dict类似,也是一组key的 集合 # 但不存储value。由于key不能重复,所以,在set中,没有重复的key。 s = set([1, 2, 3]) print(s) s = set([1, 1, 2, 2, 3, 3]) print(s) # 增,重复加没有意义 s.add(4) s.add(4) print(s) # 删,如果不存在key,删除报错 s.remove(4) # 不能获取删除的值 # s.remove(4) # 重复删,报错 print(s) # set可以添加list类型吗? # 不可以,set和dict一样,不可放入可变对象 # list1 = ['a', 'b', 'c'] # s.add(list1) # 报错 # print(s) # 再议不可变对象 # list:可变对象 a = ['c', 'b', 'a'] a.sort() # 对list a排序 print(a) # str:不可变对象 a = 'abc' # a = 'aaa' # 变量明明是可变的啊 # print(a) aChanges = a.replace('a', 'A') print(a) print(aChanges)
false
d18655221e7642cc632f6875310fd3bbd85ae270
Vivek24-learner/Vivekfolder
/Factorial no.py
217
4.125
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 23 07:51:08 2021 @author: HP """ def factorilal(n): return 1 if(n==1 or n==0) else n*factorilal(n-1) n=5 print("The factorial of ",n,"is",factorilal(n))
false
b98fb37acb9ed1b4cbf2d57f516cf650bc515332
Airbomb707/StructuredProgramming2A
/UNIT1/Evaluacion/eval02.py
304
4.15625
4
#Evaluation - Question 7 #Empty array #A length variable could be added for flexible user inputs lst=[] #Storing Values for n in range(3): print("Enter value number ", n+1) num=int(input("> ")) lst.append(num) #Built-in Max() Function in Python print("The largest number was: ", max(lst))
true
d9fad0b9f0dda940f073f6f461fd01c145eb5ba1
ZammadGill/python-practice-tasks
/task8.py
319
4.21875
4
""" Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers """ def squareOddNumber(numbers_list): odd_numbers_square = [n * n for n in numbers_list if n % 2 != 0] print(odd_numbers_square) numbers = [1,2,3,4,5,6,7,8,9] squareOddNumber(numbers)
true
cb611e5efb7fe55ca6e79a43a2eccfffd86b4834
Hrishikeshbele/Competitive-Programming_Python
/minimum swaps 2.py
1,891
4.34375
4
''' You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order. Sample Input 0 4 4 3 1 2 Sample Output 0 3 Explanation 0 Given array After swapping we get After swapping we get After swapping we get So, we need a minimum of swaps to sort the array in ascending order. Explaination: we will create 2 dictonaries. 1 whose keys will be index and values will be current elm at that index and 2nd will have elm values as key and its current position as value. now we will loop through keys of 1st dict and if we find that key of curr elm is not equal to its value which means elm at that pos is not sorted. Loop through dictionary a and whenever key doesn't match value use dictionary to find the current index of correct value. Example 2:3, means index 2 has value 3. But it should actually hold 2 as value. So we use b[2], which gives us the current index of 2 in dictionary a. b[2] gives us 4. Which means 2 is currently in index 4. So we swap index 2 and index 4 in dictionary a and increase the number of swaps count. Then we update dictionary b accordingly. That is if 2:3 is swapped with 3:4 in dictionary a, we will swap 3:2 with 4:3 ''' # Complete the minimumSwaps function below. def minimumSwaps(arr): pos={} val={} ans=0 for i in range(len(arr)): pos[i+1]=arr[i] val[arr[i]]=i+1 for i in pos: if pos[i]!=i: pos[val[i]],val[pos[i]]= pos[i],val[i] ans+=1 return ans print(pos,val) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) res = minimumSwaps(arr) fptr.write(str(res) + '\n') fptr.close()
true
2e3998204f8cf62aeb969ff28cd45b217b480bf0
Hrishikeshbele/Competitive-Programming_Python
/merge2binarytree.py
1,623
4.125
4
''' Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 ''' ''' idea here is check the node of both the trees.If both trees are empty then we return empty. The root value will be t1.val + t2.val if node in both tree are present.The left child will be the merge of t1.left and t2.left, except these trees are empty if the parent is empty similar for right child.we store resultant tree into t1 to save space. ''' class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ #recurtion solution if t1 and t2: t1.val=t1.val+t2.val t1.left=self.mergeTrees(t1.left,t2.left) t1.right=self.mergeTrees(t1.right,t2.right) return t1 else: return t1 or t2
true
224e2c2e3835534e75d9816249aaf06625e70ada
Hrishikeshbele/Competitive-Programming_Python
/Letter Case Permutation.py
1,326
4.1875
4
''' Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. You can return the output in any order. Example 1: Input: S = "a1b2" Output: ["a1b2","a1B2","A1b2","A1B2"] approach: let's see recursion tree for ex. a1b1. at each level we have choices based on which we get new strings. a1b1 / \ (choice on a, whether to take small or capital a) a A | | (choice on 1, note that we have only one choice on 1 i.e to take it ) a1 A1 / \ / \ (choice on b) a1b a1B A1b A1B | | | | (choice on 1) a1b1 a1B1 A1b1 A1B1 (our ans) ''' class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ def rec(s,ans,res): if not s: res.append(ans) return if s[0].isdigit(): rec(s[1:],ans+s[0],res) elif s[0].isalpha(): rec(s[1:],ans+s[0].upper(),res) rec(s[1:],ans+s[0],res) return res return rec(S.lower(),'',[])
true
afab2fe8f815cda591267691c0667a75a6182296
Hrishikeshbele/Competitive-Programming_Python
/Leaf-Similar Trees.py
767
4.25
4
''' Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Input: root1 = [1,2], root2 = [2,2] Output: true approach : we find root nodes of both tree and compare them ''' class Solution(object): def leafSimilar(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: bool """ def leafs(root): if root: if not root.left and not root.right: return [root.val] return leafs(root.left)+leafs(root.right) else: return [] return leafs(root1)==leafs(root2)
true
34b090968b06ee05bd9ebfb94547b9ba63e32b2b
Hrishikeshbele/Competitive-Programming_Python
/Invert the Binary Tree.py
1,079
4.3125
4
''' Given a binary tree, invert the binary tree and return it. Look at the example for more details. Example : Given binary tree 1 / \ 2 3 / \ / \ 4 5 6 7 invert and return 1 / \ 3 2 / \ / \ 7 6 5 4 ''' ### we exchange the left and right child recursively # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return the root node in the tree def invertTree(self, A): if A is None: return #exchanging the childs A.left,A.right=A.right ,A.left self.invertTree(A.left) self.invertTree(A.right) return A ##Invert from leaf up class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
true
9af9bc53e43238029d5c791bbc1cd37d26920e7a
Hrishikeshbele/Competitive-Programming_Python
/Jewels and Stones.py
1,027
4.125
4
''' You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 explaination: a is present 1 time and A is present 2 times in a S string ''' solution1: #brute force class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ count=0 for i in J: for j in S: if i==j: count+=1 return count solution2: #here we are summing up count of each elm of J in S , x.count(y) find count of y in x def numJewelsInStones(self, J, S): return sum(map(S.count, J))
true
23275fede27675ba37f35a8e9117af1395c3aa72
nirajkvinit/pyprac
/recursiveBinarySearch.py
472
4.15625
4
# Binary search using recursion def binarySearchRecursive(arr, low, high, value): mid = low + int((high + low) / 2) if arr[mid] == value: return mid elif arr[mid] < value: return binarySearchRecursive(arr, mid + 1, high, value) else: return binarySearchRecursive(arr, low, mid - 1, value) def binarySearch(arr, value): return binarySearchRecursive(arr, 0, len(arr), value) if __name__ == '__main__': arr = [1,2,3,4,5,6,7,8,9] print(binarySearch(arr, 5))
true
a4c94ed077075a01ef12f176fbccff19ef24a0fc
nirajkvinit/pyprac
/100skills/dictgen.py
386
4.3125
4
''' With a given number n, write a program to generate a dictionary that contains (i, i*i) such that i is an number between 1 and n (both included). and then the program should print the dictionary. ''' def dictgen(): n = int(input("Enter a number: ")) d = dict() for i in range(1, n+1): d[i] = i**i return d if __name__ == "__main__": print(dictgen())
true