blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c910c79076910c0dfd9a57af223335f661dd7396
parhamrp/Python3
/Strings/Reversed string.py
201
4.53125
5
# getting a string from user and revers it backward. reversed_str = input('Enter a string and press enter:') result_str = reversed_str[::-1] print('The reveresd string is:\n',"'",result_str,"'")
true
c9635753262eda04f45dfcefc3b37585939494c0
parhamrp/Python3
/Strings/First letter of the string.py
240
4.1875
4
# getting a string from user and print out # the first letter of the string str1 = input("enter a string and then press enter:") mylist = [letter[0] for letter in str1.split()] print ('the list of the first letter is :', "\n", mylist)
true
8b3050b45e61121ca5065b7e6423ba75b3b108ec
parhamrp/Python3
/List/List element swap (Ascending).py
1,657
4.28125
4
# # Ascending soprt for a list. # def list_element_swap_asc(sample_list): # my_list = sample_list[:] # length = 0 # for element in my_list: # length = length + 1 # unSorted = True # while unSorted: # unSorted = False # for item in range(0, length-1): # if my_list[item] < my_list[item + 1]: # temp_variable = my_list[item] # my_list[item] = my_list[item + 1] # my_list[item + 1] = temp_variable # unSorted = True # return my_list # one_list = [1, 3, 5, 6 ,7 ,78, 34, 2121] # list_element_swap_asc(one_list) # print (one_list) ################### Sample Solution ################### def _merge_and_sort_sample_(a, b): a.extend(b) # Create a new list new_list = [] # Loop until a becomes empty while a: # set an arbitrary element as the minimum # in this case we chose the first index maximum = a[0] # loop through the list and # find the element that is smallest for element in a: if element > maximum: maximum = element # append the smallest element to the new list new_list.append(maximum) # now remove that smallest element from the original list a.remove(maximum) # Ultimately a will become empty # and the loop will end # now return the new list return new_list list1 = [1,2,3,4,5,6,7] list2 = [8,9,10] #and now I just found the best way to use or recall a function:D print(_merge_and_sort_sample_(list1, list2))
true
f77f1a3c81c83b0bc9c8b01e1e1c0db777bd0ee4
ganeshasrinivasd/Unofficial-Work
/Fibonacci.py
309
4.125
4
a = int(input("Till which term you want the Fibonacci series:")) t1=0 t2=1 counter = 0 if a <= 0: print("Hey Man,Enter a positive number") elif a == 1: print(t1) else: while counter < a: print(t1) nextTerm = t1 + t2 t1 = t2 t2 = nextTerm counter += 1
true
f5a2cbd320b04ed3ffe33a86c6743ccdb608abb2
CaioCavalcanti/hackerhank
/data-structures/trees/9_bst_lowest_common_ancestor.py
2,930
4.25
4
""" You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. 2 / \ 1 3 / \ 4 5 \ 6 In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes 4 and 6 as descendants. Complete the function lca in the editor below. It should return a pointer to the lowest common ancestor node of the two values given. lca has the following parameters: - root: a pointer to the root node of a binary search tree - v1: a node.data value - v2: a node.data value Input: The first line contains an integer, n, the number of nodes in the tree. The second line contains n space-separated integers representing node.data values. The third line contains two space-separated integers, v1 and v2. To use the test data, you will have to create the binary search tree yourself. Here on the platform, the tree will be created for you. 6 4 2 3 1 7 6 1 7 Output: Return the a pointer to the node that is the lowest common ancestor of v1 and v2. 4 """ class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): if self.root == None: self.root = Node(val) else: current = self.root while True: if val < current.info: if current.left: current = current.left else: current.left = Node(val) break elif val > current.info: if current.right: current = current.right else: current.right = Node(val) break else: break # Enter your code here. Read input from STDIN. Print output to STDOUT ''' class Node: def __init__(self,info): self.info = info self.left = None self.right = None // this is a node of the tree , which contains info as data, left , right ''' def lca(root, v1, v2): current = root lca = None while not lca: if current.info < v1 and current.info < v2: current = current.right elif current.info > v1 and current.info > v2: current = current.left else: lca = current return lca tree = BinarySearchTree() t = int(input()) arr = list(map(int, input().split())) for i in range(t): tree.create(arr[i]) v = list(map(int, input().split())) ans = lca(tree.root, v[0], v[1]) print(ans.info)
true
f06b240fdd8b7dad82cdc0ded05a481dc76db6df
CaioCavalcanti/hackerhank
/data-structures/trees/7_binary_search_tree_insert.py
1,791
4.21875
4
""" You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function Input: The value to be inserted is 6 on the tree below 4 / \ 2 7 / \ 1 3 Output: Return the root of the binary search tree after inserting the value into the tree 4 / \ 2 7 / \ / 1 3 6 """ class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) def preOrder(root): if root == None: return print(root.info, end=" ") preOrder(root.left) preOrder(root.right) class BinarySearchTree: def __init__(self): self.root = None # Node is defined as # self.left (the left child of the node) # self.right (the right child of the node) # self.info (the value of the node) def insert(self, val): if self.root is None: self.root = Node(val) return current = self.root while True: if current.info > val: if current.left: current = current.left else: current.left = Node(val) break else: if current.right: current = current.right else: current.right = Node(val) break tree = BinarySearchTree() t = int(input()) arr = list(map(int, input().split())) for i in range(t): tree.insert(arr[i]) preOrder(tree.root)
true
73d8ec2942a83527303609f396bc31d3458788e5
odvk/sf-pyfullstack-c02
/mB2-python-02/script-b0208-01.py
1,251
4.40625
4
# B2.8 Модуль random и угадай число на Python # random.randint(а, b) # Возвращает случайное целое число на отрезке [a, b], # то есть полученное число будет больше или равно a и меньше или равно b. # random.random() # Возвращает случайное вещественное число на промежутке [0.0, 1.0), # то есть полученное число будет больше или равно 0.0 и строго меньше 1.0. # random.choice(sequence) # Возвращает случайный элемент непустого контейнера sequence (списка, кортежа, строки). import random alist = [1, 2, 3, 4, 5, 6, 'word'] print(random.choice(alist)) print(random.choice(alist)) print(random.choice(alist)) print(random.choice(alist)) print(random.choice(alist)) print() atuple = ('word', 5, 4, 3, 2, 1) print(random.choice(atuple)) print(random.choice(atuple)) print(random.choice(atuple)) print() astring = 'String is a sequence too, by the way' print(random.choice(astring)) print(random.choice(astring)) print(random.choice(astring)) print(random.choice(astring))
false
b3dc10152621d2c6cd0c75b935065e77f2c6f338
bhartiyadavdel/tathastu_week_of_code
/Day5/program5.py
458
4.1875
4
def odd_even(List): odd=[] even=[] for i in List: if i%2==0: even.append(i) else: odd.append(i) return sorted(odd,reverse=True),sorted(even) size = int(input("Enter the number of items you want to enter: ")) List = [] for i in range(size): List.append(int(input("Enter the element number " + str(i+1) + " in the List: "))) print("odd and even no seperately are :",str(odd_even(List)))
true
7b539b70908dc766815b09d0d93d888e5c38d72c
mattclemons/Python
/ThinkPython/my_pythagorean.py
434
4.1875
4
import math # As an example, suppose you want to find the distance # between two points, given by the coordinates (x1, y1) and (x2, y2). # By the Pythagorean theorem, the formula for distance is: # distance = square root of(x sub2 - x sub1)squared + (y sub2 - y sub1)squared def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result
true
d9b7f3844e2b0548bac7e5eda9c180ad2d38ef5a
luis-martinez/Coursera-Programming-for-Everybody-Python
/Assignments/assignment-5-2.py
938
4.125
4
# 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown. # Desired Output # Invalid input # Maximum is 7 # Minimum is 4 largest = None smallest = None while True: try: n = raw_input("Enter a number: ") num = int(n) if largest is None: largest = num if smallest is None: smallest = num if num < smallest: smallest = num if num > largest: largest = num #print "Minimum iss ", smallest #print "Maximum iss ", largest except ValueError: if n == "done": break else: print "Invalid input" print "Maximum is", largest print "Minimum is", smallest
true
7958360f8d72b90c0c712bc0f6550b263919383f
NikhilPrakashrao/wtfiswronghere
/10_challenge/10_challenge.py
826
4.34375
4
""" We will use this script to teach Python to absolute beginners The script is an example of Fizz-Buzz implemented in Python The FizzBuzz problem: For all integers between 1 and 99 (include both): # print fizz for multiples of 3 # print buzz for multiples of 5 # print fizzbuzz for multiples of 3 and 5" """ from fizzbuzz import fizzbuzz #----START OF SCRIPT if __name__=='__main__': fizzbuzz(100) """a. I didn't get any clue. b. i googled the error"'module' object is not callable" and got the answer. c.I learned that while calling the module we should specify the name. If we just write"import fizzbuzz" from where it should import so if we write "import fizzbuzz from fizzbuzz" it'll come to know that there is a class named as fizzbuzz.(This explaination is according to my understandings)"""
true
68fe48dd1430818dbb1e79c102ae80a15e10355b
tnralakus/SamplePythonProjects
/Notebooks-Udemy/Dictionaries.py
1,181
4.28125
4
# coding: utf-8 # In[1]: # Make a dictionary with {} and : to signify a key and a value my_dict = {'key1':'value1','key2':'value2'} # Call values by their key my_dict['key2'] # In[4]: my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']} #Lets call items from the dictionary my_dict['key3'][0].upper() # In[8]: # Subtract 123 from the value my_dict['key1'] = my_dict['key1'] - 123 my_dict['key1'] # In[9]: my_dict # In[15]: # Set the object equal to itself minus 123 my_dict['key1'] += 123 my_dict['key1'] # In[16]: # Create a new dictionary d = {} # Create a new key through assignment d['animal'] = 'Dog' # Can do this with any object d['answer'] = 42 #Show d # In[18]: # Dictionary nested inside a dictionary nested in side a dictionary d = {'key1':{'nestkey':{'subnestkey':'value'}}} d['key1']['nestkey']['subnestkey'] # In[21]: # Create a typical dictionary d = {'key1':1,'key2':2,'key3':3} # In[22]: d.keys() # In[23]: d.values() # In[24]: d.items() # In[26]: mymap = {1:2,2:3,3:4} # In[28]: mymap[mymap[mymap[1]]] # In[29]: mylist=[1,2,3,4,5,6] mymap[mylist[1]] # In[36]: mylist[1:] mylist[0:] # In[ ]:
true
7686027e203a7f1f111d047737eee3fec202b09f
githubsantonepal/PythonBasic
/phoneNumberInfo_including_plus.py
571
4.28125
4
#!/usr/bin/python import phonenumbers from phonenumbers import geocoder from phonenumbers import carrier #geocoder is used to know the specific location of the number x=input("Enter the phone number with country code") if (phonenumbers.is_valid_number(x))==True: phoneNumber=phonenumbers.parse(x,None) print(phoneNumber) #this will print the country name print(geocoder.description_for_number(phoneNumber, 'en')) #this will print the service provider name print(carrier.name_for_number(phoneNumber, 'en')) else: print("Not a valid number")
true
9b411ef94a62e00519451bf1e98a81cd573e64da
Tomasz-Kluczkowski/Concurrency_course
/semaphores/counting_semaphore.py
2,590
4.1875
4
# Semaphore is a synchronisation primitive with a counter. # The counter represents the number of acquisitions. # We are allowing acquisitions until the counter drops below zero. # So if we start with counter = 2, we allow 2 threads to acquire the semaphore and then we stop it from happening. # This allows setting how many threads at once can hold access some data at the same time. # When threads release the semaphore, the counter is increased by 1 for each thread releasing it. # When the counter goes above zero again, threads may acquire the semaphore again, dropping it by 1 for each aquisition # again until it goes below zero and stops. # CODE EXAMPLE # TICKETING SYSTEM - # NOTE THAT THIS IS INCORRECT!!! THE GLOBAL tickets_available IS NOT PROTECTED BY THE SEMAPHORE! # we allow 4 threads to try and sell the tickets. # Since in reality users can take random time when buying, each 'buy' operation will have random delay added to it. # This will allow for our threads to attempt to acquire the semaphore and sell the tickets. # Each thread will try to sell as many tickets as possible # Until they are sold out. import copy import threading import time import random class TicketSeller(threading.Thread): def __init__(self, semaphore, name: str = None): super().__init__(name=name) self.semaphore = semaphore self.tickets_sold = 0 print(f'Ticket Seller {name} started work\n') def run(self): global tickets_available running = True while running: self.random_delay() self.semaphore.acquire() if tickets_available <= 0: running = False else: self.tickets_sold += 1 tickets_available -= 1 print(f'{self.getName()} sold one ticket, ({tickets_available} left)\n') self.semaphore.release() print(f'{self.getName()} sold {self.tickets_sold} tickets in total\n') @staticmethod def random_delay(): time.sleep(random.randint(0, 4) / 4) semaphore = threading.Semaphore() tickets_available = 2000 # tickets_available_total = copy.deepcopy(tickets_available) number_of_sellers = 2000 sellers = [] for i in range(number_of_sellers): seller = TicketSeller(semaphore=semaphore, name=f'seller {i+1}') seller.start() sellers.append(seller) for seller in sellers: seller.join() tickets_sold = sum([seller.tickets_sold for seller in sellers]) print(f'total number of tickets sold is: {tickets_sold}') # assert tickets_sold == tickets_available_total
true
8217ca20c6a8250367182fe7ac2c111a425d58d5
lcqbit11/algorithms
/book/数据结构-栈和队列-用两个栈实现队列.py
633
4.15625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def append_tail(stack1, stack2): """ :param stack1: stack :param stack2: stack :return: void """ if not stack2: while stack1: temp = stack1.pop() stack2.append(temp) def delete_tail(stack1, stack2): """ :param stack1: stack :param stack2: stack :return: void """ while stack2: tmp = stack2.pop() print(tmp) # print(stack2[-1]) # del stack2[-1] if __name__ == "__main__": stack1 = [1, 2, 3] stack2 = [] append_tail(stack1, stack2) delete_tail(stack1, stack2)
false
b0145c191d1e94050363286d2e118ced8ffd11b9
AbhimanyuSinghPawar/VoiceBankingProject
/SeleniumAutomation/dataTypes_InPython.py
1,699
4.34375
4
# https://journaldev.com/14036/python-data-types #Numeric data types: int, float, complex #String data types: str #Sequence types: list, tuple, range #Binary types: bytes, bytearray, memoryview #Mapping data type: dict #Boolean type: bool #Set data types: set, frozenset #Numeric data types: int, float, complex #create a variable with integer value. a, b, c=100, 10.2345, 100+3j print("The type of variable having value", a, " is ", type(a)) print("The type of variable having value", b, " is ", type(b)) print("The type of variable having value", c, " is ", type(c)) #String data types: str a = "Abhimanyu" b= 'Singh' print(a) print(b) # using ',' to concatenate the two or several strings print(a,"concatenated with",b) #using '+' to concate the two or several strings print(a+" concated with "+b) #Sequence types: list, tuple, range #list of having only integers a= [1,2,3,4,5,6] print(a) #list of having only strings b=["hello","john","reese"] print(b) #list of having both integers and strings c= ["hey","you",1,2,3,"go"] print(c) #index are 0 based. this will print a single character print(c[1]) #this will print "you" in list c #tuple having only integer type of data. a=(1,2,3,4) print(a) #prints the whole tuple #tuple having multiple type of data. b=("hello", 1,2,3,"go") print(b) #prints the whole tuple #index of tuples are also 0 based. print(b[4]) #this prints a single element in a tuple, in this case "go" #Binary types: bytes, bytearray, memoryview #Mapping data type: dict #a sample dictionary variable a = {1:"first name",2:"last name", "age":33} #print value having key=1 print(a[1]) #print value having key=2 print(a[2]) #print value having key="age" print(a["age"])
true
a36f4dea34af77d73b732b6d6b4e507c52cff4c7
andresvenegasr/PythonCourse
/Basic/Loops/ShoppingLists.py
2,569
4.15625
4
import os # Welcome message print('Welcome to the Shopping list') input('Press any key to continue...') os.system('cls') # Define the accepted options options = ['A', 'S', 'Q'] selected_option = None # Define variable to determine if the program must closed exit_list = False # Define variable to store de products shopping_list_items = [] while not exit_list: # Request option to choose while selected_option not in options: selected_option = input('Select an option [A]dd, [S]how, [Q]uit: ') os.system('cls') # Code for add item process if selected_option == 'A': item = input('Enter the product: ') os.system('cls') # If the element is in the list shows a message. if item in shopping_list_items: print('The product is already in the list.') input('Press any key to continue...') # Add the product in the list else: # Add confirmation to add the product confirmation = None while confirmation not in ['Y', 'N']: confirmation = input('Are you sure that you want to add this element? [Y/N]') # If the confirmation is Y the product will be added to the list if confirmation == 'Y': shopping_list_items.append(item) print(f'The {item} item was added successfully') else: print(f'The {item} item was not added to the list') input('Press any key to continue...') # Code for Show option process elif selected_option == 'S': # Validate if the list has items if len(shopping_list_items) > 0: legend = 'The elements in the list are: ' print(legend) print('{}'.format('-' * len(legend))) for items in shopping_list_items: print(f'----> {items}') input('Press any key to continue...') # If the list is empty shows a message. else: print('The list is empty.') input('Press any key to continue...') elif selected_option == 'Q': exit_list = True legend = 'The elements in the list are: ' print(legend) print('{}'.format('-' * len(legend))) for items in shopping_list_items: print(f'----> {items}') print('{}'.format('-' * len(legend))) print('Goodby!!! :)') input('Press any key to continue...') else: print("Invalid option") selected_option = None os.system('cls')
true
99f271a59bb99ef8cfe876ff234ba7a8f76aa9b8
lcastal/think_python_exercises
/chapter5/exercise5.3.py
205
4.15625
4
def is_triangle(a, b, c): if (a > b+c or b > a+c or c > a+b): print ("No") else: print ("Yes") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) is_triangle(a,b,c)
false
e6f6ddeaf3c03b65677e4271c5c1132e36a8df2e
Slugskickass/Teaching_python
/Week 2/6.) Numpy reshaping.py
301
4.25
4
import numpy as np #Build an array array_one = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) #Change its shape new_array = array_one.reshape([1, 9]) print(new_array) new_array = np.reshape(new_array, [1, 9]) print(new_array) print(new_array.reshape([3, 3])) #Transpose the array print(array_one.T)
false
e4113bde1f2562a9c14809393224ccdde4058578
Slugskickass/Teaching_python
/Week 2/5.) Numpy Slicing.py
813
4.28125
4
import numpy as np #Build an array array_one = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(array_one, '\n') # Select a specific part of an array print('The 1 1 element is') print(array_one[1, 1]) # select the center remember python starts indexing at 0 print('The 1 : element is') print(array_one[1, :], '\n') # Print the centre row print('The : 1 element is', '\n') print(array_one[:, 1]) # Print the centre column # Note the : on its own is short for all the indices # The term A:B are the indices between A and B # The last item in an array can be addressed as -1 x = [0, 2] print(array_one[x, :]) # Print the top and bottom rows y = [[0, 0], [1, 2], [2, 2]] print(array_one[y]) array_two = np.random.rand(10, 10) print(array_two) print() print(array_two[3:6, 7:9]) print()
true
76525f9902d34b562fbe7bad58b261d8daa2466b
daks001/py102
/4/Lab4_Act3_PartD.py
1,829
4.15625
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Name: DAKSHIKA SRIVASTAVA # Section: 532 # Assignment: LAB4_ACTIVITY3_PartD # Date: 18 SEPTEMBER 2019 print("This is the optional part of Lab 4, activity 3") #user input for a aval = input("For a, enter 'True' or 'T' or 't' for true and 'False' or 'F' or 'f' for false: ") #assigning boolean values to variable a depending on user input if aval=='True' or aval=='T' or aval=='t': a = True elif aval=='False' or aval=='F' or aval=='f': a = False #user input for b bval = input("For b, enter 'True' or 'T' or 't' for true and 'False' or 'F' or 'f' for false: ") #assigning boolean values to variable b depending on user input if bval=='True' or bval=='T' or bval=='t': b = True elif bval=='False' or bval=='F' or bval=='f': b = False #user input for c cval = input("For c, enter 'True' or 'T' or 't' for true and 'False' or 'F' or 'f' for false: ") #assigning boolean values to variable c depending on user input if cval=='True' or cval=='T' or cval=='t': c = True elif cval=='False' or cval=='F' or cval=='f': c = False #part D val = (not (a and not b) or (not c and b)) and (not b) or (not a and b and not c) or (a and not b) print("First part prints:", str(val)) value = (not ((b or not c) and (not a or not c))) or (not (c or not (b and c))) or (a and not c) and (not a or (a and b and c) or (a and ((b and not c) or (not b)))) print("Second part prints:", str(value)) #after simplification using boolean algebra val = (not b) or ((not a) and b and (not c)) print("First part is still:", str(val)) value = ((not b) and c) or a print("Second part is still:", str(value)) #end of program
true
49e7597f2c3db6badd8f91c8297e6a8b8fdcabf3
alabasterfox/Python-Samples
/Projects/Pythgoras_Demo/pythagoras1.py
583
4.21875
4
# Pythagoras Demo # Author: A. Stevens # Date: 6/3/2021 # Description: Passing value back from the function (see README file) #======================================================================= def is_right_triangle(a, b, c): if (a**2 + b**2 == c**2): return True else: return False side1 = int(input("Please enter the size of side A: ")) side2 = int(input("Please enter the size of side B: ")) side3 = int(input("Please enter the size of side C: ")) if is_right_triangle(side1, side2, side3): print("Right-angled") else: print("Not right-angled")
true
46b6a3d8c5f394a0e517623d21b006c4f3da2138
jacketdembys/genetic-algorithms
/gen-algo-python/guessPassword.py
1,925
4.15625
4
# hello world genetic algorithm program import random import datetime # genes to be used when building the guesses geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!." target = "Hello World!" # generate a guess, a random string from the geneSet def generate_parent(length): genes = [] while len(genes) < length: sampleSize = min(length - len(genes), len(geneSet)) genes.extend(random.sample(geneSet, sampleSize)) return ''.join(genes) # fitness # the fitness value is feedback provided to guide the search toward the solution def get_fitness(guess): return sum(1 for expected, actual in zip(target, guess) if expected == actual) # mutate # the algorithm produces a new guess by mutating the current one def mutate(parent): index = random.randrange(0, len(parent)) childGenes = list(parent) newGene, alternate = random.sample(geneSet, 2) childGenes[index] = alternate \ if newGene == childGenes[index] \ else newGene return ''.join(childGenes) # display what is happening def display(guess): timeDiff = datetime.datetime.now() - startTime fitness = get_fitness(guess) print("{0}\t{1}\t{2}".format(guess, fitness, str(timeDiff))) if __name__ == "__main__": # initialize the best parent to a random sequence of letters and calling the display function random.seed(1000) startTime = datetime.datetime.now() bestParent = generate_parent(len(target)) bestFitness = get_fitness(bestParent) display(bestParent) # generate a guess, request the fitness and keep the guess of the better fitness while True: child = mutate(bestParent) childFitness = get_fitness(child) if bestFitness >= childFitness: continue display(child) if childFitness >= len(bestParent): break bestFitness = childFitness bestParent = child
true
a5ae578dcd78170c65fe8ab05190425f0e5575ec
EsterLan/pycharm_project
/basic_data_structure/advancedSorting.py
2,991
4.125
4
from basicSorting import merge_sorted_list def mergeSort(l: list)-> list: """From Up to Bottom, recursively implement 先递归再排序 """ # 基线条件 if len(l) <= 1: return l else: mid = len(l)//2 # 为何此处不能为mid+1 # 首先len(l)>=2, 不需要考虑前半部分无元素(且:0也取得出元素 # 其次考虑 len(l) = 2时, 会进入四循环,递归无法返回的情况。 lefthalf = mergeSort(l[:mid]) righthalf = mergeSort(l[mid:]) # 合并两有序数组 return merge_sorted_list(lefthalf, righthalf) def merge(l: list, lo:int, mid: int, hi: int)-> list: '对一个数组实行原地归并' i = lo j = mid+1 lux = [0 for i in range(len(l))] for k in range(len(l)): if i > mid: lux[k] = l[j] j += 1 elif j > hi: lux[k] = l[i] i+=1 elif l[j] <l[i]: lux[k] = l[j] j += 1 else: lux[k] = l[i] i += 1 return lux def mergeSortBU(l: list)->list: 'BOTTOM UP' # while sz < pass def quick_sort(l: list, lo: int, hi: int) -> list: """ 选定pivot, 分别对list中小于pivot和大于pivot的值进行排序 先排序再递归 """ # 基线条件 if hi <= lo: return l else: j = partition(l, lo, hi) left_to_j = quick_sort(l, lo, j-1) right_to_j = quick_sort(l, j+1, hi) return l def partition(l:list, lo: int, hi: int) -> int: """ 对l[lo:hi]进行切分,使代切分元素左侧元素均小于pivot,其右侧元素均大于pivot :param l: 待处理list lo: 起始元素的indx hi: 末尾元素的indx :return: 切分元素在列表l中的位置 """ i = lo j = hi while True: v = l[lo] # 切分元素为传入的首个元素 while l[i] <= v and i < hi: # 从左往右搜索, <=pivot的元素跳过,指针右移直至到hi # 有>pivot的元素跳出循环 i += 1 while l[j] >= v and j > lo: # 从hi开始往左搜索, >= pivot的元素跳过,指针左移直到lo # 有<pivot的元素,跳出循环 j -= 1 if i >= j: # 指针相遇时 break出整个循环 break # 将pivot两侧的元素交换 exch(l, i, j) # pivot与j处元素交换 exch(l, lo, j) # 返回切分元素的索引 return j def nth_element(l:list, beg:int, end: int, k:int): if beg == end: return l[beg] pivot_index = partition(l, beg, end) if k< pivot_index+1: return nth_element(l, beg, pivot_index-1,k) elif k > pivot_index+1: return nth_element(l, pivot_index+1, end, k-pivot_index) else: return l[pivot_index] def exch(l: list, i: int, j: int): l[i], l[j] = l[j], l[i]
false
a5f7e4d633c219c1ec91cbed705b304c2b2c3c96
firefighter-eric/Algorithm
/sort.py
740
4.125
4
def merge(arr1: list, arr2: list) -> list: """merge sorted array Args: arr1 (list): array 1 arr2 (list): array 2 Returns: list: merged array """ arr = [] i1 = i2 = 0 while i1 < len(arr1) and i2 < len(arr2): if arr1[i1] <= arr2[i2]: arr.append(arr1[i1]) i1 += 1 else: arr.append(arr2[i2]) i2 += 1 arr += arr1[i1:] arr += arr2[i2:] return arr def merge_sort(array) -> list: l = len(array) if l == 0 or l == 1: return array return merge(merge_sort(array[:l//2]), merge_sort(array[l//2:])) if __name__ == '__main__': array = [2, 3, 45, 653, 26, 2, 4, 6, 7] print(merge_sort(array))
false
649bf4bb93bd7cf951f29dad140a16fad0199e13
dgyarmati/code_examples
/src/python_iterators/infinite_iterator_implementation.py
608
4.375
4
import random """ An iterator can also return an infinite amount of values if we leave out raising the StopIteration exception. """ class RandomNumberIterator: # think of this as a special kind of list that can only contain the seven dwarves def __init__(self, min, max): self.min = min self.max = max def __iter__(self): return self def __next__(self): return random.randint(self.min, self.max) random_number_iterator = RandomNumberIterator(0, 2783684) # this will produce an infinite number of elements for num in random_number_iterator: print(num)
true
a1fc8d2a40f139b25f50ef38d98db5f00011cc6b
kunalvirdi/Blend_with_python
/BMI.py
307
4.375
4
"""this is a bmi calculator""" print("this is a bmi calculator") name=str(input("enter your name")) mass=int(input("enter your weight in kg's")) height=float(input("enter your height in meters")) bmi=mass/(height*height) print(f'hey {name},your heightis {height},yourweight is {mass} and your BMI is {bmi}')
true
1d955724ef1b38916966f9f23789ca81228d7966
kunalvirdi/Blend_with_python
/Day 2 BMI Assignment/Jatin Tanwar/BMI _ Jatin Tanwar_201154.py
420
4.4375
4
""" This Is A BMI Calculator, Used To Calculate body mass index and used to predict health risks """ print("This is a BMI Calculator") Name = str(input("Enter Your Name")) mass = int(input("Enter Your Weight In KiloGrams")) height = float(input("Enter Your Height In Metres")) # Formula Starts Here Bmi = mass/(height*height) print(f"Hey {Name}, Your height is {height} , Your Mass Is {mass}, Your Bmi is {Bmi}")
true
1902ae4336af7e37c5153d9654a058ab605af88f
saguu6/python_learning
/control_flow.py
1,899
4.21875
4
# #operators # # 2 > 1 # # 1 < 2 # # 2 >= 1 # # 1 <= 2 # # 1 != 2 # # #there is not data type equality in python i.e === # # 1 == 1 # return true # # 1 == "1" #returns false #logical orperators # in python logical operators are 'and' and 'or' keywords # (1 > 2) and (2 > 3) # # (1 > 2) or (2 > 3) #if statments #in python therte is no need of brackets after if statements, it will get to know the code block by indentation if 1 < 2: #colon indicates the code block print("true") if 1 > 2: print("true") else: print("false") #else if is written in shortcut form as "elif" if 2 < 1: print("if statements") elif 2 == 2: print("elif statement") else: print("else statement") #loops seq = [1,2,3,4,5,6] # item name cane be any name for item in seq: print item for abc in seq: print abc #for loop in dictionary d = {"key1":1,"key2":2} for item in d: print item #goin to print the keys -- > output is key1 key2 for k in d: print(k) print(d[k]) #prints the values #looping tuples inside the lists mypairs = [(1,2),(3,4),(5,6)] for item in mypairs: print (item) #prints the tuples (1,2),(3,4),(5,6) #unpacking the tuples for t1,t2 in mypairs: print(t1) print(t2) #output 1 2 3 4 5 6 #while loops i = 1 while i < 5 : print ("i is : {}".format(i) ) i = i + 1 #RANGE FUNCTIONS #to get the value from 1 to 5 #[1,2,3,4,5] range(1,5) #output [1, 2, 3, 4] not including 5 list1=list(range(0,5)) print(list1) #output [0, 1, 2, 3, 4] list_even = list(range(0,20,3)) print(list_even) #output [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] without including 20 for a in range(10): print(a) #output prints 0 to 9 not including 10 #list comprehension x =[1,2,3,4] out = [] for num in x: out.append(num) #appends all the number into out print(out) out = [num for num in x] #one more way of for loop print out
false
d0dbb6a30b3ccbfc370fcdf7a0de1382b71ce8ca
liuhao940826/python-demo
/List的练习2.py
856
4.4375
4
# List(列表) 是 Python 中使用最频繁的数据类型。 # # 列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。 # # 列表是写在方括号 [] 之间、用逗号分隔开的元素列表。 # # 和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表。 # # 列表截取的语法格式如下 list = ['abcd', 786, 2.23, 'runoob', 70.2] list2 = ['q', 'w', 'e', 'r', 't'] if 'abcd' not in list: print("进来") print(list.__contains__('abcd')) first = enumerate(list2) print("first:{}".format(first)) #集合下标遍历 for i, value in enumerate(list): print("下标:{},值:{}".format(i, value)) print("list2:{},值:{}".format(i,list2[i]))
false
d5b467b0ac55b7c77e3fdac929caff3b60600cd9
sivamatsa/Django-Framwork
/studentinfo.py
646
4.125
4
class Student: #constructor def __init__(self,name,rollno): self.name = name self.rollno = rollno def display(self): return {'name': self.name,'rollno':self.rollno} obj = Student('Siva',513) print(obj.display()) ''' Inheritance : Getting Properties of one class to another class Syntax: class subClass(parentClass1,[parentClass2,..]): functions class sub(): ''' class Cse: def student(): return 'I am Cse Student' class Ece: def student(): return 'I am Ece Student' obj1 = Cse print(obj1.student()) obj2 = Ece print(obj2.student())
true
c6e2ba0958e0554c09f65c88f7ae328801e958fc
sfilata/gitskills
/Python/Warship.py
2,261
4.15625
4
from random import randint board = [] limit = 7 number = 2 round = 7 for x in range(0, limit): board.append(["O"] * limit) def print_board(board): for row in board: print (" ".join(row)) print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) # ship_row = random_row(board) # ship_col = random_col(board) ship_location = [] for i in range(number): ship_location.append([random_row(board), random_col(board)]) # ship_row.append(random_row(board)) # ship_col.append(random_col(board)) # print ship_row # print ship_col # print ship_location def instruction(guess_location, ship_location): row_idea = '' col_idea = '' result = '' for i in range(number): if (guess_location[0] > ship_location[i][0]): row_idea = 'North' if (guess_location[0] < ship_location[i][0]): row_idea = 'South' if (guess_location[1] > ship_location[i][1]): col_idea = 'West' if (guess_location[1] < ship_location[i][1]): col_idea = 'East' result += 'There is a WarShip is at Your ' + row_idea + col_idea + '\n' return result for turn in range(round): print ("Turn", turn + 1) guess_row = int(input("Guess Row: ")) - 1 guess_col = int(input("Guess Col: ")) - 1 # Write your code below! guess_location = [guess_row, guess_col] if (guess_location in ship_location): number -= 1 if (number == 0): board[guess_row][guess_col] = 'Y' print('Congratulations! You sank all of the battleships!') print_board(board) break else: print('You sank one battleship!') board[guess_row][guess_col] = 'Y' ship_location.remove(guess_location) print_board(board) else: if(guess_row not in range(limit) or guess_col not in range(limit)): print('Oops, that\'s not even in the ocean.') elif (board[guess_row][guess_col] == 'X'): print('You guessed that one already.') else: print('You missed my battleship!') board[guess_row][guess_col] = 'X' print_board(board) print(instruction(guess_location, ship_location)) if(turn == 3): print('Game Over')
false
1e91948812d335f9e9ecbb903f3958900ba24801
CenturyHSProgramming/volume-of-a-cone-calculator-bertb537
/ConeVolumeCalculator.py
785
4.1875
4
# ConeVolumeCalculator.py # Your job is to write a function in ConeVolumeCalculator.py (call # it **calculateConeVolume()** that calculates the volume of a cone # factor based on the Volume Calculator # Calculator.net (http://www.calculator.net/volume-calculator.html) import math # Define Function below # be sure to return an integer def calculateConeVolume(r, h) : volume = 1/3*math.pi*r**2*h volume = round(volume, 2) return volume if __name__ == '__main__': print("Hello user.") radius = float(input("What is the radius of your cone?")) height = float(input("What is the height of your cone?")) volume = calculateConeVolume(radius, height) volume = round(volume, 2) print("The volume of your cone is " + str(volume))
true
8c25ba7593329dc48fd814305f4714a9c6940d8b
CaptCorpMURICA/TrainingClasses
/Udemy/TimBuchalka/CompletePythonMasterclass/ContinueBreakElse/continueBreak.py
1,962
4.28125
4
""" Author: CaptCorpMURICA Project: ContinueBreakElse File: continueBreak.py Creation Date: 12/1/2017, 1:35 PM Description: How to implement a Continue and Break into your Python program Use CONTINUE to advance to next iterator in loop. Use BREAK to end current code block and advance to next code block. CONTINUE and BREAK are used to improve processing efficiency. """ # Use CONTINUE to stop processing the block when TRUE and move to the next iterator shopping_list = ["milk", "pasta", "eggs", "spam", "bread", "rice"] for item in shopping_list: if item.lower() == "spam": print("I will never buy {}.".format(item)) continue print("You need to buy {}.".format(item)) print("===============") # Use BREAK to stop the loop completely when TRUE shopping_list = ["milk", "pasta", "eggs", "spam", "bread", "rice"] for item in shopping_list: if item.lower() == "spam": print("I will never buy {}.".format(item)) print("I'm done here.") break print("You need to buy {}.".format(item)) print("===============") # Use a BREAK to end a search program once match is found. Improves efficiency. meal = ["egg", "bacon", "spam", "sausages"] nasty_food_item = "" for item in meal: if item.lower() == "spam": nasty_food_item = item break if nasty_food_item: print("Can't I have anything without spam in it?") print("===============") # Else for loops is executed only when the loop runs to the end. No breaks allowed. meal = ["egg", "bacon", "pancakes", "sausages"] nasty_food_item = "" for item in meal: if item.lower() == "spam": nasty_food_item = item break else: print("I'll have a plate of that, then, please.") if nasty_food_item: print("Can't I have anything without spam in it?")
true
d9854ab5d105903683573cc76b30a25470b3d5ff
CaptCorpMURICA/TrainingClasses
/Udemy/TimBuchalka/CompletePythonMasterclass/FileIO/shelveExample.py
2,987
4.1875
4
""" Author: CaptCorpMURICA File: shelveExample.py Creation Date: 11/2/2018, 1:11 PM Description: Learn about the shelve module for storing large amounts of data with key/value pairs. """ # URGENT: Loading a shelve file can execute code just like pickles. # Shelve object requires a string for a key. A dictionary can accept any immutable object as a key. import shelve with shelve.open('ShelfTest') as fruit: fruit['orange'] = 'a sweet, orange, citrus fruit' fruit['apple'] = 'good for making cider' fruit['lemon'] = 'a sour, yellow citrus fruit' fruit['grape'] = 'a small, sweet fruit growing in bunches' fruit['lime'] = 'a sour, green cirtus fruit' print(fruit['lemon']) print(fruit['grape']) print(fruit) print("=" * 50) # Keep shelf open. Requires the shelf to be closed manually. fruit = shelve.open('ShelfTest') fruit['orange'] = 'a sweet, orange, citrus fruit' fruit['apple'] = 'good for making cider' fruit['lemon'] = 'a sour, yellow citrus fruit' fruit['grape'] = 'a small, sweet fruit growing in bunches' fruit['lime'] = 'a sour, green citrus fruit' print(fruit['lemon']) print(fruit['grape']) print(fruit['lime']) print("-" * 40) # Assign a new value to a key fruit['lime'] = 'great with tequila' for snack in fruit: print(snack + ': ' + fruit[snack]) print("=" * 50) while True: shelf_key = input("Please enter a fruit: ") if shelf_key.lower() == "quit": break description = fruit.get(shelf_key, "We don't have a " + shelf_key) print(description) print("-" * 40) # Alternative method while True: dict_key = input("Please enter a fruit: ") if dict_key.lower() == "quit": break if dict_key in fruit: description = fruit[dict_key] print(description) else: print("We don't have a " + dict_key) print("=" * 50) # Keys are unsorted and order is undefined for f in fruit: print(f + " - " + fruit[f]) print("-" * 40) # Create sorted list first ordered_keys = list(fruit.keys()) ordered_keys.sort() for f in ordered_keys: print(f + " - " + fruit[f]) print("=" * 50) # Return values and items stored in the shelf for v in fruit.values(): print(v) print("-" * 40) print(fruit.values()) print("-" * 40) for f in fruit.items(): print(f) print("-" * 40) print(fruit.items()) # Shelf needs to be closed fruit.close() print("=" * 50) print(fruit) print("=" * 50) books = shelve.open("book") books["recipes"] = {"blt": ["bacon", "lettuce", "tomato", "bread"], "beans_on_toast": ["beans", "bread"], "scrambled_eggs": ["eggs", "butter", "milk"], "soup": ["tin of soup"], "pasta": ["pasta", "cheese"]} books["maintenance"] = {"stuck": ["oil"], "loose": ["gaffer tape"]} print(books["recipes"]["soup"]) print(books["recipes"]["scrambled_eggs"]) print(books["maintenance"]["loose"]) books.close()
true
84f7e9456f49ccad7c6918cf4e1fe88f5df45c6b
CaptCorpMURICA/TrainingClasses
/Udemy/TimBuchalka/CompletePythonMasterclass/IntroToLists/lists.py
895
4.28125
4
""" Author: CaptCorpMURICA Project: IntroToLists File: lists.py Creation Date: 12/4/2017, 1:11 PM Description: Introduction to Lists in Python """ # Using the count function ipAddress = input("Please enter an IP address: ") print("The number of periods in the IP address is {}.".format(ipAddress.count("."))) print("==============") # Add an additional entry to a list parrot_list = ["non pinin'", "no more", "a stiff", "bereft of life"] parrot_list.append("A Norwegian Blue") for state in parrot_list: print("This parrot is " + state) print("==============") # Concatenate two lists even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = even + odd print(numbers) # Unsorted print(sorted(numbers)) # Sorted numbers.sort() print(numbers) # Sorted numbers_in_order = sorted(numbers) print(numbers_in_order)
true
999d38199c0044be7f0a6059905f232abf3b8610
marinov98/fall-127-proof-of-work
/Python_127_proof_winter/commach04.py
655
4.40625
4
##Comma code problem chapter 4 #Say you have a list value like this: #spam = ['apples', 'bananas', 'tofu', 'cats'] #Write a function that takes a list value as an argument and returns #a string with all the items separated by a comma and a space, with and #inserted before the last item. For example, passing the previous spam list to #the function would return 'apples, bananas, tofu, and cats'. But your function should be able #to work with any list value passed to it. spam=['Beckham','Rooney','Ronaldo','Messi','Neymar'] def Comma(spam): n='' for i in spam[0:-1]: n+=i+',' return n+'and'+' '+spam[-1] Comma(spam)
true
e0771388e5b17c7e6438c0c83cc4bc2bdf668e2b
Jcnovoa1/tallerIntegradorPythonUNLZ
/GuiaEjercicios/Ejercicio3.5.py
529
4.46875
4
""" Ejercicio 3.5. Escribir un programa que le pida al usuario que ingrese un número por teclado, lo eleve al cubo y muestre el resultado por pantalla. El programa deberá seguir funcionando hasta que el usuario ingrese el número cero. """ def cuboNumero(numero): return numero**3 while True: print("Ingresa Cero para salir") numeroIngresado = int(input("Ingrese un Número: ")) if numeroIngresado != 0: print("El Cubo del Numero Ingresado es: ", cuboNumero(numeroIngresado)) else: break
false
64baa68c6fe4d9efbc2763024e78afd49f47b428
kevalrathod/Python-Learning-Practice
/reverse_array.py
319
4.15625
4
def reverse_array(input_array): size=len(input_array) loop_val = size//2 index=size-1 for i in range(0,loop_val): temp=input_array[index] input_array[index]= input_array[i] input_array[i]=temp index=index-1 print(input_array) print("Got the reverse_array") input_array=[1,2,3] reverse_array(input_array)
true
91902a03cb64195eeb83b4e97e8d1404f54edcba
kevalrathod/Python-Learning-Practice
/other_Exmple/delete_occurence.py
369
4.28125
4
# Given a string as your input, delete any reoccurring # character, and return the new string. def delete_characters(string): char_seen = set() output_string = '' for char in string: if char not in char_seen: char_seen.add(char) output_string += char print(output_string) string='abbccdfet' delete_characters(string)
true
62d02592c5412449fa6b5f4f5de95917877c4992
kevalrathod/Python-Learning-Practice
/palindrom.py
266
4.28125
4
def palindrom(string): length=len(string) for i in range(0,length//2): if string[i]!=string[length-i-1]: return False return True string="wowow" if palindrom(string): print("yes, input string is palindrom") else: print("No,Input string is not palindrom")
true
19c198d1d10a2ff36b274d62c110e9d8c661b6aa
PamsterHamster/prg105
/5.2AutomobileCosts.py
2,085
4.4375
4
# Write Rubric here # Write a program that asks the user to enter monthly costs from his/her automobile: loan payment, insurance, gas # and maintenance. Display the total monthly cost of these expenses and total annual cost of these expenses. def askForExpenses(): monthlyLoanPayment = float( input("How much do you pay for your monthly loan?: " ) ) monthlyInsurancePayment = float( input("How much do you pay for your monthly insurance?: " ) ) monthlyGasPayment = float( input("How much do you pay for your monthly gas?: " ) ) monthlyMaintenancePayment = float( input("How much do you pay for your monthly maintenance?: " ) ) return monthlyLoanPayment, monthlyInsurancePayment, monthlyGasPayment, monthlyMaintenancePayment def calculateTotalMonthlyCost( payment1, payment2, payment3, payment4 ): totalMonthlyCost = payment1 + payment2 + payment3 + payment4 return totalMonthlyCost def calculateTotalAnnualCost( totalMonthlyCost ): TotalAnnualCost = totalMonthlyCost * 12 return TotalAnnualCost def printDetails( totalMonthlyCost, TotalAnnualCost ): print( "Your total monthly cost is $" + format( totalMonthlyCost, ",.2f") + \ "\nYour total annual cost is $" + format( TotalAnnualCost, ",.2f") ) def main(): monthlyLoanPayment, monthlyInsurance Payment, monthlyGasPayment, monthlyMainenancePayment = askForExpenses(): totalMonthlyCost = calculateTotalMonthlyCost( monthlyLoanPayment, monthlyInsurance Payment, monthlyGasPayment, monthlyMaintenancePayment ): TotalAnnualCost = calculateTotalAnnualCost( totalMonthlyCost ) printDetails( totalMonthlyCost, TotalAnnualCost ) main() """ # Variables--make all money ones floats monthly loan insurance Gas maintenance monthly_cost # Steps Get user input calculate total print formatted total call yearly, pass monthly_cost # Variables --argument variable of month_total yearly calculate yearly cost (multiply by 12 months) Display main() # Group steps into logical functions (Data entry together, calculations all together) """
true
12965a0bf08dd2c72a608729671ed05411fb8015
thecodingsophist/madlibs
/madlibs.py
1,475
4.3125
4
#features: have a story, have inputs, replace blanks with inputs #ex: Once upon a time, there was an __________ (reptile). # THIS CAN BE USED LATER... # def begins_with_vowel(word): # if word.lower()[0] == 'a' or word.lower()[0] == 'e' or word.lower()[0] == 'i' or word.lower()[0] == 'o' or word.lower()[0] == "u": # return True # else: # return False def mad_libs(): print("Welcome to the game of Mad Libs! Where you will build your vocabulary and be entertained for hours!") #a list of nouns, verbs, adjectives used in the GAME OF MADLIBS! reptile = input("REPTILE: ") adjective = input("ADJECTIVE: ") number = input("NUMBER: ") noun = input("PLURAL NOUN: ") adverb = input("ADVERB: ") #REFACTORED INTO A FUNCTION CALLED begins_with_vowel # if reptile.lower()[0] == 'a' or reptile.lower()[0] == 'e' or reptile.lower()[0] == 'i' or reptile.lower()[0] == 'o' or reptile.lower()[0] == "u": # print("Once upon a time, there was an %s" % (reptile)) # else: # print("Once upon a time, there was a %s" % (reptile)) # if begins_with_vowel(reptile): print("Once upon a time, there was a(n) %s. It was a very %s %s. It had %s %s. It lived %s ever after." %(reptile, adjective, reptile, str(number), noun, adverb)) # else: # print("Once upon a time, there was a %s." %(reptile)) def test(): mad_libs() test() #python modules #system modules #was the input a noun?
true
a0edfc65a93e9d99cd7544a1fa611278e152ea54
ucsb-cs8-m17/Lecture3_0810
/turtle_demo_06.py
788
4.25
4
import turtle t = turtle.Turtle() # Invoke the shape method, # passing the string "turtle" # as a parameter t.shape("turtle") # A better approach... now we can draw many Ts # But this is very repetitive.. it works, but...??!?!? def drawT(): ''' draw a T assume turtle facing east (0), and leave it facing east assume pen is down no assumptions about position. ''' t.forward (50) t.backward (25) t.right (90) t.forward (100) t.left(90) # REFACTORED... # put the part that's the same into the function def # put the parts that's different as parameter to function call def moveToNewPlace(x): t.up() t.goto(x,0) t.down() drawT() moveToNewPlace(-200) moveToNewPlace(-100) moveToNewPlace(0) moveToNewPlace(100) moveToNewPlace(200)
true
e92d5cb7a4222967878c8eb73a1b9f200a5fdad5
mudit-chopra/Python
/project_euler/problem_01/sol6.py
525
4.375
4
''' Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' from __future__ import print_function try: raw_input # Python 2 except NameError: raw_input = input # Python 3 '''store multiples of 3 and 5 in a set and then add''' n = int(input().strip()) l = set() x = 3 y = 5 while(x<n): l.add(x) x+=3 while(y<n): l.add(y) y+=5 print(sum(l))
true
12add586facb9692575b8e424e8d29fe9c908d78
henry-aw/CU_FinTech_ClassActivities
/M2 Financial Applications with Python/M2, Class 1/01_Stu_Python_Code_Drills/Unsolved/04-condition-control-flow-01/Unsolved/condition-control-flow-01.py
1,287
4.21875
4
# Declare a variable budget and assign it a value of 5000. budget = # YOUR CODE HERE! # Declare a variable rent_cost and assign it a value of 1500. rent_cost = # YOUR CODE HERE! # Declare a variable utilities_cost and assign it a value of 150. utilities_cost = # YOUR CODE HERE! # Declare a variable food_cost and assign it a value of 250. food_cost = # YOUR CODE HERE! # Declare a variable transportation_cost and assign it a value of 350. transportation_cost = # YOUR CODE HERE! # Declare a variable computer_cost and assign it a value of 2000. computer_cost = # YOUR CODE HERE! # Declare a variable called total_cost that takes the sum of all costs above (excluding budget). # YOUR CODE HERE! # Write an if statement that checks whether the sum of all our costs is within the budget. # If so, print "You're total cost is " concatenated with the `total_cost` variable. # Else, print "You're over budget by " concatenated with the difference between `budget` and `total_cost`. # YOUR CODE HERE! # Write an if statement that checks whether the rent_cost is larger than the sum of the `utilities_cost`, `food_cost`, # and `transportation_cost`. If so, print a string that says "The rent is too darn high!". # Else, print a string that says "Ahhh just right!" # YOUR CODE HERE!
true
2ba7b3d44ccf93dffd85058f0bf36eb5de0291ba
henry-aw/CU_FinTech_ClassActivities
/M1 Financial Programming with Python/M1, Class 1/06_Stu_Working_with_Dictionaries/Unsolved/dictionaries.py
1,577
4.375
4
""" Async Content: M1_L02: Dictionaries- Skill Drills Scripts designed for practice with designing and working with Python dictionaries. """ # Working with Python Dictionaries # Following is Python Dictionary containing student loan information. # Notice all keys are defined as strings, but the values are declared in a variety of data types. student_loan_information_aj = { "student_name": "Amy Johnson", "university": "Yale", "academic_year": "2015_2016", "laon_amount": 45000, "duration_years": 10, "payments_started": False, } # Using the student_loan_information_aj dictionary provided, complete the following instructions: # Print the original 'student_loan_information_aj' dictionary print("The original student loan profile:", student_loan_information_aj) # Our student's name was spelled incorrectly. # @TODO Update the value of the `student_name' key to `Amy Johnston`. # @TODO Be sure to print the dictionary so that you know your changes are working. # HINT - Remember, bracket notation. # Every loan should have an interest rate associated with its information. # @TODO Add a key called 'interest_rate' and assign it a value of 3.5 percent (or 0.035). # @TODO Print the dictionary so that you know your changes are working. # Reviewing the information, it appears that the key for 'loan_amount' has been spelled incorrectly. # @TODO Delete the existing key:value pair. # @TODO Add a new key:value pair with the correct spelling. You can use the same amount of 45000. # @TODO Print the dictionary so that you know your changes are working.
true
8b16673dfc5f9988adc405decd84b50c0a450aa4
carlbergh/learnPython
/ex15.py
592
4.15625
4
from sys import argv # Unpack the argunments to Variables script, filename = argv # Set default prompt prompt = ('> ') # Assign file to 'txt' variable txt = open(filename) print "Here's your file %r: " % filename # Print file content print txt.read() print "Closing the file %s" % filename txt.close() print "Type the filename again:" # Store new file path to new variable file_again = raw_input(prompt) # Open the new file path txt_again = open(file_again) # Print the content of the prompted file print txt_again.read() print "Closing the file %s" % file_again txt_again.close()
true
a22c5a2bc7c33abc87dbe78b47868f4dbff52c85
Techaddi/unit_conversion
/time_unites_ino minutes.py
1,274
4.34375
4
print(" The programe to convert all unites of time into minuts\n") print (" After giving the value please specify the Unit like 'day,week,hour,year'\n") def cal (): value = int (input("Enter a value in Numbers to convert in minutes : ")) unit = input("Enter Unit name : ") if unit =='day': value_minutes= (value*24)*60 print(value_minutes,"minutes") cal() elif unit=='hour': value_minutes=value*60 print(value_minutes,"minutes") cal() elif unit=='week': value_minutes=(value*7)*60 print(value_minutes,"minutes") cal() elif unit=='year': leap_value=input("Is there any leap year please Give input in only 'yes'or'no' : ") if leap_value=='yes': leap_year= int(input("how many leap year in the ginven years : ")) non_leap_year=value - leap_year value_minutes=(((leap_year*366)*24)*60)+(((non_leap_year*365)*24)*60) print(value_minutes, 'minutes') else: value_minutes= ((value*365)*24)*60 print(value_minutes,"minutes") cal() else: print("wrong input try again..") cal() cal()
true
fe9264b8dab6b3ac9ddb82d0f3e1bfa631d5069b
LucasAraujoBR/Python-Language
/pythonProject/Intermediate Pyhon/Funcoes.py
864
4.3125
4
''' Funções - def em python args and kwargs ''' def funcao(): print('Hello world!') def funcao1(msg,nome): print(msg, nome) funcao() funcao() funcao() funcao() funcao1('Olá','Lucas') funcao1(nome='Olá',msg='Lucas') def func(msg='mensagem',nome='nome'): return f'{msg} {nome}' aux = func() print(aux) # sempre que eu seto um argumento padrão os próximos tambem tem que ser padrão ex def gh(a1,a2=2,a3=3): print(a1,a2,a3) gh('valor') def tuple(*args): print(args) args = list(args) #Mudando de tupla para list args[0] = 'Lucas' print(args) print(args[0]) print(args[3]) print(len(args)) tuple(1,2,3,4,5) """ Global """ var = 'lucas' def fuun(): print(var) def fuuun(): global var #altera a variável global e não so a local var = 'edson' print(var) print(var) fuuun() print(var)
false
9d0626485f03fc0e6795191486dca955d6729055
LucasAraujoBR/Python-Language
/ListaPythonBrasil/CelsiusFahe.py
765
4.21875
4
""" Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. C = 5 * ((F-32) / 9). """ try: Fahrenheit = input('Digite a temperatura em graus Fahrenheit: ') Fahrenheit = float(Fahrenheit) conversor = ((Fahrenheit-32)*5)/9 print(f'{Fahrenheit} Fahrenehit equivale a {conversor:.2f} Celsius.') except: print('Dados inválidos.') """ Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. """ try: Celsius = input('Digite a temperatura em graus Celsius: ') Celsius = float(Celsius) conversor = (Celsius * 9/5) + 32 print(f'{Celsius} Celsius equivale a {conversor:.2f} Fahrenheit.') except: print('Dados inválidos.')
false
fabb6f4b04c3ac94cfd433742d6ac6ffedb24b9b
Mazen-Alalwan/PXW
/dictionary/templates/dictionary/testing.py
294
4.125
4
while True: height = input("are you tall?\n") gender = input("what's you gender\n") if height == "yes": height = "tall" elif height == "stop" or gender == "stop": break else: height = "short" print(" You're a " + gender + " and your " + height)
false
5be14e81fef1e3ff2a88d7868b20eed7915945e8
etangreal/compiler
/test/tests/03if/6432-if-else-test.py
600
4.125
4
if True: print "good" if False: print "Not good" if False: print "Not good" elif True: print "good" if False: print "Not good" elif False: print "Not good" if True: print "good" elif True: print "good 2" if True: print "good" elif False: print "Not good" if False: print "Not good" else: print "good" if True: print "good" else: print "Not good" if True: print "good" elif False: print "Not good" else: print "Not good" if True: print "good" elif True: print "good 2" else: print "Not good" if False: print "Not good" elif True: print "good" else: print "Not good 2"
true
e7c71df8c7f75dd67de0948a0fba747d60bdcdc9
DVDBZN/Schoolwork
/CS136 Database Programming With SQL/SQLite3Programs/PRA27 - Insert Into Select/InsertIntoSelect/CreateDB.py
926
4.21875
4
import sqlite3 import sys #Connect to database and set cursor conn = sqlite3.connect("Fish.sqlite3") cur = conn.cursor() #Create table if none exists try: conn.execute("CREATE TABLE Menu (ID INTEGER, Name TEXT, Price DECIMAL(3,2))") print "Table created" #If exists, exit program #We don't want duplicate rows in table except: print "Table exists" conn.close() raw_input("Press 'Enter' to exit") sys.exit() #List of row values fishes = ["tuna", "bass", "salmon", "catfish", "trout", "haddock", "yellowfin tuna"] prices = [7.50, 6.75, 9.50, 5.00, 6.00, 6.50, 12.00] #Loop seven times for idnum in range(1, 8): #Insert values into table cur.execute("INSERT INTO Menu (ID, Name, Price) VALUES(?, ?, ?)", (idnum, fishes[idnum - 1], prices[idnum - 1])) #Save and exit conn.commit() conn.close() print "Table succesfully populated and saved." raw_input("Press 'Enter' to exit")
true
1d97a02e476f575078f394c7aa1c301e5c8735d6
mpappas86/programmingTutorial
/commented_code/3_hellofilename.py
1,612
4.84375
5
# The big revelation of this file is that we can read information in from files. This means, by changing the files, # we can change the behavior of our code, *without having to change the code itself, nor its inputs*. The file # "3_filename.txt" that we are using here is an example of a very simple "database". # We saw this in the previous file - the import keyword says "I want to use the code in the 'os' folder" import os # Again, we define a function. This time, it takes 0 arguments. def load_name_from_file(): # There's a chain of keywords here that almost always get used together. Roughly, this line in plain english means: # "Open the file called '3_filename.txt', and create a variable called "opened_file" whose value is that file." with open('3_filename.txt') as opened_file: # Now opened_file is a variable whose value is a "file", but we don't care about everything about the file. # For instance, we don't care when it was last opened. We just want the text of the file. So we call the # "read" function to grab the text from inside the file, and set that as the value of the variable "name". name = opened_file.read() return name # Here we see one of the biggest advantages of functions - you can call it twice! That's much less code than if you had # to write out the instructions to open the file and read the contents multiple times! print 'Hello ' + load_name_from_file() + ', assuming ' + load_name_from_file() + ' is your real name!' # name = load_name_from_file() # print 'Hello ' + name + ', assuming ' + name + ' is your real name!'
true
06ee4b842b2c61768fcffb71651cf09cc65062d6
Jzweifel15/turtle-racing-py
/turtle_racing.py
1,767
4.25
4
import turtle import time import random # Width and Height of the canvas/screen WIDTH, HEIGHT = 500, 500 # A list of colors for the turtle racers COLORS = ["red", "green", "blue", "orange", "yellow", "black", "purple", "pink", "brown", "cyan"] # A function that asks the User for the number of turtles to race def get_number_of_racers(): racers = 0 while True: racers = input("Enter the number of racers (2 - 10): ") if racers.isdigit(): racers = int(racers) else: print("Input is not numeric... Try again!") continue if 2 <= racers <= 10: return racers else: print("Number not in range 2 - 10. Try again!") def race(colors): turtles = create_turtles(colors) while True: for racer in turtles: distance = random.randrange(1, 20) racer.forward(distance) x, y = racer.pos() if y >= HEIGHT // 2 - 10: return colors[turtles.index(racer)] # A function that creates the entered number of turtles and evenly places them on the canvas in their starting positions def create_turtles(colors): turtles = [] spacing_x = WIDTH // (len(colors) + 1) for i, color in enumerate(colors): racer = turtle.Turtle() racer.color(color) racer.shape("turtle") racer.left(90) racer.penup() racer.setpos(-WIDTH//2 + (i + 1) * spacing_x, -HEIGHT//2 + 20) racer.pendown() turtles.append(turtle) return turtles def init_turtle(): # Declaration and setup of the canvas/screen screen = turtle.Screen() screen.setup(WIDTH, HEIGHT) screen.title("Ninja Turtle Racing!") racers = get_number_of_racers() init_turtle() random.shuffle(COLORS) colors = COLORS[:racers] winner = race(colors) print("The winner is the turtle with color: " + winner)
true
00271a7e4b1571e039221696d5aeea137116d556
acidsafari/congenial-journey
/ex_11_1_greplike.py
556
4.21875
4
# Write a simple program to simulate the operation of the grep command on Unix. import re # Ask the user to enter a regular expression and hand = open('mbox.txt') lookfor = input('Please enter regular expression: ') i = 0 #counter for line in hand: line = line.rstrip() if re.search(lookfor, line): i = i + 1 print('mbox.txt had ', i, 'lines that matched ', lookfor) #count the number of lines that matched the regular expression: # $ python grep.py # Enter a regular expression: ^Author # mbox.txt had 1798 lines that matched ^Author
true
b9e2e63ff71a8e9f82f7d26e3a2a0af7f2672d34
kbhat1234/Python-Project
/python/formattime.py
1,121
4.3125
4
#fomat the time output from datetime import date from datetime import time from datetime import datetime def main(): now = datetime.now() print now.strftime("%Y") #prints year as YYYY (2017) print now.strftime("%y") #prints year as yy (17) print now.strftime("%a") #prints weekday name as Mon print now.strftime("%A") #prints weekday name as Monday print now.strftime("%b") #prints month name as Sep print now.strftime("%B") #prints month name as September print now.strftime("%d") #prints date print now.strftime("%a, %d, %b, %y") #prints output as Mon, 25, Sep, 17 print now.strftime("%A, %d, %B, %Y") #prints output as Monday, 25, September, 2017 print now.strftime("%c") #prints output as 09/25/17 14:28:14 print now.strftime("%x") #prints output as 09/25/17 print now.strftime("%X") #prints output as 14:28:14 print now.strftime("%I:%M:%S %p") print now.strftime("%H:%M %p") if __name__ == "__main__": main()
true
57d2c6269c93768089cad917879392391b0f9173
ariel1985/PyAI
/class1412/exercise.py
452
4.15625
4
""" Script shows a basic calculator """ print('\n\nPlease enter 2 numbers and get the results for:\n\t1. Addition\n\t2. Subtraction\n\t3. Multiplication\n\t4. Division') num1 = int(input("Enter first number:")) num2 = int(input("Enter second number:")) print('\nFor numbers: ', num1, num2) print('1. Addition', num1 + num2) print('2. Subtraction', num1 - num2) print('3. Multiplication', num1 * num2) print('4. Division', num1 / num2)
true
3c3d8f094cf06516e7ca90c3517980afe9def334
hemahpd/python_bigo
/quadraticTime.py
522
4.25
4
#An algorithm is said to have a quadratic time complexity when it needs # to perform a linear time operation for each value in the input data #Bubble sort # Best O(n^2); Average O(n^2); Worst O(n^2) def bubbleSort(List): for i in range(len(List)): for j in range(len(List) - 1, i, -1): if List[j] < List[j - 1]: List[j], List[j - 1] = List[j - 1], List[j] return List if __name__ == '__main__': List = [3, 4, 2, 6, 5, 7, 1, 9] print('Sorted List:',bubbleSort(List))
true
4f7bb95cb410f5fa155e76fb45e5ff5b5f12bfea
Git-Pierce/CIS122
/Week7/Conversion.py
333
4.125
4
CM_PER_INCH = 2.54 INCHES_PER_FOOT = 12 def height_US_to_cm(feet, inches): """Converts height in feet/inches to centimeters""" total_inches = feet * INCHES_PER_FOOT + inches cm = total_inches * CM_PER_INCH return cm feet = 6 inches = 4 centimeters = height_US_to_cm(feet, inches) print('Centimeters:', centimeters)
true
f5c3dbe5af5298083027794bd682ac3d292610cb
perteetd5295/cti110
/P3T1_AreasOfRectangles_PerteetDominique.py
698
4.34375
4
# CTI-110 # P3T1 Areas Of Rectangles # Dominique Perteet # 6/20/2018 # Get the dimensions of rectangle 1. length1 = int(input("Enter the length of rectangle 1: ")) width1 = int(input("Enter the width of rectangle 1: ")) # Get the dimensions of rectangle 2. length2 = int(input("Enter the length of rectangle2: ")) width2 = int(input("Enter the width of rectangle2: ")) # Calculate the areas of the rectangles. area1 = length1 * width1 area2 = length2 * width2 # Determine which has the greater area. if area1 > area2: print("Rectangle 1 has the greater area.") elif area2 > area1: print("Rectangle 2 has the greater area.") else: print("Both have the same area.")
true
4bb93c9aaf65225c66e1e9f5d2f24731fdf4a7a6
perteetd5295/cti110
/P4T2Bug CollectorPerteetDominique.py
430
4.125
4
## CTI-110 ## P4T2: Bug Collector ## Dominique Perteet ## 6/28/2018 # Initialize the accumlator. total = 0 # Get the bugs collected for each day. for day in range(1, 8): # Prompt the user. print('Enter the bus collected on day', day) # Input the number of bugs. bugs = int(input()) # Add bugs to total. total += bugs # Display the total bugs. print('Collected a total of', total, 'bugs')
true
70b9281637d68a6955d57abc07ea122a7ab999f4
stanrex-stack/algorithms_and_solutions
/ilya_masterclass_1.py
2,143
4.21875
4
class MyClass: i = 12345 def f(): return 'Hello World' print(MyClass.i) print(MyClass.f()) # 5:28 two ways to use an attribute reference x = MyClass() print(x.i) print(x.f) # 6:31 use instantination of class class Dog: breed = 'Pit Bull' def __init__(self, name, color): self.name = name self.color = color def methof(self): print(f'{self.name} is a good dog') name = self.name lucky = Dog('Lucky', 'black') snow = Dog('Snow', 'white') print(lucky.name) print(snow.name) print(lucky.color) print(snow.color) print(lucky.breed) print(snow.breed) print('') class MyClass1(object): is_agree = True is_agree: 1 def __init__(self, x): self.x = x def my_method(self, y): self.x = y @staticmethod def my_static_method(x, y): return x + y @classmethod def my_class_method(cls): cls.is_agree = False example = MyClass1(10) print(example.x) example.my_method(15) print(example.x) print(example.my_static_method(10, 20)) print(example.is_agree) example.my_class_method() print(example.is_agree) print('') class Employee: def __init__(self, name, salary): self._name = name self._salary = salary def set_salary(self, new_salary): self._salary = new_salary def get_salary(self): return self._salary def __count_all_year_salary(self): return self._salary * 12 def get_all_year_salary(self): return self.__count_all_year_salary() employee_1 = Employee('John', 10000) print(employee_1.get_salary()) employee_1.set_salary(100000) print(employee_1.get_salary()) print(employee_1.get_all_year_salary()) print('') class BaseClassName: def __init__(self, name): self.name = name def get_name(self): print(self.name) class BaseLasteName: def __init__(self, last_name): self.last_name = last_name def hello_world(self): print('Hello World') class DerivedClassName(BaseClassName, BaseLasteName): pass example = DerivedClassName('John') print(example.name) example.get_name() example.hello_world()
true
333b78f346e1bed7e9df317765fd8dfbe282a6ec
Vikram25/Interview-Prep-CTCI-Python
/Array & Strings/09-String-Rotation.py
525
4.21875
4
''' Assumeyou have a method isSubstringwhich checks if oneword is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). ''' def isSubstr(s1: str, s2: str) -> bool: return s1 in s2 def isRotation(s1: str, s2: str): if (len(s1) == len(s2) and len(s1) > 0): s1s1 = s1 + s1 return isSubstr(s1s1, s2) return False; print(isRotation("waterbottle","erbottlewat"))
true
3850ba354de7e961feddcb82e34719004960212d
ShoneSingLone/mindmap
/practice/Python/pythonc1.py
598
4.28125
4
# #号注释法 print("Hello Python!") ''' print("Hello Python2!") print("Hello Python3!") ''' listStuck = [1,"2","3"] print(listStuck[0]) listStuck[0] = "111111" print(listStuck[0]) tuplesStuck = (1, "2", "3") print(tuplesStuck[0]) dictionaryStuck = {"Name": "ShoneSingLone"} print(dictionaryStuck["Name"]) setStuck = set('asdfasdfasdfasdfasdfasdf') setStuck2 = set('asdfjkl;') setStuck3 = set('asd') print(setStuck) print(setStuck | setStuck2) b=8 if(b==9): print(b) # print(setStuck + setStuck3) for i in range(0,10): if(i>5): print("in for loop: current is "+str(i)) continue
false
95d229d7e3f2f34e0ba1ba871048a5790a171d62
monika48/LMS
/week1/varavarb.py
522
4.21875
4
#Assume that two variables, varA and varB, are assigned values, either numbers or strings. #Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages: #varA=input("Enter string1: ") #varB=input("Enter string2: ") #In this question we can't include input statements It should be automated. if isinstance(varA, str) or isinstance(varB, str): print("string involved") elif varA > varB: print("bigger") elif varA < varB: print("smaller") else: print("equal")
true
5b18c2bab4342d5dbbc4d22fb94c0227951775e7
jinglepp/python_cookbook
/03数字日期和时间/03.08分数运算.py
726
4.1875
4
# -*- coding: utf-8 -*- # fractions 模块可以被用来执行包含分数的数学运算。 # 比如: from fractions import Fraction a = Fraction(5, 4) b = Fraction(7, 16) print(a + b) print(a * b) c = a * b print(c.numerator) # 分子 print(c.denominator) # 分母 print(float(c)) print(c.limit_denominator(8)) # 约束分母 x = 3.75 y = Fraction(*x.as_integer_ratio()) # 把浮点数转化为分数形式 print(y) # 讨论 # 在大多数程序中一般不会出现分数的计算问题,但是有时候还是需要用到的。 # 比如,在一个允许接受分数形式的测试单位并以分数形式执行运算的程序中, # 直接使用分数可以减少手动转换为小数或浮点数的工作。
false
88fe71b7b083616588e908d15647e6676a75e886
jinglepp/python_cookbook
/03数字日期和时间/03.11随机选择.py
2,191
4.28125
4
# -*- coding: utf-8 -*- # 从一个序列中随机抽取若干元素,或者想生成几个随机数。 # 解决方案 # random 模块有大量的函数用来产生随机数和随机选择元素。 # 比如,要想从一个序列中随机的抽取一个元素,可以使用 random.choice() : import random values = [1, 2, 3, 4, 5, 6] print(random.choice(values)) # for i in range(5): # print(random.choice(values)) # 为了提取出N个不同元素的样本用来做进一步的操作,可以使用 random.sample() : print(random.sample(values, 2)) print(random.sample(values, 2)) print(random.sample(values, 3)) print(random.sample(values, 3)) # 如果你仅仅只是想打乱序列中元素的顺序,可以使用 random.shuffle() : random.shuffle(values) print(values) random.shuffle(values) print(values) # 生成随机整数,请使用 random.randint() : print(random.randint(0, 10)) print(random.randint(0, 10)) print(random.randint(0, 10)) print(random.randint(0, 10)) print(random.randint(0, 10)) # 为了生成0到1范围内均匀分布的浮点数,使用 random.random() : print(random.random()) print(random.random()) print(random.random()) # 如果要获取N位随机位(二进制)的整数,使用 random.getrandbits() : print(random.getrandbits(200)) # 讨论 # random 模块使用 Mersenne Twister 算法来计算生成随机数。 # 这是一个确定性算法, 但是你可以通过 random.seed() 函数修改初始化种子。比如: # random.seed() # Seed based on system time or os.urandom() # random.seed(12345) # Seed based on integer given # random.seed(b'bytedata') # Seed based on byte data # 除了上述介绍的功能,random模块还包含基于均匀分布、高斯分布和其他分布的随机数生成函数。 # 比如, random.uniform() 计算均匀分布随机数, random.gauss() 计算正态分布随机数。 # 对于其他的分布情况请参考在线文档。 # 在 random 模块中的函数不应该用在和密码学相关的程序中。 如果你确实需要类似的功能,可以使用ssl模块中相应的函数。 # 比如, ssl.RAND_bytes() 可以用来生成一个安全的随机字节序列。
false
6f93ffbb3801ab5835e1c2410172ad1d7ba7a5da
jinglepp/python_cookbook
/04迭代器与生成器/04.09排列组合的迭代.py
1,889
4.34375
4
# -*- coding: utf-8 -*- # 迭代遍历一个集合中元素的所有可能的排列或组合 # 解决方案 # itertools模块提供了三个函数来解决这类问题。 # 其中一个是 itertools.permutations() , 它接受一个集合并产生一个元组序列, # 每个元组由集合中所有元素的一个可能排列组成。 # 也就是说通过打乱集合中元素排列顺序生成一个元组,比如: items = ['a', 'b', 'c'] from itertools import permutations for p in permutations(items): print(p) # 如果你想得到指定长度的所有排列,你可以传递一个可选的长度参数。就像这样: for p in permutations(items, 2): print(p) # 使用 itertools.combinations() 可得到输入集合中元素的所有的组合。比如: from itertools import combinations for c in combinations(items, 3): print(c) for c in combinations(items, 2): print(c) for c in combinations(items, 1): print(c) # 对于 combinations() 来讲,元素的顺序已经不重要了。 # 也就是说,组合 ('a', 'b') 跟 ('b', 'a') 其实是一样的(最终只会输出其中一个)。 # # 在计算组合的时候,一旦元素被选取就会从候选中剔除掉(比如如果元素’a’已经被选取了,那么接下来就不会再考虑它了)。 # 而函数 itertools.combinations_with_replacement() 允许同一个元素被选择多次,比如: from itertools import combinations_with_replacement for c in combinations_with_replacement(items,3): print(c) # 讨论 # 这一小节我们向你展示的仅仅是 itertools 模块的一部分功能。 # 尽管你也可以自己手动实现排列组合算法,但是这样做得要花点脑力。 # 当我们碰到看上去有些复杂的迭代问题时,最好可以先去看看itertools模块。 # 如果这个问题很普遍,那么很有可能会在里面找到解决方案!
false
156903ae913871c5c874c09d8824f405af98c49e
iofh/Course-Files
/Programming 4/11.1 Intro to Programming Paradigms/examples.py
2,768
4.25
4
# Imperative example total = 0 num_one = 5 num_two = 10 num_three = 15 total = num_one + num_two + num_three # Functional example x = [1, 2, 3, 4, 5] def square(num): return num * num print(list(map(square, x))) # [1, 4, 9, 16, 25] a = 'Hello' b = 0 c = 0.0 d = True e = 3+1j print(type(a)) # <class 'str'> print(type(b)) # <class 'int'> print(type(c)) # <class 'float'> print(type(d)) # <class 'bool'> print(type(e)) # <class 'complex'> # Arithmetic operators x = 11 y = 2 print('x + y =', x + y) # x + y = 11 print('x - y =', x - y) # x - y = 9 print('x * y =', x * y) # x * y = 22 print('x / y =', x / y) # x / y = 5.5 print('x % y =', x % y) # x % y = 1 print('x // y =', x // y) # x // y = 5 print('x ** y =', x ** y) # x ** y = 121 # Comparison operators x = 10 y = 12 print('x > y is', x > y) # x > y is False print('x < y is', x < y) # x < y is True print('x == y is', x == y) # x == y is False print('x != y is', x != y) # x != y is True print('x >= y is', x >= y) # x >= y is False print('x <= y is', x <= y) # x <= y is True # Logical operators x = True y = False print('x and y is', x and y) # x and y is False print('x or y is', x or y) # x or y is True print('not x is', not x) # not x is False # Special operators - identity and membership a = 5 b = 5 c = 'Hello' d = 'Hello' e = [1, 2, 3] f = [1, 2, 3] print(a is not b) # False print(c is d) # True print(e is f) # False x = 'Hello world' y = {1: 'a', 2: 'b'} print('H' in x) # True print('hello' not in x) # True print(1 in y) # True print('a' in y) # False # Implicit type conversion num_int = 123 num_float = 1.23 num = num_int + num_float print(type(num_int)) # <class 'int'> print(type(num_float)) # <class 'float'> print(num) # 124.23 print(type(num)) # <class 'float'> # Explicit type conversion num_int = 123 num_float = 1.23 num = num_int + num_float num = int(num) print(type(num_int)) # <class 'int'> print(type(num_float)) # <class 'float'> print(num) # 124 print(type(num)) # <class 'int'> # Flow of control - if statements x = int(input("Please enter an integer: ")) if x < 50: print('x is less than 50') elif x > 50: print('x is greater than 50') else: print('x is equal to 50') # Flow of control - for statements animals = ['cat', 'dog', 'goldfish'] for a in animals: print(a, len(a)) # cat 3 # dog 3 # goldfish 8 # Functions def hello_world(): print('Hello world') hello_world() # String functions my_str = 'Hello, my name is John Doe' print(my_str) # Hello, my name is John Doe print(my_str.upper()) # HELLO, MY NAME IS JOHN DOE print(my_str.lower()) # hello, my name is john doe print(my_str.title()) # Hello, My Name Is John Doe print(my_str.replace('John', 'Jane')) # Hello, my name is Jane Doe
false
67db06000bcf5a9ce983ff6c8804ddd0c95fcf83
SubbuDevasani/Programs
/3.DataStructures/OrderdList/OrderedList.py
2,715
4.21875
4
""""" -------------------------------------------------------------------------------------------------------------------- 1.Read the Text from a file, split it into words and arrange it as Linked List. Take a user input to search a Word in the List. If the Word is not found then add it to the list, and if it found then remove the word from the List. In the end save the list into a file. -------------------------------------------------------------------------------------------------------------------- """ from Scripts.com.BridgeLabs.Functional.LinkedList import LinkedList class OrderderdList: if __name__ == '__main__': # Creating the object of the linked list ListNum = LinkedList() # creating an empty array and importing the file and spliting it and adding to the array array = [] file = open("maninums", "r") for i in file: nums = i.split() for i in nums: array.append(i) # After adding the elements into array adding the elements to the linked list array.sort() for i in array: ListNum.add(i) # printing the list before searching ListNum.show() # Taking the integer input from the user for searching num = int(input("Enter the value for searching : ")) # calling the searching method in the linked list class passing the int value # if the element is present in the list then it will delete element from the list if ListNum.search(num): index = ListNum.indexOf(num) ListNum.pop(num) print("After searching elements in the list are : ") ListNum.show() print("Element removed at :", index) # else it will add to the list at the particular position else: # calling insertOrder method to insert element at particular position ListNum.insertOrder(num) print("After searching") ListNum.show() print("Element added at Last of the list ") # After adding the element into the list updating the file using the num string # num string will append all the elements in the list and finally add the string to the fila num = "" for i in range(ListNum.size()): var = str(ListNum.index(i)) space = " " num = num + var + space print(num) # open the file in a+ mode it means for adding the text to the file # here we are adding the num string to the file and after adding closing the file f = open("maninums", "a+") f.write(num) f.close()
true
96ab3ad243925d358380104f07daa30526e54a3a
Anne19953/Algorithmspractice
/旋转数组的最小数字.py
1,349
4.1875
4
#!/usr/bin/env python # coding:utf-8 """ Name : 旋转数组的最小数字 Author : anne Time : 2019-09-18 09:29 Desc: """ #############################单纯找最小值,没意义 # class Solution: # def minNumberInRotateArray(self,rotateArray): # return min(rotateArray) # # a = Solution() # list = [3,4,5,1,2] # print(a.minNumberInRotateArray(list)) #########################使用二分查找 """ 1.array[mid] < array[high] 最小值为array[mid]或者在左边,因为是右边的数是递增的 high = mid 2.array[mid] > array[high] 此时最小值在array[mid]右边 low = mid + 1 3.array[mid] = array[high] 如果数组为[1,0,1,1,1,1]或者[1,1,1,0,1],不好判断,一个一个试 high = high -1 """ class Solution(): def minNumberInRotateArray(self, rotateArray): low = 0 high = len(rotateArray)-1 while(low<high): mid = (low + high)//2 if(rotateArray[mid]>rotateArray[high]): low = mid + 1 elif(rotateArray[mid]== rotateArray[high]): high = high-1 else: high = mid return rotateArray[low] a = Solution() list = [3,4,5,1,2] list2 = [1,0,1,1,1,1] list3 = [1,1,1,0,1] print(a.minNumberInRotateArray(list)) print(a.minNumberInRotateArray(list2)) print(a.minNumberInRotateArray(list3))
false
4d4c4be7e1312a91ea60efce80e65853fbd0cae5
Anne19953/Algorithmspractice
/从头到尾打印链表.py
1,226
4.125
4
#!/usr/bin/env python # coding:utf-8 """ Name : 从头到尾打印链表 Author : anne Time : 2019-09-12 22:57 Desc: """ #-----------------------递归法 class ListNode(): def __init__(self, x): self.val = x self.next = None class Solution1: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): if listNode is None: return [] return self.printListFromTailToHead(listNode.next) + [listNode.val] head = ListNode(1) head.next = ListNode(2) b = head.next b.next = ListNode(3) a = Solution1() b = a.printListFromTailToHead(listNode=head) print(b) #--------------法二 将链表转为list 再用切片 class Solution2: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead2(self, listNode): result = [] if listNode is None: return result while listNode is not None: result.append(listNode.val) listNode = listNode.next return result[::-1] head = ListNode(1) head.next = ListNode(2) b = head.next b.next = ListNode(3) a = Solution2() b = a.printListFromTailToHead2(listNode=head) print(b)
false
a940577265ec0d6985c1bed1763f79036a9274a8
panditdandgule/DataScience
/Other/Projects/Dictonary/Addset.py
1,290
4.4375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 25 08:10:58 2019 @author: pandit """ #Creating a set set1=set() print("Intial blank set: ") print(set1) #Adding element to set set1.add(8) set1.add(9) set1.add(12) print("\n Set after Addition of Three elements: ") print(set1) #Adding elements to the set using Iterator for i in range(1,6): set1.add(i) print("\n Set after Addition of elements from 1-5: ") print(set1) #Adding Tuples to the Set set1.add((6,7)) print("\nAfter Addition of a Tuple: ") print(set1) #Using Update function set1.update([10,11]) print("\nSet after Addition elements using update: ") print(set1) set1=set([1,2,3,4,5,6,7,8,9,10,11,12]) print("Intial set: ") print(set1) #Removing elements from set set1.remove(5) set1.remove(6) set1 #Removing elements form set set1.discard(8) set1.discard(9) print("\n Set after Discarding two elements: ") print(set1) #Removing elements from set using iterator method for i in range(1,5): set1.remove(i) print(set1) #Removing element from the set using the pop() set1.pop() print(set1) set1.clear() A={10,20,30,40,50} B={110,30,80,40,60} print(A.difference(B)) print(B.difference(A)) set1={2,4,5,6} set2={4,6,7,8} set3={4,6,7} set1.intersection(set2) set1.intersection(set3)
true
ff0516a4f50a0c043811f802146dd2cd71c7af3d
panditdandgule/DataScience
/NLP/StopWords.py
538
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 15 19:35:55 2018 @author: pandit """ from nltk.corpus import stopwords from nltk.tokenize import word_tokenize example_sentence ="This is an example showing off stop word filtration." stop_words=set(stopwords.words("english")) words=word_tokenize(example_sentence) #filtered_sentence=[] #for w in words: # if w not in stop_words: # filtered_sentence.append(w) filtered_sentence=[w for w in words if not w in stop_words] print(filtered_sentence)
false
af5ccf1f99c554418d0eb6afc57915fe2dd7c0a2
qq8282661/learn_py
/basics/generator.py
976
4.28125
4
# 创建generator,generator保存的是算法 g = (x for x in range(0, 3)) print(next(g)) print(next(g)) print(next(g)) # print(next(g)) //StopIteration # 我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。 # while 是循环,if 是条件判断 def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a+b n = n+1 return 'done' f = fib(6) print(f) for x in f: print(x) # generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。 # 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行 def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) o = odd() next(o) next(o) next(o) # 杨辉三角
false
b3ed41c4f6a73e6460523378f4d630d0f41eeba2
Ebad8931/PythonWorkshop
/04_functions.py
1,177
4.40625
4
from random import randint # Previous Examples of functions print('Hello world') range(5, 17, 2) len('python') # defining a function def hello(): print('hello world') # calling the function hello() def add(num1, num2): # num1 and num 2 are arguments return num1 + num2 # result is returned # Function Calling total = add(7, 9) print(total) def add_numbers(*args): total = 0 for num in args: total += num return total print(add_numbers(5, 6, 8, 4, 2)) print(add_numbers(234, 543)) print(add_numbers(34, 56, 78, 5, 5.67, 2.45, 5*4)) def cool_function(a, b=4, c=10): # b and c are default value arguments print('a is', a, 'b is', b, 'c is', c) cool_function(38, 49) # a&b are passed c takes its default value cool_function(54, c=74) # c is keyword argument, b is default argument cool_function(c=72, a=23) # a&c are keyword arguments, b is default argument data = [45, 35, 67] # a = data[0], b = data[1], c = data[2] cool_function(*data) # * unpacks the list and passes it to the function # random.randint(a,b) generates a random number N such that a <= N <= b print(randint(1, 10)) print(randint(1, 10))
true
71871e34aefbd84e5ac3119adb296da3849e0b7f
vkuberan/100-days-of-code-source
/day-15/python/section-7-structure-of-array.py
727
4.3125
4
import numpy as np # Section 7: Structure of Arrays # dtype: finds data type of array. # shape: shows shape of the array(n x m). # itemsize: Memory used by each array element in bytes. # ndim: Number of axes(of dimensions). structuresOfArray = np.ones((5, 3), dtype=int) print("Sample Array: \n{}".format(structuresOfArray)) print("Data Type: {}".format(structuresOfArray.dtype)) print("Item Size: {}".format(structuresOfArray.itemsize)) print("N Dimention: {}".format(structuresOfArray.ndim)) print("Array Shape: {}".format(structuresOfArray.shape)) # Creating a 3-D array. Difficult to print it. # reshape() simply reshape a 1-D array. array_3d = np.arange(12).reshape(2, 3, 2) print("\n\nReshape: \n{}".format(array_3d))
true
154624931e86efd00ca7623ed4a263414384ac26
egealpturkyener/Sorting_Algorithms_PyQt
/quick_sort.py
769
4.125
4
def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) # Function to do Quick sort def quickSort(arr,low,high): if low < high: pivot = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, pivot-1) quickSort(arr, pivot+1, high)
true
3bcac179e0c802bcce31b7c31abc208869ec352f
cristobalgh/python
/cursopython/animals.py
361
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 17 21:16:45 2018 @author: cristobal """ animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') def how_many(animals): i = 0 for word in animals: i += len(animals[word]) return i
false
c4253931b7f50764eba8305575a0d9635db716ec
john-m-hanlon/Python
/Sentdex Tutorials/Monte Carlo Simulations [SENTDEX]/03 - Simple Bettor Creation.py
1,595
4.125
4
import random def roll_dice(x): ''' Takes an argument x and returns a random integer Parameters ========== x : int Random positive integer Returns ======= roll : int returns a random between 1 and the provided argument ''' i = 0 while i < x: roll = random.randint(1, x) if roll == 100: # print('{} roll was 100, you lose! What are the odds!'.format(roll)) return False elif roll <= 50: # print('{} roll was less than 50, you lose!'.format(roll)) return False elif 100 > roll > 50: # print('{} roll was greater than 50, you WIN!'.format(roll)) return True print(roll) i += 1 roll_dice(100) def simple_bettor(funds, initial_wager, wager_count): ''' Takes three arguments and returns Parameters ========== funds : int How much money the user started with initial_wager : int How much user bets each time wager_count : int How many times the user particpates in the exercise Returns value : int The sum of 100 random wagers ======= ''' value = funds wager = initial_wager currentWager = 0 while currentWager < wager_count: if roll_dice(wager_count): value += wager else: value -= wager currentWager += 1 if value < 0: value = 'broke' print('Funds: {}'.format(value)) x = 0 while x < 100: simple_bettor(10000, 100, 1000) x += 1
true
aa7c222db4d08c7ee655cdd08538cb862f9e4c34
john-m-hanlon/Python
/General Python/Python Fundamentals [Pluralsight]/PF - 01 - Intro.py
701
4.375
4
# # A simple program to count the words in a given text # PF - 01 - Intro.py # __author__ = 'JohnHanlon' import sys def count_words(filename): ''' Counts the number of words in a give text Parameters ========== filename : file the while which will be analyzed Returns ======= N/A : returns nothing ''' results = dict() with open(filename, 'r') as f: for line in f: for word in line.split(): results[word] = results.setdefault(word, 0) + 1 for word, count in sorted(results.items(), key=lambda x: x[1]): print('{} {}'.format(count, word)) # count_words(sys.argv[1]) count_words('test_file.txt')
true
b84c15ea4e4d84b754847b9cbe4fdbf3ef5dc17f
john-m-hanlon/Python
/General Python/LTP - Introduction to Python [PluralSight]/LTP - 01 - Introduction to Python.py
1,559
4.34375
4
# # Simple script which takes input from a user and assigns it to be their # favorite number! # LTP -01 - Introduction to Python.py # __author__ = 'JohnHanlon' # What is your favorite number? def favorite_number(): ''' Asks for your favorite number and returns the same Parameters ========== N/A : takes no parameters Returns ======= value : str Sentence with your favorite number ''' print('Hello, what is your favorite number?') number = input() value = 'Your favorite number is {}'.format(number) return value # print(favorite_number()) def random_number_guesser(): ''' Asks for a number and gives the user several attempts to guess the number Parameters ========== N/A : takes no parameters Returns ======= magic_number : int random magic number ''' import random min_number = 1 max_number = 100 magic_number = random.randint(min_number, max_number) message = 'The magic number is between {0} and {1}'.format(min_number, max_number) print(message) found = False while not found: print('Hello, what is the magic number?') usr_input = int(input()) if usr_input == magic_number: found = True elif usr_input < magic_number: print('Your guess is too low') elif usr_input > magic_number: print('Your guess is too high') print('You got it') random_number_guesser()
true
e887a19c3b3918f55c5914e674e7f79aec28fe49
ThomasZumsteg/project-euler
/problem_0057.py
1,425
4.125
4
#!/usr/bin/env python3 """ It is possible to show that the square root of two can be expressed as an infinite continued fraction. √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? """ import logging import sys import time logging.basicConfig( stream=sys.stderr, level=logging.INFO, format='%(levelname)s: %(message)s') def main(): i = 1000 count = 0 for n, d in root_fract_gen(): logging.debug("{}/{}".format(n,d)) if len(str(n)) > len(str(d)): count += 1 if i < 0: break i -= 1 print("There are {} fraction with the num".format(count)) def root_fract_gen(): num = 1 den = 1 while True: (num, den) = (num + 2 * den, num + den) yield (num, den) if __name__ == "__main__": start = time.time() main() print("That took {time:4.2f} seconds" .format(time=time.time() - start))
true
e2cb3379b3f7963e5c4dab70baa383414efeb7ce
Shawn070/python_intr
/max_n.py
447
4.15625
4
# 寻找一组数中的最大值 def main(): #方法一: n = eval(input("How many numbers are there?")) max = eval(input("Enter a number>>")) for i in range(n-1): x = eval(input("Enter a number>>")) if x > max: max = x print("The largest value is", max) #方法二: # x1, x2, x3 = eval(input("Please enter three values:")) # print("The largest value is", max(x1, x2, x3)) main()
true
6dd336c2e69bc05636f8c27be09df8870b3801c6
naveentata/Sortings-in-different-Languages
/Python/InsertionSort.py
370
4.1875
4
def insertionSort(array): for itemCounter in range(len(array)): item = array[itemCounter] locationCounter = 0 while item > array[locationCounter]: locationCounter += 1 for i in reversed(range(locationCounter, itemCounter + 1)): array[i] = array[i - 1] array[locationCounter] = item return array
true
4bbc79322fa161b1ce0ed7d6fce398423ec5d115
ryancarmes/python-strings-lists
/findandreplace.py
240
4.15625
4
words = "It's thanksgiving day. It's my birthday,too!" print words[18:21] #printing array/list positions within a string. print words.replace("day", "month", 1) #replace takes parameter a and replaces with b a number of times as defined.
true
ca798b2f278296fe0c253f3559b6e1487075aad4
kovalevcon/algorithms
/Arrays/sort/select-sort.py
537
4.1875
4
# Selection sort of array # Asymptotic complexity (O) = n * n def find_smallest_index(arr): """ :type arr: list :rtype: list """ smallest, smallest_index = arr[0], 0 for i in range(len(arr)): if arr[i] < smallest: smallest, smallest_index = arr[i], i return smallest_index def select_sort(arr): sort_arr = [] for i in range(len(arr)): sort_arr.append(arr.pop(find_smallest_index(arr))) return sort_arr print(select_sort([2, 4, 5, 7, 1, 6])) # [1, 2, 4, 5, 6, 7]
false
488cbdfb29429268fcce1ca807e37983cbbbee38
lakshuguru/Hacker-Rank
/22_bst.py
1,292
4.1875
4
'''The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree. Sample Input 7 3 5 2 1 4 6 7 Sample Output 3''' class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def getHeight(self,root): #Write your code here if root is None: return -1 hL = self.getHeight(root.left) hR = self.getHeight(root.right) if hL > hR: return 1+hL else: return 1+hR T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) height=myTree.getHeight(root) print(height)
true
4b90e4b61d41d11fd69aeaa6b8dc4e46cd8b1bbf
usman-tahir/rubyeuler
/array_palindromes.py
573
4.375
4
#!/usr/bin/env python # http://programmingpraxis.com/2015/03/31/identifying-palindromes/ def array_is_palindrome(list): left_index = 0 right_index = len(list)-1 while right_index >= left_index: if list[left_index] != list[right_index]: return False else: left_index += 1 right_index -= 1 return True even_palindrome = [1,2,3,4,4,3,2,1] odd_palindrome = [1,2,3,4,5,4,3,2,1] not_palindrome = [1,2,3,4,5,1,2,3,4] print array_is_palindrome(even_palindrome) print array_is_palindrome(odd_palindrome) print array_is_palindrome(not_palindrome)
false
da676ded1c108987c0fb271d6097d5019a258bf3
usman-tahir/rubyeuler
/powers_of_three.py
340
4.25
4
#!/usr/bin/env/python # https://programmingpraxis.com/2016/03/01/powers-of-3/ def is_power_of_three(n): if n == 1 or n == 3: return True elif n % 3 != 0: return False else: return is_power_of_three(n/3) print [3**x for x in xrange(0,7)] == [x for x in xrange(1,1000) \ if is_power_of_three(x)]
false
19cd1dac709cf6bcc15671cb92002980161f320a
Linjiayu6/LeetCode
/History/0629/88_merge.py
1,846
4.125
4
""" 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] """ # def merge(nums1, m, nums2, n): # i = 0 # j = 0 # L = [] # nums1 = nums1[:m+1] # nums2 = nums2[:n+1] # while(i < m and j < n): # a = nums1[i] # b = nums2[j] # if a < b: # L.append(a) # i += 1 # elif a > b: # L.append(b) # j += 1 # else: # L.append(a) # L.append(b) # i += 1 # j += 1 # if (i<m): L += nums1[i:m] # if (j<n): L += nums2[j:n] # return L # print(merge([1,2,3], 3, [2,5,6],3)) """ 该题的重点不是新创建一个L, 而是覆盖掉nums1 """ # def merge(nums1, m, nums2, n): # i = m - 1 # j = n - 1 # z = m + n - 1 # while(True): # if (i < 0 or j < 0): # break # if nums1[i] < nums2[j]: # nums1[z] = nums2[j] # j -= 1 # z -= 1 # else: # nums1[z] = nums1[i] # i -= 1 # z -= 1 # while(i >= 0): # nums1[z] = nums1[i] # i -= 1 # z -= 1 # while(j >= 0): # nums1[z] = nums2[j] # j -= 1 # z -= 1 # return nums1 # print(merge([1,2,3,0,0,0], 3, [2,5,6],3)) def merge(nums1, m, nums2, n): i = m j = 0 while(j < n): nums1[i] = nums2[j] i += 1 j += 1 # 前面已经是排序好的, 插入排序 for x in range(m, len(nums1), 1): for y in range(x, 0, -1): if (nums1[y] < nums1[y - 1]): nums1[y], nums1[y - 1] = nums1[y - 1], nums1[y] return nums1 print(merge([1,2,3,0,0,0], 3, [2,5,6],3))
false
afa77d7a98764494f8336a7143d98e0f64436962
MYESHASVIREDDY/Advance-Data-Structures-Using-Python
/Experiment 2c/quick_sort.py
512
4.1875
4
def quick_sort(list): if len(list) <=1: return list else: pivort = list[len(list) // 2] left = [x for x in list if x < pivort] middle = [x for x in list if x == pivort] right = [x for x in list if x > pivort] return quick_sort(left) + middle + quick_sort(right) list=[] n=int(input("enter range for arrary :")) print("enter elements to the array") for i in range(0,n): ele =int(input()) list.append(ele) print("the elements of array are",list) quick_sort(list)
true
29808bff831e9dd92fbd1d111c5e77d3a6ef331e
Marcfeitosa/listadeexercicios
/ex041.py
833
4.125
4
"""DESAFIO 41 A confederação nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: - Até 9 anos: MIRIM - Até 14 anos: INFANTIL - Até 19 anos: JUNIOR - Até 20 anos: Sênior - Acima: MASTER""" idadeatleta = int(input("Qual é a idade do atleta? ")) if idadeatleta <= 9: print("MIRIM") elif idadeatleta > 9 and idadeatleta <= 14: print("INFANTIL") elif idadeatleta > 14 and idadeatleta <= 19: print("JUNIOR") elif idadeatleta >19 and idadeatleta <= 25: print("SÊNIOR") else: print("MASTER") if idadeatleta <= 9: print("MIRIM") elif idadeatleta <= 14: print("INFANTIL") elif idadeatleta <= 19: print("JUNIOR") elif idadeatleta <= 25: print("SÊNIOR") else: print("MASTER")
false
c0f2adbeae1d93d87204ad29165ee4d6111ebe1d
Marcfeitosa/listadeexercicios
/ex057.py
440
4.125
4
"""Desafio 057 Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'. Caso esteja errado, peça a digitação novamente até ter um valor correto.""" mcount = 0 sexo = str(input('Qual é o seu sexo? [M/F]')).upper().strip()[0] while sexo not in 'MF': sexo = str(input('O anta... qual é o seu probema? Só existe Masculino (M) e Feminino (F).')).upper().strip()[0] print('OK... grandes coisa!!!!')
false
e1cab861f9d528fb66274f571baf5f47234f8a4b
Marcfeitosa/listadeexercicios
/ex037.py
1,539
4.34375
4
print (3*'===============xx==============xx' + '==============') """DESAFIO 37 Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: -1 para binário -2 para octal -3 para hexadecimal""" import types def checkifnumeric( num ): while True: if num < 400: choice = int(input("""Para qual base você deseja converter -1 para binário -2 para octal -3 para hexadecimal""")) return calc(num,choice) else: print('Digita um número sua anta...') break def calc(num,choice): if choice <= 3: if choice == 1: print('O número {} em binário é {}'.format(num, bin(num))) elif choice == 2: print('O número {} em octal é {}.'.format(num, oct(num))) elif choice == 3: print('O número {} em hexadecimal é {}'.format(num, hex(num))) else: print('Opção inválida') else: print('número inválido') choice = int("""Para qual base você deseja converter -1 para binário -2 para octal -3 para hexadecimal""") print (3*'===============xx==============xx' + '==============') number = int(input('Excolha um número qualquer: ')) checkifnumeric(number)
false
7414611ee6ab3673db646e0da5e86324b3f3e419
szabgab/Learning-Python
/Basic/Day 11/Sample programs/Sample program 1.py
390
4.1875
4
>>> list=[[1,2,3],[2,3,4],[3,4,5]] >>> print(list[1]) [2, 3, 4] >>> print(len(list)) 3 >>> print(list[2][1]) 4 >>> print(len(list[0])) 3 >>> print(list) [[1, 2, 3], [2, 3, 4], [3, 4, 5]] >>> for i in range(0,len(list)): ... for j in range(0,len(list[i])): ... print(list[i][j]) ... 1 2 3 2 3 4 3 4 5 >>> for i in list: ... for c in i: ... print(c,end="") ... print() ... 123 234 345
false
a4afc0e03f58d839e6c285cfd6f730e1d7396293
szabgab/Learning-Python
/Basic/Day 18/Sample programs/Sample question 1.py
1,145
4.3125
4
>>> hardware={ "Brand": "Dell", "Model": 2430, "Year": "2020"} >>> print(hardware) #prints the value of the dictionary {'Brand': 'Dell', 'Model': 2430, 'Year': '2020'} >>> print(hardware["Model"]) 2430 >>> print(hardware.get("Model")) 2430 >>> hardware["Year"]=2021 #Changing the value of the dictionary >>> print(hardware) {'Brand': 'Dell', 'Model': 2430, 'Year': 2021} >>> print(hardware.pop("Model")) 2430 >>> print(hardware) {'Brand': 'Dell', 'Year': 2021} >>> hardware["Model"]="Lenovo" >>> hardware["Year"]=2019 >>> print(hardware.popitem()) #popitem returns the last value entered ('Model', 'Lenovo') >>> print(hardware) {'Brand': 'Dell', 'Year': 2019} >>> for y in hardware: ... print(y)#Corresponds to each key ... Brand Year >>> for x in hardware: ... print(hardware[x])#refers to the value ... Dell 2019 >>> for z in hardware.values(): ... print(z) ... Dell 2019 >>> hardware.clear() #Cleares the dictionary (not delete) >>> print(hardware) {} >>> print(hardware["Price"])#trying to remove element which is not present Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Price'
true
b41bda8b3da1eb28e6b0a812b5a959a860d61deb
dparadise28/python
/eKnap.py
813
4.25
4
# 0-1 knapsack problem dynamic program # David Eppstein, ICS, UCI, 2/22/2002 # each item to be packed is represented as a set of triples (size,value,name) def itemSize(item): return item[0] def itemValue(item): return item[1] def itemName(item): return item[2] # example used in lecture exampleItems = [(3,3,'A'), (4,1,'B'), (8,3,'C'), (10,4,'D'), (15,3,'E'), (20,6,'F')] exampleSizeLimit = 32 # inefficient recursive algorithm # returns optimal value for given # # note items[-1] is the last item, items[:-1] is all but the last item # def pack1(items,sizeLimit): if len(items) == 0: return 0 elif itemSize(items[-1]) > sizeLimit: return pack1(items[:-1],sizeLimit) else: return max(pack1(items[:-1],sizeLimit), pack1(items[:-1],sizeLimit-itemSize(items[-1])) + itemValue(items[-1]))
true