blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
696e979eadffb26bac50a562fd62c0dc6de655b4
AvanindraC/Python
/histogram.py
332
4.15625
4
# Write a Python program to create a histogram from a given list of integers def histogram(data): for item in data: print('.' * item) data = [] num_data = int(input("Enter number of entries: ")) for item in range(0, num_data): user_input = int(input()) data.append(user_input) res = histogram(data) print(res)
true
8b0c933fc0179f1a072ff79403e64ad979e69ca0
AvanindraC/Python
/reverse.py
262
4.28125
4
# Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them first = str(input("Enter first name: ")) last = str(input("Enter last name: ")) result = first[::-1] + " " + last[::-1] print(result)
true
02bd5ed48d7d512b30aa1b0938c87ef26629351d
JeganKunniya/practice-python-exercises
/16-PasswordGenerator.py
1,094
4.125
4
# Exercise 16 - Password Generator import random import string STRONG = 1 MEDIUM = 2 WEAK = 3 def generate_password(password_complexity): """ Generates the password based on the complexity requested by the user. :param password_complexity: could be Strong, Medium, Weak :return: generated password based on the complexity """ password_sequence = string.ascii_letters + string.digits + string.punctuation if password_complexity == STRONG: password = ''.join(random.choice(password_sequence) for i in range(32)) elif password_complexity == MEDIUM: password = ''.join(random.choice(password_sequence) for i in range(16)) elif password_complexity == WEAK: password = ''.join(random.choice(password_sequence) for i in range(8)) else: password = '' return password if __name__ == '__main__': print('The choices of password complexity are \n 1. Strong \n 2. Medium \n 3. Weak') complexity = int(input('Enter your password complexity choice: ')) print('Your password is : ', generate_password(complexity))
true
9446bb68742d2f789534219c702c2be0c303f373
mathivanansoft/algorithms_and_data_structures
/algorithms/divide_and_conquer/sorted_rotated_arr.py
877
4.125
4
# search an element in sorted rotated array def search_in_sorted_rotated_arr(arr, key, start, end): if start > end: return -1 else: mid = start + (end - start) // 2 if arr[mid] == key: return mid elif arr[mid] < arr[end]: if key > arr[mid] and key <= arr[end]: return search_in_sorted_rotated_arr(arr, key, mid + 1, end) else: return search_in_sorted_rotated_arr(arr, key, start, mid - 1) else: if key >= arr[start] and key < arr[mid]: return search_in_sorted_rotated_arr(arr, key, start, mid - 1) else: return search_in_sorted_rotated_arr(arr, key, mid + 1, end) if __name__ =="__main__": arr = [ 7, 8, 9, 10, 1, 2, 3, 4, 5, 6] print(search_in_sorted_rotated_arr(arr, 8, 0, len(arr)-1))
false
c6ce638e8b2ac21aa1971d76f27d50aab98ca958
cleviane/CampinasTechTalentes-Python
/Aula_006/condicionaiscomnumeros.py
365
4.28125
4
# num_um = 1 # num_dois = 2 numero = int(input("Coloque o seu número: ")) if numero >= 0 and numero <= 3: print(f"Os números {numero} está entre 0 e 3") elif numero >= 3 and numero <= 4: print(f"O número {numero} está entre 3 e 4") elif numero >= 5 and numero <= 10: print(f"O número {numero} está entre 5 e 10")
false
dd75bef404b684e89eea27671c8e5adb78a35ab8
dannyjew/Data22
/HangMan/main.py
2,460
4.28125
4
word_to_guess = input("Please pick a word to guess...") # user inputs a word to guess max_lives = 5 # max lives that the guesser has wrong_counter = 1 # tracks the number of times the guesser guesses wrong underscores = "________________________________________________________________________" # this is used to make the initial hidden word hidden_word = underscores[0:len(word_to_guess)] # this creates the hidden word (e.g. "_____" for "Hello") print(hidden_word) incorrect_letters = [] # This function reveals a letter in the hidden word... # this function has 3 arguments, the guessed letter, the word to guess and the hidden word (e.g. "h_ll_") # it then converts the hidden word to a list and loops through the actual word to find # out when the guessed letter appears,this information is stored in the counter variable, # which is then used to swap an underscore in that position, to the guessed letter # e.g. reveal_letter("e", "Hello", "_____") -> "_e___" def reveal_letter(letter_picked, word_to_guess, underscored_word): counter = 0 hidden_word_list = list(underscored_word) for letter in word_to_guess: if letter == letter_picked: hidden_word_list[counter] = letter_picked counter += 1 return ''.join(hidden_word_list) # This is the main loop which loops whilst the user has lives or whilse the word # to guess is not fully alphabetical e.g. "_e__o" meaning that there are still letters to be guessed while wrong_counter <= max_lives and not hidden_word.isalpha(): guessed_letter = input("Please guess a letter...") # user guesses a letter if guessed_letter in hidden_word or guessed_letter in incorrect_letters: # if guessed letter is in the hidden_word or incorrect_letters list then it has already been guessed print("You have already guessed this letter you fool...") wrong_counter += 1 # they loose a life for this elif guessed_letter in word_to_guess: # if the guessed letter is in the word to guess print("That was correct!") hidden_word = reveal_letter(guessed_letter, word_to_guess, hidden_word) # call the function to reveal the letter in the word print(hidden_word) # print the word e.g. "_e_ll_" else: wrong_counter += 1 # otherwise, they just guessed a letter that was not in the word to guess and not already guessed before incorrect_letters.append(guessed_letter) print("Incorrect!")
true
94c4e796a3ab358f9c73df69be968aedcb7182e4
EWilcox811/UdemyPython
/LambdaMap.py
988
4.125
4
def square(num): return num**2 my_nums = [1,2,3,4,5] for item in map(square, my_nums): print(item) list(map(square,my_nums)) def splicer(mystring): if len(mystring)%2 == 0: return 'EVEN' else: return mystring[0] name = ['Andy','Eve','Sally'] list(map(splicer,name)) # When using the map function, you enter the function name as an argument without the () # You aren't calling the funciton in the map call, map calls it later. If you do enter () # you will receive a type error # FILTER funciton def check_even(num): return num%2==0 mynums = [1,2,3,4,5,6] list(filter(check_even, mynums)) # LAMBDA EXPRESSIONS def square(num): result = num ** 2 return result # Turning this into a lambda EXPRESSION # Also known as an anonymous function list(map(lambda num: num**2, mynums)) # Typically this is used in conjunction with other functions like map and filter. list(filter(lambda num:num%2==0, my_nums)) list(map(lambda name:name[::-1], name))
true
89fd8e1721a761ac8db70bd29590bc7d1b1ae6d3
lingxueli/CodingBook
/Python/decorator/decorator.py
1,223
4.28125
4
def hello(): print('helloooooo') greet = hello() print(greet) # hello greet = hello print(greet) # function object del hello # hello is the pointer to the function # this deletes the pointer not the function itself greet() # still executed # @decorator # def hello(): # pass # decorator add extra features to a function # higher order function # a function that accepts another function as a parameter def greet(func): func # a function that returns another function def greet2(): def func(): return 5 return func # example: map, reduce, filter # wrap another funciton, enhance it def my_decorator(func): def wrap_func(): print('********') func() print('********') return wrap_func @my_decorator def hello(): print("hello") @my_decorator def bye(): print("see ya") hello() bye() # this has the same effect def my_decorator(func): def wrap_func(): print('********') func() print('********') return wrap_func def hello(): print("hello") def bye(): print("see ya") hello2 = my_decorator(hello) # pointer to wrap_func, where func == hello hello2() # call wrap_func # alternative my_decorator(hello)()
true
fd4dfabeda6c4267eb8b57cd33c0aa95be45701d
lingxueli/CodingBook
/Python/Basics/range.py
283
4.125
4
# range creates an object that you can iterate over print(range(0,100)) # obj: range(0,100) for number in range(0,100): print(number) # when you don't need the variable # send emails 100 times for _ in range(0,100): print('email email list') print(_) # print 1,2,...
true
ef4fcfc933daf2bd296b07ec620f32af92ccd248
lingxueli/CodingBook
/Python/Error handling/errorhandling4.py
537
4.1875
4
# stop the program from an error: raise while True: try: age = int(input('what s your age? ')) 10/age # this stops the program raise ValueError('hey cut it out') # alternative: stop from any type of error raise Exception('hey cut it out') # remove the except part # except ValueError: # print('please enter a number') except ZeroDivisionError: print('please enter age higher than 0') else: # no thing failed print('thank you!') break
true
c25a1bb60e229ce1e9041427dadb3addc4429d56
haodayitoutou/Algorithms
/LC50/lc24.py
1,239
4.125
4
""" Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. """ from util import ListNode, create_node_list, print_node_list def swap(node): if node is None or node.next is None: return node dummy = ListNode(0) first = dummy previous = dummy first = node second = node.next while first and second: third = second.next # pre - 1st - 2nd - 3rd --> # pre - 2nd - 1st - 3rd previous.next = second # pre - 2nd - 3rd, 1st - 2nd - 3rd second.next = first # pre - 2nd <-> 1st, 3rd first.next = third # pre - 2nd - 1st - 3rd if third: previous = first first = third second = third.next else: break return dummy.next def test(): nums_list = [ [], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5] ] for nums in nums_list: node = create_node_list(nums) print_node_list(swap(node)) test()
true
926fd5942e965801e9a0483c7ad67d0bfb33e77c
Bushraafsar/Alien-Dictionary
/alien.py
2,532
4.40625
4
# PYTHON ASSIGNMENT: #ALIEN TASK: # Python Program that display meaning of word said by alien in English Language: # Python Program that display meaning of word said by human in alien language: import json print("==================== ENGLISH / ALIEN TRANSLATOR=========================") while True: print("SELECT ANY ONE OPTION :") print("Enter 1 if you wanna know the meaning of word in english language!") print("Enter 2 if you wanna add new word in english dictionary!") print("Enter 3 if you wanna know the meaning of word in alien language:") print("Enter 4 if you wanna add new word in alien dictionary!") print("Enter 5 to exist!") choice = int(input("Enter your choice:")) if choice == 1: alien_input = input("Enter the word you wanna change in english language:") alien_input = alien_input.lower() with open("data1.json")as f: hd = json.load(f) try: for keys,values in hd.items(): if keys == alien_input: print("The meaning of this word in alien language is:",values) except: print("This word doesn't exist in our dictionary!") elif choice == 2: new_word = input("Enter the word you want to Add in human dictionary!") with open("data.json")as f: human_dictionary = json.load(f) human_dictionary[new_word] = input("Enter the meaning of this word which doesn't exist before!") print(human_dictionary) elif choice == 3: human_input = input("Enter the word you wanna change in alien language:") human_input = human_input.lower() with open("data.json")as f: alien_dictionary = json.load(f) try: for word,values in alien_dictionary.items(): if word == human_input: print("the meaning of this word in alien language is:",values) except: print("This word currently doesn't exist is our dictionary!!") elif choice == 4: new_word = input("Enter the word you wanna add in alien dictionary:") with open("data1.json")as f: alien_dictionary = json.load(f) alien_dictionary[word] = input("Enter the meaning of this word which doesn't exist before!!") print(alien_dictionary) elif choice == 5: break else: print("You enter wrong number!")
true
4558a55e7d002e971aa7472aba0983160b90926e
ZanyeEast/ISAT252
/lec9.py
615
4.4375
4
""" Lecture 9 Classes Self method should be the first argument """ class car: # car is the class name maker = 'toyota' #attribute def __init__(self,input_model): self.model = input_model def report(self): #return the attribute of the instance return self.maker,self.model my_car = car('corolla') print(my_car.report()) my_car.maker = 'ford' print(my_car.report()) ''' def report_maker(self): #method return(self.maker) my_car = car() #Create an instance/object #print(my_car.maker) # has same output as code below. print(my_car.report_maker())'''
true
17bb66f503fee20354db38815f5ec7e094c3059c
ZanyeEast/ISAT252
/lec8.py
1,220
4.46875
4
""" Lecture 8 Functions return function should always be the last command in function """ #positional argument def my_function(a, b): result = a + b print('a is',a) print('b is',b) return result print(my_function(2, 1)) def my_function(a, b=0): result = a + b print('a is',a) print('b is',b) return result #different way to assign value (key-word argument) print(my_function(a=2)) def my_function(a, b=0): result = a + b print('a is',a) print('b is',b) return a + b print(my_function(a=1)+1) #Ex1 return absolute value def calculate_abs(a): if type(a) is str: return ('wrong data type') elif a>0: return a else: return -a print(calculate_abs(a=0)) #ex2 calculate sigma(n,m) def cal_sigma(m,n): result = 0 for i in range (n,m+1): result = result + i return result print(cal_sigma(m=5,n=3)) def cal_pi(n,m): result=1 for i in range(n,m+1): result=result*i return result print(cal_pi(5,3)) #ex3 def cal_f(m): if m == 0: return 1 else: return m* cal_f(m-1) #print(cal_f(3)) def cal_p(m,n): return cal_f(m)/cal_f(m-n) print(cal_p(5,3))
true
00e625639340092f82a32dedf9bdabcf3be4c28a
DrGMark7/CodingProblem
/Circle Test.py
461
4.15625
4
from math import sqrt print('*'*30) print('*********About Circle*********') print('*'*30) r = float(input('Input radius: ')) pi = 3.141592653589793 area = (pi*(r*r)) circ = (2*pi*r) print('Radius is',r) print('Circumference is', round(circ,4)) print('Area is', round(area,2) ) y = float(input('Enter y for finding x: ')) x = '{:.4f}'.format(sqrt((r**2)-(y**2))) print('y is {0:.4f}'.format(y)) print('x is '+ ('-'+x) + " and " + x ) print('*'*30)
false
dc8df2ff35639fe143f5173aae56413e33ab125b
karinasamohvalova/OneMonth_python
/tip.py
551
4.15625
4
# We ask client's name and his bill name = input("What is your name? ") original_bill = int(input("What is your bill? ")) # We count three types if tips tip_one = original_bill * 0.15 tip_two = original_bill * 0.18 tip_three = original_bill * 0.20 # We make an offer to the person. It includes 3 choices. print("You can choose one of three types of tips") print(f"{name} 15% tip from your bill is ${tip_one:.1f}.") print(f"{name} 18% tip from your bill is ${tip_two:.1f}.") print(f"{name} 20% tip from your bill is ${tip_three:.1f}.")
true
2a45b8f146c70af9967b203c4cc587a0bdc801a2
nakayamaqs/PythonModule
/Learning/func_return.py
1,354
4.3125
4
# from :http://docs.python.org/3.3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters # By returning a tuple of the results: def func2(a, b): a = 'new-value' # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = 'old-value', 99 x, y = func2(x, y) print(x, y) # output: new-value 100 # By passing a mutable (changeable in-place) object: def func1(a): a[0] = 'new-value' # 'a' references a mutable list a[1] = a[1] + 1 # changes a shared object args = ['old-value', 99] func1(args) print(args[0], args[1]) # output: new-value 100 # By passing in a dictionary that gets mutated: def func3(args): args['a'] = 'new-value' # args is a mutable dictionary args['b'] = args['b'] + 1 # change it in-place args = {'a':' old-value', 'b': 99} func3(args) print(args['a'], args['b']) # Or bundle up values in a class instance: class callByRef: def __init__(self, **args): for (key, value) in args.items(): setattr(self, key, value) def func4(args): args.a = 'new-value by func4.' # args is a mutable callByRef args.b = args.b + 100 # change object in-place args = callByRef(a='old-value', b=99,c=23) func4(args) print(args.a, args.b, args.c)
true
0b4b0a0299125f12419c24828b4e3699b8708226
nakayamaqs/PythonModule
/Learning/find.py
1,670
4.125
4
#!/usr/bin/env python # encoding: utf-8 # # Simple imitation of the Unix find command, which search sub-tree # for a named file, both of which are specified as arguments. # Because python is a scripting language, and because python # offers such fantastic support for file system navigation and # regular expressions, python is very good at for these types # of tasks from sys import argv from os import listdir from os.path import isdir, exists, basename, join # import re def listAllExactMatches(path, filename): """Recursive function that lists all files matching the specified file name""" if(basename(path) == filename): # print(re.match(filename, basename(path))) print("Find: ",path) # match file by extension. # if(basename(path).endswith(".py")): # print("match:", path) if(not isdir(path)): print("not a path:",path) return dirlist = listdir(path) for file in dirlist: listAllExactMatches(file, filename) def parseAndListMatches(): """Parses the command line, confirming that there are in fact three arguments, confirms that the specified path is actually the name of a real directory, and then recursively searches the file tree rooted at the specified directory.""" if(len(argv) != 3): print("Usage: find <path-to-directory-tree> <filename>") return directory = argv[1] if(not exists(directory)): print("Specified path ", directory," does not exist.") return if (not isdir(directory)): print (directory , "exists, but doesn't name an actual directory.") filename = argv[2] listAllExactMatches(directory, filename) # test code listAllExactMatches("/Users/zhezhang/Documents/MyGitProjects/PythonCodes/", "find.py")
true
9b16cc21ec0857141c7c359bf9a9ed5d8f72868a
ravgeetdhillon/hackerrank-algo-ds
/Extract_Number.py
341
4.375
4
numbers=['0','1','2','3','4','5','6','7','8','9'] print('***PROGRAM : To extract the valid phone number from the string***') a=str(input('Input your string : ')) p='' for char in a: if char in numbers: p=p+char if len(p)==10: print('The phone number is',p) else: print("Your input doesn't contain a valid phone number!")
true
75febbcc0d60df375dd9990b256fb1f35f330aa1
balaprasanna/Trie-DataStructure
/trie.py
2,254
4.125
4
#!/usr/bin/python # -*- coding: utf-8 -*- class trieNode: """ leaf to indicates end of string """ def __init__(self): self.next = {} self.leaf = False """function to add a string to trie""" def add_item(self, item): i = 0 while i < len(item): k = item[i] if not k in self.next: node = trieNode() self.next[k] = node self = self.next[k] if i == len(item) - 1: # if last character then mark it as a leaf node self.leaf = True else: self.leaf = False i += 1 """ function to search a string in the created trie """ def search(self, item): if self.leaf and len(item) == 0: return True first = item[:1] # get start character of string to search in trie str = item[1:] # get remaining char of string if first in self.next: return self.next[first].search(str) else: return False """ function to perform autocompletion.traverses till the last char of seached string inside trie and then performs a dfs traversal from the current node to get all child nodes under the nodes and concatenate to get final strings (for eg, ab is passed and trie contains abc and abd,then traverses till ab and do dfs to get abc and abd """ def dfs(self, item): if self.leaf: print item for i in self.next: s = item + i self.next[i].dfs(s) def autocomplete(self, item): i = 0 s = '' while i < len(item): k = item[i] s += k if k in self.next: self = self.next[k] else: return 'not found' i += 1 self.dfs(s) return '###end###' list = [ 'sin', 'singh', 'sign', 'sinus', 'sit', 'silly', 'side', 'son', 'soda', 'sauce', 'sand', 'soap', 'sar', 'solo', 'sour', 'sun', 'sure', 'and', 'ask', 'animal', 'an', 'ant', 'aunt', ] x = trieNode() for i in list: x.add_item(i) print x.autocomplete('so')
true
0fa387eb77e0e0143b6390cec53c0edc123bc670
soumyax1das/soumyax1das
/string_format.py
434
4.1875
4
""" This function shows how to use format method in different ways Author :: Soumya Das """ import math def string_format(str): print(str.format('val1','val2','val3')) def string_format_import_math_library(str): print(str.format(m=math)) if __name__ == '__main__': string_format('parm1={} parm2={} parm3={}') string_format('parm1={1} parm2={0} parm3={2}') string_format_import_math_library('Value of PI is {m.pi}')
false
d7bc082d5a94cd74332333f1b94beac9264711fb
soumyax1das/soumyax1das
/list_index_and_slicing.py
420
4.125
4
#!/usr/bin/env python3 def string_index_example(lst,indx): print('Actual String is -',lst) print('Value at index',indx,'is',lst[indx]) def string_slice(lst): print(lst[-2:-1]) print(lst[-2:]) if __name__ == '__main__': str="Hello this is Soumya Das" ###Create a list from a string### lst=list(str.split()) string_index_example(lst,3) string_index_example(lst,-1) string_slice(lst)
false
7c19c4a9425947694aa49fcdd30ff905e044df7d
soumyax1das/soumyax1das
/simpleWhile.py
320
4.15625
4
""" This is a simple program to demonstarte the while loop in Python """ def create_pyramid(height): i=1 while(i<=height): i=i+1 print('i is',i) if i == 4: #continue pass print('+'*i) print('*'*i) if __name__ == '__main__': create_pyramid(5)
true
8e2059b1be305f600cf4f0c1db5addd0da218cbe
yang-official/LC
/Python/4_Trees_and_Graphs/2_Graph_Traversal/207_course_schedule.py
2,170
4.125
4
# https://leetcode.com/problems/course-schedule/ # 207. Course Schedule # There are a total of n courses you have to take, labeled from 0 to n-1. # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? # Example 1: # Input: 2, [[1,0]] # Output: true # Explanation: There are a total of 2 courses to take. # To take course 1 you should have finished course 0. So it is possible. # Example 2: # Input: 2, [[1,0],[0,1]] # Output: false # Explanation: There are a total of 2 courses to take. # To take course 1 you should have finished course 0, and to take course 0 you should # also have finished course 1. So it is impossible. # Note: # The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. # You may assume that there are no duplicate edges in the input prerequisites. def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = [[] for _ in range(numCourses)] degree = [0 for _ in range(numCourses)] for c in prerequisites: degree[c[0]] += 1 graph[c[1]].append(c[0]) queue = [] for i in range(len(degree)): if not degree[i]: queue.append(i) count = 0 while queue: cur = queue.pop(0) count += 1 for i in range(len(graph[cur])): degree[graph[cur][i]] -= 1 if degree[graph[cur][i]] == 0: queue.append(graph[cur][i]) return numCourses == count # Initially we add all the courses withought any prerequisite to our queue. # As long as this queue is not empty we pick a course and update the dictionaries. # SO if we pick 2 we find [3,4] using pre dictionary and for each we decrement their # value by one in the count dictionary. If the count dictionary for any of them # is zero it means that their prerequisites have been met and they are ready to be # picked so we add them to the queue.
true
7e83e498e6841fa9db31c32c9591dfe5da8112ad
theknewkid/knewkidcalculator
/backend-code/calculations.py
1,206
4.46875
4
#Let's set up functions for the different calculations here. We'll create a float from the user's input. hey = "Welcome to my very elementary calculator!" print(hey) def addition(): '''This is a function for adding.''' a = float(input("Enter a number. ")) b = float(input("Enter another number. ")) print(a + b) def subtraction(): """This is a funciton for subtracting.""" a = float(input("Enter a number. ")) b = float(input("Enter another number. ")) print(a - b) def multiply(): '''This is a function for multiplying.''' a = float(input("Enter a number. ")) b -= float(input("Enter another number. ")) print(a * b) def division(): '''This is a function for multiplying.''' a = float(input("Enter a number. ")) b = float(input("Enter another number. ")) print(a / b) #This is where the user will choose either addition, subtraction, multiplication, or division. calc = input("Here's how this works. Type either +, -, *, or / ") if calc == "+": addition() elif calc == "-": subtraction() elif calc == "*": multiply() elif calc == "/": division() else: print("The selection is invalid. Please choose again. ")
true
bfdcaf2efb90c0318c26a74d1e4c18ace6a781a2
Liu-YanP/DataStructure
/DoubleQueue.py
1,262
4.53125
5
#双端队列 ''' 双端队列(deque,全名double-ended queue),是一种具有队列和栈的性质的数据结构。 双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行。 双端队列可以在队列任意一端入队和出队。 操作 Deque() 创建一个空的双端队列 add_front(item) 从队头加入一个item元素 add_rear(item) 从队尾加入一个item元素 remove_front() 从队头删除一个item元素 remove_rear() 从队尾删除一个item元素 is_empty() 判断双端队列是否为空 size() 返回队列的大小 ''' class Deque(object): """双端队列""" def __init__(self): self.items = [] def is_empty(self): return self.items==[] def add_front(self,item): self.items.insert(0,item) def add_rear(self,item): self.items.append(item) def remove_front(self): return self.items.pop(0) def remove_rear(self): return self.items.pop() def size(self): return len(self.items) #测试 if __name__ == '__main__': deque = Deque() deque.add_front(1) deque.add_front(2) deque.add_rear(3) deque.add_rear(4) print('长度',deque.size()) print(deque.remove_rear()) print(deque.remove_rear()) print(deque.remove_front()) print(deque.remove_front())
false
fc7dc9c3c7f6999c57faf2a49dd43bb0a316bc65
Liu-YanP/DataStructure
/Queue.py
730
4.375
4
#队列的实现 ''' 同栈一样,队列也可以用顺序表或者链表实现。 操作 Queue() 创建一个空的队列 enqueue(item) 往队列中添加一个item元素 dequeue() 从队列头部删除一个元素 is_empty() 判断一个队列是否为空 size() 返回队列的大小 ''' class Queue(object): """队列""" def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self,item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) #测试 if __name__ == '__main__': queue = Queue() queue.enqueue('hello') queue.enqueue('liu') print(queue.size()) print(queue.dequeue()) print(queue.size())
false
f1d80ec4d8de02adbb016bbf7a094ed24d1b9fbe
swathiswaminathan/guessing-game
/game.py
1,640
4.21875
4
"""A number-guessing game.""" # Put your code here import random print "Welcome to the game!" name = raw_input("What's your name? ") print"Choose a random number, %s" % (name) # secret_num = random.randint(1, 100) #print " the secret number is %d" % (secret_num) # guess = None # too_high = 100 # too_low = 0 # count = 0 def continue_game(): user_choice = raw_input("Would you like to play again? Say 'yes' or 'no'").lower() if user_choice == 'yes': guessing_game() elif user_choice == 'no': return def guessing_game(): secret_num = random.randint(1, 100) guess = None too_high = 100 too_low = 0 best_count = 100 count = 0 while guess != secret_num: count = count + 1 try: guess = int(raw_input("Guess the number: ")) if guess > 100 or guess < 1: print "invalid input, WHAT WERE YOU THINKING?! Enter a number between 1 and 100" #guess = int(raw_input("Guess the number: ")) elif guess > secret_num: too_high = guess print "%d too high, guess again" % (guess) elif guess < secret_num: too_low = guess print "%d too low, guess again" % (guess) except ValueError: print "Enter a valid number!" print "You got it! The number is %d"%(guess) print "The number of guesses is %d" %(count) continue_game() if count < best_count: best_count = count print "The best number of guesses you gave was %d" %(best_count) guessing_game()
true
b0d5c7e842af58cd8d159e137f94a6eab79e5428
sfGit2Hub/PythonLearn
/PythonDemo/static/max_cost_assignment.py
1,058
4.40625
4
import dlib # So in this example, let's imagine we have 3 people and 3 jobs. We represent # the amount of money each person will produce at each job with a cost matrix. # Each row corresponds to a person and each column corresponds to a job. So for # example, below we are saying that person 0 will make $1 at job 0, $2 at job 1, # and $6 at job 2. cost = dlib.matrix([[1, 2, 6, 5], [5, 3, 6, 4], [4, 5, 0, 1], [4, 2, 1, 6],]) # To find out the best assignment of people to jobs we just need to call this # function. assignment = dlib.max_cost_assignment(cost) # This prints optimal assignments: [2, 0, 1] # which indicates that we should assign the person from the first row of the # cost matrix to job 2, the middle row person to job 0, and the bottom row # person to job 1. print("Optimal assignments: {}".format(assignment)) # This prints optimal cost: 16.0 # which is correct since our optimal assignment is 6+5+5. print("Optimal cost: {}".format(dlib.assignment_cost(cost, assignment)))
true
3a167a50a74c630eaa197f4188b3baffb20eeced
ua114/py4e
/week1.py
1,221
4.1875
4
# Using strong functions # fruit = 'banana' # print(len(fruit)) #Lengh of the string # fruit = 'mango' # count = 0 # while count < len(fruit): # print(count, fruit[count]) # count = count +1 # print('Done') # # for letter in 'banana': # print(letter) # word = 'abrasion' # count = 0 # a_count = 0 # # for i in word: # if i =='a': # a_count = a_count + 1 # count = count + 1 # print(count, a_count) # word = 'once upon a time' # print(word[:5]) # print(word[5:]) # print(word[:]) # in is a logical operator # fruit = 'pineapple' # # if 'a' in fruit: # print('a is present') # String commands: lowercase, locating # greet = 'HELLO world' # greet_lower = greet.lower() # # fruit = 'tomato' # pos = fruit.find('o') # print(pos) # # greet_2 = 'Good Morning' # print(greet_2.replace('Morning', 'Evening')) # print(greet_2.replace('o','u')) # Removing white space # greet = ' Hello World ' # print(greet) # print(greet.lstrip()) # print(greet.rstrip()) # print(greet.strip()) # Starts with # line = 'Please close the doors' # print(line.startswith('Please')) # Exercise 6.5 str = 'X-DSPAM-Confidence:0.8475' pos = str.find(':') data = str[pos+1 :] data = float(data) print(data)
true
0961deb46fd0ad1a27f842950979a5cb87188a74
anjan111/python_8pm
/002_Built-in-function/003_built-in/004_unput_raw_float.py
464
4.15625
4
# raw_input vs input ''' ===>> rawinput is resultant datatype is str for any data ===>> input is resultant datatype is based data ''' a = raw_input("enter float by raw : ") print "data in a " ,a print(type(a)) print "memory : ",id(a) a = bool(a) print "data in a " ,a print(type(a)) print "memory : ",id(a) a = input("enter float by input : ") print "data in a " ,a print(type(a)) print "memory : ",id(a) # datatype conversion functions
false
625b9dc82f0deea1a6a81f5496679a6ab30dbbbf
khyathipurushotham/python_2
/matrix_subraction.py
884
4.1875
4
row = int(input("enter the row numbers:")) col = int(input("enter the col number:")) print("enter the elements for matrix1:") matrix1 = [[int(input()) for i in range (col)] for j in range(row)] print("matrix1:") for i in range (row): for j in range (col): print(format(matrix1[i][j],"<3"),end="") print() print("enter the elements for matrix2:") matrix2 = [[int(input()) for i in range (col)] for j in range(row)] print("matrix2:") for i in range (row): for j in range (col): print(format(matrix1[i][j],"<3"),end="") print() result = [[0 for i in range (col)] for j in range (row)] for i in range(row): for j in range (col): result[i][j] = matrix1[i][j] - matrix2[i][j] for i in range(row) : for j in range (col): print(format(result[i][j],"<3"),end="") print()
false
f940e67265df7b83165a5aed6a153bd311b2d35a
yufang2802/CS1010E
/checkOrder.py
338
4.375
4
integer = input("Enter positive integer ") def check_order(integer): previous = 0 while (integer > 0 and integer > previous): previous = integer integer = int(input("Enter positive integer ")) if integer == 0: print("Data are in increasing order.") else: print("Data are not in increasing order.") check_order(int(integer))
true
2008f04cd95611d3f205817998af5534a1624bae
yufang2802/CS1010E
/factorial.py
376
4.125
4
#using recursion def getFactorial(n): if n < 2: return 1 else: return n * getFactorial(n-1) #using iteration (loops) def getFactorial2(n): if n > 2: factorial = 1 for i in range(1, n+1): factorial *= i return factorial number = int(input("Enter n: ")) print(getFactorial(number)) print(getFactorial2(number))
false
4e6e1082fa4cd3c3b102eec8cdbc7de38673004e
TutorialDoctor/Scripts-for-Kids
/Python/math_basic.py
661
4.1875
4
# Get the sum of two numbers a and b def sum(a,b): return a+b # Get the difference of two numbers a and b def difference(a,b): return a-b # Get the quotient of two numbers a and b where b cannot equal 0 # You have to use a float somewhere in your dividion so that the answer comes out as a float # A float is a number with a decimal def quotient(a,b): if b != 0: return a/float(b) # Get the product of two numbers: def product(a,b): return a*b # That's it for basic math in a computer program! # No cheating on your homework! Hehe ;) print quotient(2232,2322) print product(23.134,132.34) print sum(2314,46426) print difference(8,3546456345)
true
0cf6a75530b43c968ab95fd2e2623369bbd9b5d9
siraom15/coffee-to-code
/Python/SmilealniS.py
219
4.125
4
# coffee = input() coffee = "coffee" code = "" words = coffee.split(' ') for word in words: if word == 'coffee': code += 'code' else: code += word code += ' ' code = code.rstrip() print(code)
false
acec8f27e351ee18087d6abb276a695dc95180a9
Rhylan2333/Python35_work
/精品试卷 - 10/基本操作题 3:字典交换.py
417
4.4375
4
#在......上填写一段代码 def reverse_dict(dic): out_dic = {} ## print(dic.items()) for key, value in dic.items(): ## print(key, value) out_dic[value] = key keys = sorted(out_dic.keys(), reverse = True) # 返回一个列表 ## print(keys) for key in keys: print(key, out_dic[key]) return out_dic #请输入一个字典 dic = eval(input("")) reverse_dict(dic)
false
34e739f02434bd9530cafc88adb65a6efe3bc4ec
sinvalfelisberto/python_curso_video
/aula10/exercicio/aula10_02.py
315
4.375
4
# estruturas condicionais valor = int(input('Quantos anos tem seu carro?: ')) if valor <= 3: print('Seu carro ainda está novo!') else: print('Seu carro está velho') print('--- Fim ---') # outra forma de fazer uma condicional print('Seu carro ainda está novo!' if valor <=3 else 'Seu carro está velho!')
false
33703def35ae0f6298b06ca4e49c2f3a49d2ba4f
Dishvater/sda_pycharm_python
/python podstawy d2/d2/python_basic/python_basic/zad/z03_leap_year.py
787
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_leap_year(year: str): if not int(year) % 4 and not year.endswith('00'): return True elif not int(year) % 400 and year.endswith('00'): return True else: return False def is_leap_year_2(year: str): if year.endswith('00'): if not int(year) % 400: return True else: if not int(year) % 4: return True return False if __name__ == '__main__': while True: my_year = input('Input a year: ').strip() answer = 'is' if is_leap_year_2(my_year) else 'is not' print(f'Year {my_year} {answer} a leap year\n') shall_continue = input('Do you want to continue (y/n)?: ') if shall_continue != 'y': break
false
c5e9594da3c8e46845d7428ec06c6cbac40b4499
saisurajpydi/Python
/Python/Lists.py
1,040
4.5625
5
fruits = ["apple","banana","orange","kiwi"] fruits.append("cherry")# to add element at last print(fruits) fruits.insert(2,"watermelon") # to add at index 2 print(fruits) print(fruits[1]) # to get the element at index 1 print(fruits[1:4]) # to get the element from 1-3 # print using for loop for i in fruits: print(i) print("using while loop ") i = 0 while i < len(fruits): print(fruits[i]) i += 1 print(" using another loop method " ) [print(x) for x in fruits] tropical = ["mango", "pineapple", "papaya"] # new list fruits.extend(tropical) # to merge the lists print(fruits) # to copy one list to another # remove pop del clear fruits.remove("banana") print("remove " ,fruits) fruits.pop(1) print("pop(1) " ,fruits) fruits.pop() print("pop() " ,fruits) del fruits[2] print(" del fruits(2) " ,fruits) tropica = ["mango", "pineapple", "papaya"] # new list del tropica print("tropica deletes whole list" , tropica) tropic = ["mango", "pineapple", "papaya"] # new list tropic.clear() print("clears tropic list" , tropic)
false
732cb6de8566d69a84813850a25d426d862944f8
Shailendre/simplilearn-python-training
/section1 - basic python/lesson6.5.py
1,233
4.28125
4
# tuple and list # tuple: immutable # sicnce tuple is immutable its fast in traversal and other operations def example(): # this is called sequence packing return 13,13 # this is sequence unpacking a,b = example() print(a) # list ll = [2,4,1,7,3,9,3,8,6,4,0] # list size print ("original length:", len(ll)) # list append, add to the end # ll.append('Hello') # adding str is possible but some operations will not be supported ll.sort() ll.append(67) # list access print(ll[len(ll) - 1]) # list sort ll.sort() # return 'None', similar to 'void' in java print(ll) # this will print the sorted instance # list insert, for inserting ta index ll.insert(5,23) print (ll); # list index, find the index of element try: print(ll.index(3)) # returns the first index print(ll.index(43)) # return 'ValueError' if value not found except ValueError as e: print(str(e)) # list count, count the frequnecy print(ll.count(3)) print(ll.count(55)) # returns expcected 0 # list remove, remove the first occurence print("before removing", ll) ll.remove(3) # removes first '3' print ("after removing",ll) # list reverse; # THIS IS NOT REVERSE SORTING, # ONLY REVERING THE EXISTING LIST ll.reverse(); print ("reverse ll", ll)
true
da06aa6567f4495284792a7196f01af46ecacb19
zahranorozzadeh/tamarin4
/tamrin4-3.py
255
4.5
4
# Python Program to print table # of a number upto 10 def table(n): for i in range (1, 11): # multiples from 1 to 10 print (n, i, n * i) # number for which table is evaluated n = 5 table(n) # This article is contributed by Shubham Rana
true
f1938f6cdb52543c85729a355584a25fd52ab9c4
smspillaz/fair-technical-interview-questions
/python/default.py
303
4.28125
4
#!/usr/bin/env python # # This code *should* print [1], [2] but does something different. Can # you explain why and how you would fix the problem? def append(element, array=[]): """Return element as appended to array.""" array.append(element) return array print(append(1)) print(append(2))
true
fad067e667888ea23e5903f5b76eab36192ca521
ZeyadAl/small-python-programs
/balance.py
473
4.375
4
''' we are given 3 variablees 1) balance 2) annual interest rate 3) monthly min rate first calculate monthly interest rate ''' balance= float(input('Balance ')) annual= float(input('Annual interest rate ')) minrate= float(input('monthly Min rate ')) paid=0 mint= annual/12 for i in range(12): balance= balance*(mint+1) balance-=balance*minrate paid+=balance*minrate print(round(balance, 2)) print ('remaining balance', str(round(balance, 2)), str(paid))
true
ac86491af11e13ad77e3f266aba3e241a72f6476
deesaw/PythonD-03
/Databases/sqlite3Ex/selectTable.py
618
4.25
4
import sqlite3 conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() sql = "SELECT * FROM cars" print ("listing of all the records in the table:") for row in cursor.execute(sql): print (row) print ("Results...") cursor.execute(sql) print(len(cursor.fetchmany(3))) for id,carname,price in cursor.fetchall(): print ("The car is {} and its price is {}".format(carname,price)) print('***********') cursor.execute(sql) print(cursor.fetchmany(3)) #for id,carname,price in t: # print ("The car is {} and its price is {}".format(carname,price)) conn.close() ''' fetchmany(2) fetchone() fetchall() '''
true
768615562d1ba0d17b4e7a473ee8819bfd02da13
deesaw/PythonD-03
/Data Structures/7_dictionary.py
750
4.28125
4
#dictionary marks={'Maths':97,'Science':98,'History':78} print(marks) print(type(marks)) print(len(marks)) print(sum(marks.values())) print(max(marks.values())) print(min(marks.values())) print(marks.keys()) #prints keys from the dictionary print(marks.values()) #prints values from the dictionary print(marks.items()) #prints keys and values from the dictionary,returns list of tuples #printing value of the element from the dictionary print(marks['History']) #adding new item to the dictionary marks['Computers'] = 90 print(marks) #Changing the value of the existing key marks['History']=80 print(marks) #removing an element from the dictionary del marks['History'] print(marks)
true
b5017c4fce9992d652e6cbd57056ab8ab36e3c5c
kingkongmok/kingkongmok.github.com
/bin/test/python/ex42.py
1,852
4.40625
4
#!/usr/bin/python # http://learnpythonthehardway.org/book/ex42.html # Is-A, Has-A, Objects, and Classes ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal, has a function named __init__ that taks self, name parameters. class Dog(Animal): def __init__(self, name): ## Class Dog has-a __init__ that taks self and name as parameters self.name = name ## make a new class named Cat that is-a Animal class Cat(Animal): def __init__(self, name): ## Class Cat has-a __init__ that takes self, name as parameters self.name = name ## make a new class named Person that is-a object class Person(object): def __init__(self, name): ## from Person.this set the attribute of name as parameter name self.name = name ## Person has-a pet of some kind self.pet = None ## ?? class Employee(Person): def __init__(self, name, salary): """ That's how you can run the __init__ method of a parent class reliably. Search for "python super" and read the various advice on it being evil and good for you. """ ## ?? hmm what is this strange magic? super(Employee, self).__init__(name) ## set the attribute of this.salary as salary parameters self.salary = salary ## Fish is-a object class Fish(object): pass ## make a class Salmon is-a Fish class Salmon(Fish): pass ## make a class Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? satan = Cat("Satan") ## ?? mary = Person("Mary") ## from mary get pet attribute and set it to satan mary.pet = satan ## ?? frank = Employee("Frank", 120000) ## ?? frank.pet = rover ## ?? flipper = Fish() ## ?? crouse = Salmon() ## ?? harry = Halibut()
true
0d55bfc50430c186b8c46fa816a23b27838f2aab
thuaung23/elementary-sortings
/main.py
2,511
4.125
4
# This program uses elementary sorts, such as selection, insertion and bubble. # This program is written in object oriented programming. # Written by: Thu Aung # Written on: Oct 11,2020 """ These elementary sorting algorithms are good for only smaller input sizes because the time complexity of them is quadratic, O(N^2). """ class Sorting: def __init__(self, item): self.item = item def select_sort(self): for i in range(len(self.item)): # Create minimum for comparison. i_min = i for j in range(i+1, len(self.item)): if self.item[j] < self.item[i_min]: # If condition is met, minimum is assigned to lesser item. i_min = j # Swap positions. self.item[i], self.item[i_min] = self.item[i_min], self.item[i] return self.item def insert_sort(self): # Item at index[0] is considered as sorted. for i in range(1, len(self.item)): # Hold the value of item at index[i] in a variable, key. key = self.item[i] # To compare value of item/items (located before index[i]) with key. j = i-1 while j>=0 and key < self.item[j]: # If conditions met, move item to the right. self.item[j+1] = self.item[j] # This is to continue moving until one of conditions is false. j-=1 # After breaking out of loop, the next item after sorted items becomes key. self.item[j+1] = key return self.item def bubble_sort(self): # Scan the whole list. for i in range(len(self.item)-1): # A counter to break out of loop if already sorted. no_swap = 0 # After first pass, last item reached to last index. Thus, for second pass, scan up to n-2 and so on. for j in range(len(self.item)-i-1): if self.item[j] > self.item[j+1]: # Swap items if condition is true. self.item[j], self.item[j+1] = self.item[j+1], self.item[j] no_swap += 1 if no_swap == 0: break return self.item # Example Usage arr_1 = [2,6,8,4,9,2,1,4,3,6,9,7,5,1,2,3] sorted_arr1 = Sorting(arr_1) print("Unsorted: ", arr_1) print("Selection Sort: ", sorted_arr1.select_sort()) print("Bubble Sort: ", sorted_arr1.bubble_sort()) print("Insertion Sort: ", sorted_arr1.insert_sort())
true
52fed17125980a152cc0c90ef0a0cd21fa87c10b
caffwin/rev-string
/reverse-string.py
2,816
4.375
4
from pprint import pprint # Reverse a string in place # Input: string # Output: string # Strings are immutable in python, so use a list # "hello" > "olleh" # h e l l o # 0 1 2 3 4 # 0 <-> 4 # or.. 0 <-> -1 # 1 <-> 3 # or.. 1 <-> -2 # 2 stays in place (no work done) # h e l l o o # 0 1 2 3 4 5 # ^ ^ # 0 <-> 5 # 1 <-> 4 # 2 <-> 3 # Establish a front and end pointer to track indices to swap # As long as beginning pointer is less than or equal to end pointer, # swap the elements in those indices def rev_string_in_place(str): sample_test = 5/2 # Rounds down list_string = list(str) length = len(str) for i in range(0, length/2): # len(hello) is 5, length is 2 # list_string[2 - 1 - i] list_string[i], list_string[len(str) - 1 - i] = list_string[len(str) - 1 - i], list_string[i] print(sample_test) return list_string print(rev_string_in_place("Hello")) def rev_str_in_place_pointers(list_chars): left_pointer = 0 right_pointer = len(list_chars) - 1 # As long as left pointer is less than right pointer.. # Swap the pointers - middle letter can be left alone if it's an odd # of chars while left_pointer < right_pointer: list_chars[left_pointer], list_chars[right_pointer] = list_chars[right_pointer], list_chars[left_pointer] left_pointer += 1 right_pointer -= 1 return list_chars print(rev_str_in_place_pointers(['H', 'E', 'N', 'L', 'O'])) # class Test(object): # def __init__(self, a): # self.a = a # def __repr__(self): # return "<Repr Test a:%s>" % (self.a) # def __str__(self): # return "From str method of Test: a is %s" % (self.a) # Reverse string using a stack class Stack(object): def __init__(self): self.items = [] def __str__(self): return "String of self.items: " + str(self.items) def push(self, item): self.items.append(item) def pop(self): if not self.items: print("Can't remove from empty stack") return False self.items.pop() def reverse_order(self, string): # Create an empty stack, and keep track of the length of the string print("String is: ", string) length_str = len(string) string_stack = Stack() # this is a list, refer to elements using string_stack.items for i in range(0, length_str, 1): print("String at i is: ", string[i]) string_stack.push(string[i]) # p = pprint(vars(string_stack)) reversed_string = "" for i in range(0, length_str, 1): reversed_string += string_stack.items.pop() return reversed_string # H E L L O # 1 2 3 4 5 Normal access sequence # 5 4 3 2 1 Access via Stack
true
218350fa2a2e5fb0ac0226a9ff64a9bf29ffa935
samrana1996/python-code
/Grocery_shop.py
1,735
4.125
4
print(" Hello Friends! ") print(" What Item do you want to buy ?") print(" You may Check our Product_List") product = ["Rice", "Cereal", "Soap", "Biscuit", "Chips"] catagory = ({"Basmati Rice": 90, "Gouri": 85, "Gobindovog": 79, "Golden Silky Rice": 26, "Normal Rice": 50}, {"Arhar Dal": 271, "Toor Dal": 212, "Chana Dal": 150, "Green Moong Dal": 200,}, {"Fiama Gel Bar": 192, "Dettol": 206, "Pears": 192, "Dove": 312, "Santoor": 132, "Savlon": 150,}, {"Little heart": 13, "Parle g gold": 100, "Horlicks": 90, "Britannia": 30,}, {"Lays": 40, "Kurkure": 45, "jolochip": 199, "maxx": 10, }) cart = [] price = [] while (1): x = input("Any Item do you want to buy? Press- y / Press- n to exit") if x == "n": break if x == "y": print("Available products:") for i in product: print(i) p = input("What product do you want?") indx = product.index(p) for i, j in catagory[indx].items(): print(i, ":", j) item = input("Which type do you want?") qnty = int(input("How many product you need??")) cart.append(item) price.append(catagory[indx][item] * qnty) # if x=="yes": print(cart, price) total = sum(price) print("____________ INVOICE_____________") print("The Total Price is :", total) print("""Go to Cart and Checkout.... Thank You For Shopping With Us!""")
false
2c655db1e97429eeb8bc525cbc9d5408f6edeaf9
appleboy919/python_DS_ALG
/ch4_Queue/myQueue.py
1,147
4.25
4
# application: # CPU scheduling # asynchronous data between two processes # graph traversal algorithm # transport, operations management # file servers, IO buffers, printer queues # phone calls to customer service hotlines # !! resource is shared among multiple consumers !! # head <-> rear (tail) # FIFO # head: remove / rear: add # operations: enqueue, dequeue # using list to implement Queue is not efficient ! since insert, pop from the beginning of a list is slow ! # ==> use 'Deque' data structure (double-ended queue) from collections import deque class Queue: def __init__(self): self.items = deque() def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.popleft() def is_empty(self): return not self.items def size(self): return len(self.items) def peek(self): return self.items[0] def __str__(self): return str(self.items) if __name__ == '__main__': q = Queue() print(q) print(q.is_empty()) q.enqueue('a') q.enqueue('b') q.enqueue('c') print(q) print(q.dequeue()) print(q)
true
0c9f99988ba5ce914094e28cccf2c85a008ee8b6
GintautasButkus/20210810_Coin-Flip-Streaks
/Coin Flips.py
2,384
4.34375
4
# Coin Flip Streaks # For this exercise, we’ll try doing an experiment. If you flip a coin 100 times # and write down an “H” for each heads and “T” for each tails, you’ll create # a list that looks like “T T T T H H H H T T.” If you ask a human to make # up 100 random coin flips, you’ll probably end up with alternating headtail # results like “H T H T H H T H T T,” which looks random (to humans), # but isn’t mathematically random. A human will almost never write down # a streak of six heads or six tails in a row, even though it is highly likely # to happen in truly random coin flips. Humans are predictably bad at # being random. # Write a program to find out how often a streak of six heads or a streak # of six tails comes up in a randomly generated list of heads and tails. Your # program breaks up the experiment into two parts: the first part generates # a list of randomly selected 'heads' and 'tails' values, and the second part # checks if there is a streak in it. Put all of this code in a loop that repeats the # experiment 10,000 times so we can find out what percentage of the coin # flips contains a streak of six heads or tails in a row. As a hint, the function # call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value # the other 50% of the time. # You can start with the following template: # import random # numberOfStreaks = 0 # for experimentNumber in range(10000): # # Code that creates a list of 100 'heads' or 'tails' values. # # Code that checks if there is a streak of 6 heads or tails in a row. # print('Chance of streak: %s%%' % (numberOfStreaks / 100)) # Of course, this is only an estimate, but 10,000 is a decent sample size. # Some knowledge of mathematics could give you the exact answer and save # you the trouble of writing a program, but programmers are notoriously # bad at math. import random number_of_streaks = 0 coin_flips = [] streak = 0 for experiment_number in range(10000): for i in range(100): coin_flips.append(random.randint(0,1)) for i in range(len(coin_flips)): if i == 0: pass elif coin_flips[i] == coin_flips[i-1]: streak += 1 else: streak = 0 if streak == 6: number_of_streaks += 1 coin_flips = [] print('Chance of streak: %s%%' % (number_of_streaks / (100 * 10000)))
true
791fe6d02d0a5a85f62db34d82a35e07aa72aeb7
greenca/exercism-python
/wordy/wordy.py
945
4.15625
4
operators = {'plus':'+', 'minus':'-', 'multiplied':'*', 'divided':'/'} def calculate(question): question_words = question.split(' ') if question_words[:2] == ['What', 'is']: question_words = question_words[2:] num1 = question_words.pop(0) op = question_words.pop(0) num2 = question_words.pop(0) if num2 == 'by': num2 = question_words.pop(0) if num2[-1] == '?': num2 = num2[:-1] try: int(num1) int(num2) except: raise ValueError('Invalid number') try: expression = num1 + operators[op] + num2 except: raise ValueError('Invalid operator') val = eval(expression) if question_words: return calculate('What is ' + str(val) + ' ' + ' '.join(question_words)) else: return val else: raise ValueError('Invalid question')
true
9c895d9990c777c0ecd1310d316ad10ca69b7cf8
vdpham326/python-data-structures
/dictionary/find_anagrams.py
892
4.28125
4
words = ['gallery', 'recasts', 'casters', 'marine', 'bird', 'largely', 'actress', 'remain', 'allergy'] def find_anagrams(list): new = {} #key should store strings from input list with letters sorted alphabetically for word in list: key = ''.join(sorted(word)) if key not in new: new[key] = [] #set the key in alphabet order and equal to an empty list for value new[key].append(word) #value should contain a list of words from the input list which are anagrams for the given key return new #alternative method using get() method def find_anagrams2(list): new = {} #key should store strings from input list with letters sorted alphabetically for word in list: key = ''.join(sorted(word)) new[key] = new.get(key, []) + [word] return new #print(''.join(sorted(words[0]))) print(find_anagrams2(words))
true
59aa697109d141faa171bfb00ddee85cac9e153f
vdpham326/python-data-structures
/tuple/get_values.py
608
4.3125
4
''' Create a function named get_min_max_mean(numbers) that accepts a list of integer values and returns the smallest element, the largest element, and the average value respectively – all of them in the form of a tuple. ''' def get_min_max_mean(numbers): smallest, largest, total = numbers[0], numbers[0], 0 for number in numbers: total += number if number < smallest: smallest = number if number > largest: largest = number average = total / len(numbers) return (smallest, largest, average) print(get_min_max_mean([1, 2, 3, -1, -2, -3])) #expect (-3, 3, 0.0)
true
d7528247c450cbd739a07c58dae1d6812250c192
hiukongDan/EulerMethod
/EulerMethod.py
802
4.1875
4
#!/usr/python class EulerMethod: def __init__(self, diffFunc, initX, initY): self.func = diffFunc self.init = [initX, initY] def plot(self, stop, step): dot = [self.init[0], self.init[1]] while dot[0] <= stop: print("(%f,%f)"%(dot[0],dot[1])) slope = self.func(dot[0], dot[1]) dot[1] = dot[1] + slope * step dot[0] += step if __name__ == '__main__': print("Python Script: Euler's Method\nUseage: calculating value of given differential equation using euler's method") print("Example: dy/dx = 6*x*x - 3*x*x*y with f(0) = 3") M = EulerMethod(lambda x, y: 6*x*x-3*x*x*y, 0,3) print("step = 1") M.plot(1,1) print("step = 0.1") M.plot(1, 0.1)
false
bca033e9e874316c0386fc7efc55cc3e4034ff4c
dignakr/sample_digna
/python-IDLE/item_menu_ass1.py
1,892
4.25
4
class ItemList: def __init__(self, itemname, itemcode): self.itemname = itemname self.itemcode = itemcode def display(self): print '[itemname :',self.itemname,',itemcode :',self.itemcode,']' if __name__=="__main__": ans=True l=list() while ans: print (""" 1.Add items 2.Display items 3.Delete Items 4.View Items 5.Exit/Quit """) ans=raw_input("What would you like to do? ") if ans=="1": itemname=raw_input("Enter item name: ") itemcode = raw_input("Enter item code: ") item1=ItemList(itemname,itemcode) l.append(item1) elif ans=="3": c=raw_input("which item to delete? ") for i in l: if i.itemname==c: k=l.index(i) l.remove(i) print'The item is deleted successfully' elif ans=="2": for item in l: item.display() elif ans=="4": itm=raw_input('Enter an item you want to be displayed :') for i in l: if i.itemname==itm: k=l.index(i) print 'The index of the item is :',k temp=l[k] print 'The Item details are :[itemname :',temp.itemname,',itemcode :',temp.itemcode,']' elif ans=="5": print("\n bye") exit() else: print("\n Not Valid Choice Try again")
true
d76e737379f2afd92f4dce9f74ac73593d674980
John-Ming-Ngo/Assorted-Code
/PureWeb_Submission/Shuffle.py
2,853
4.4375
4
import random as rand import copy ''' This function, given an input value N, produces a randomized list with each value from 1 to N. Naively, this can be done by actually simulating a real shuffle, as I did in a prior assignment, but since we want to optimize for speed, we're going to have to be more creative. The first idea that came to mind was to lay out all the 'cards', then randomly pick a card index, then take the card at that index and put it into my new random shuffle. The problem, here, is that removing from an arbitrary index in a Python list is O(n), so if I do this n times, I get an O(n^2) algorithm, which is no better than naively shuffling! Clearly, the problem is with removing. But the trick is, editing entries is an O(1) operation! So why don't we just boot it to the end of the list by exchanging it with whatever was at the end of the list, and then stop considering that end of the list? ''' ''' Card index 'removal' shuffle. Since removal is costly, but editing the values of the list aren't, the current idea is to boot the chosen element to the 'end of the list' by exchanging it with the value at the end of the list, then decrement the 'size of the list' counter. Algorithm should be an O(N) algorithm, where N is length of the input list. Parameters: inputList: An input list of any sort of item. Returns: outputList: A new list containing the elements of the input list, shuffled. Maybe Improve: random.randint is known to be relatively costly; if there's a way to substitute out the random index generating function for something else, we can gain additional speed. Marginal improvement compared to simply getting a good algorithm. ''' def listShuffle(inputList): outputList = [] listSize = len(inputList) workingList = copy.deepcopy(inputList) lastPos = listSize-1 for iteration in range(listSize): #get a candidate position in the list candidate = rand.randint(0, lastPos) #getRandInt(lastPos) #attach it to the output list outputList.append(workingList[candidate]) #exchange candidate with last entry in list. temp = workingList[lastPos] workingList[lastPos] = workingList[candidate] workingList[candidate] = temp #Increase the dead zone. lastPos -= 1 return outputList ''' Given an integet input N, generates a list of numbers from 1 to N, shuffled and randomized. Algorithm should be an O(N) algorithm. Parameters: N: The input integer from 1 to N. Returns: List of integers from 1 to N, shuffled. ''' def randList(N): numList = [] #Generate list of numbers from 1 to N. O(N) step. for val in range(1, N+1): numList.append(val) #Shuffle the list. return listShuffle(numList) #O(N) step. #Program proper. print("Input an integer number N") list = randList(int(input())) print(list) #Hit enter to leave. print("Hit enter to leave.") input()
true
86b243cc66970a367cf6ffacf2e9727cea200e78
vgiabao/a-byte-of-python
/oop_objvar.py
965
4.125
4
class Robot: ''' Represents a robot, with a name''' # A class variable, counting the number of robots population = 0 def __init__(self, name): '''Initialise the data''' self.name = name print('initialise {0}'.format(self.name)) Robot.population += 1 def die(self): print('{} is detroyed'.format(self.name)) Robot.population -= 1 if Robot.population == 0: print('{} is the last one'.format(self.name)) else: print('There are still {} Robots working'.format(Robot.population)) def say_hi(self): print('Greeting, Master call me {}'.format(self.name)) @classmethod def how_many(cls): print('we have {:d} Robot'.format(Robot.population)) droid1= Robot('R2-D2') droid2= Robot('R3-D3') Robot.how_many() droid1.say_hi() print('Robots are doing somethings') print('Work done! Destroying them') droid1.die() droid2.die() Robot.how_many()
false
47ddd4ebe7f26b2f3a48439ac77110a69df333e6
NotQuiteHeroes/HackerRank
/Python/Math/Triangle_Quest_2.py
929
4.15625
4
''' You are given a positive integer N. Your task is to print a palindromic triangle of size N. For example, a palindromic triangle of size 5 is: 1 121 12321 1234321 123454321 You can't take more than two lines. The first line (a for-statement) is already written for you. You have to complete the code using exactly one print statement. Note: Using anything related to strings will give a score of 0. Using more than one for-statement will give a score of 0. Input Format A single line of input containing the integer N. Output Format Print the palindromic triangle of size N as explained above. https://www.hackerrank.com/challenges/triangle-quest-2 ''' # (((10**i)-1)/9) is equation for repunit numbers: 1, 11, 111, 1111,... # Calculate square of each repunit to get Demlo numbers for i in range(1,int(raw_input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also print(((10**i)-1)/9)**2
true
8f76164190b01039565d41b9c735c5dba85304dc
NotQuiteHeroes/HackerRank
/Python/Sets/Captains_Room.py
1,359
4.125
4
''' Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. One fine day, a finite number of tourists come to stay at the hotel. The tourists consist of: → A Captain. → An unknown group of families consisting of K members per group where K ≠ 1. The Captain was given a separate room, and the rest were given one room per group. Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear K times per group except for the Captain's room. Mr. Anant needs you to help him find the Captain's room number. The total number of tourists or the total number of groups of families is not known to you. You only know the value of K and the room number list. Input Format The first line consists of an integer, K, the size of each group. The second line contains the unordered elements of the room number list. Output Format Output the Captain's room number. https://www.hackerrank.com/challenges/py-the-captains-room ''' input() allRooms = map(int, raw_input().split()) uniqueRooms = set() uniqueRoomsRecurring = set() for i in allRooms: if i in uniqueRooms: uniqueRoomsRecurring.add(i) else: uniqueRooms.add(i) captainsRoom = uniqueRooms.difference(uniqueRoomsRecurring) print(captainsRoom.pop())
true
ddf276c6fd4b62db64141085002cc4b246e61de1
NotQuiteHeroes/HackerRank
/Python/Basic_Data_Types/List_Comprehensions.py
873
4.28125
4
''' Let's learn about list comprehensions! You are given three integers x, y, and z representing the dimensions of a cuboid along with an integer n. You have to print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0 <= i <= x, 0 <= j <= y, 0 <= k <= z. Input Format Four integers x, y, z and n each on four separate lines, respectively. Constraints Print the list in lexicographic increasing order. https://www.hackerrank.com/challenges/list-comprehensions ''' if __name__ == '__main__': x = int(raw_input()) y = int(raw_input()) z = int(raw_input()) n = int(raw_input()) results = [] for i in range(0, x+1): for j in range(0, y+1): for k in range(0, z+1): if(i+j+k != n): results.append([i, j, k]) print(results)
true
37da311250659eff59593188f0c3a40423d93f77
bensontjohn/pands-problem-set
/squareroot.py
600
4.15625
4
# Benson Thomas John, 2019 # Program that takes a positive floating point number as input and outputs an approximation of its square root. # import the math module import math # Take user input and convert to float type user_num = float(input("Please enter a positive number: ")) # Referenced : https://docs.python.org/3/library/math.html # Stores the square root of user_num to square_root using sqrt method square_root = math.sqrt(user_num) # Print the approximation of square_root using round method with 1 decimal place print("The square root of", user_num, "is approx.", round(square_root, 1))
true
9cc7773a5de21e86034de5b1bea974f33d240289
lucius1991/myedu-1904
/day02/lianxi.py
1,426
4.1875
4
#这是一个列表的数据类型,英文是list,也叫数组 alist = ['你好',10,15,20,'world'] #查询 def list_test(): print(alist[0]) print(alist[0:1]) 取倒数第三位 print(alist[6:7]) print(alist[-3]) #第5个开始到后面所有 print(alist[4:]) print(alist[:4]) #删除 def list_del(): alist.pop() print(alist) alist.pop(4) a = alist.pop(4) print(alist) #增加 def list_add(): blist = ['Hello',5,6,7,8] # blist.append('world') # print(blist) clist = ['Blue','Sky'] blist.extend(clist) # blist.append(clist) print(blist) #更改 def list_update(): dlist = [5,'believe','can fly'] dlist[0] = 'I' dlist[2] = 200 print(dlist) #排序 def list_order_by(): elist = [5,7,3,11,1,2,4] elist.sort() # elist.sort(reverse=True) print(elist) #去重 def list_distinct(): flist = [1,1,1,4,5,6,7,7,8] flist = set(flist) print(flist) print(len(flist)) def list_sel(): print(alist[2]) print(alist[1:4]) def list_de(): alist = ['你好', 10, 15, 20, 'world'] alist.pop(3) print(alist) def list_ad(): alist = ['你好', 10, 15, 20, 'world'] alist.append(5) if __name__ == '__main__': # list_test() # list_del() # list_add() # list_update() # list_order_by() # list_distinct() list_sel() list_de()
false
4bee2818070b5910cd395c0c88e7df7657672819
jerryperez25/ArtificialIntelligence-CS4341
/Homework 1/CS4341_HW1_PerezJerry/PerezJerry/ex2.py
773
4.125
4
def isreverse(s1, s2): # Your code here if (len(s1) == 0 and len(s2) == 0): # if both lengths are 0 then they are both equal: only thing thats 0 is empty return True; if len(s1) != len(s2): # if the lengths of 2 words are not equal then there is no way they can be reversals return False; if s1[0] != s2[-1]: # this is supposed to check the last letter of the second word against the first letter of the first return False; # if they are not equal then theres nopossible way they can be reversals else: return isreverse(s1[1:], s2[:-1]); #recursive call for each individual letter, it'll use from the first letter on with the first word # and from the last letter of the second word down to the beginning of it.
true
c4c8adf35fb920d7929e3e4ee11281ae69300d68
androshchyk11/Colocvium-2-semester
/10.py
896
4.375
4
''' Дані про температуру повітря за декаду листопада зберігаються в масиві. Визначити, скільки разів температура опускалася нижче -10 градусів. Виконав студент групи КН-А Андрощук Артем Олександрович ''' temperature = [20, 14, -5, 1, 23, 5, 7, -8, -7, 0] # Ініціалізуємо масив з температурами(можна дані змінити) answer = 0 # ініціалізуємо змінну результату for i in range(10): # проходимо по циклу 10 разів if (temperature[i] < 10): # перевіряємо умову на від'ємність answer += 1 # якщо температура <10, то збільшуємо результат print(answer) # Виводимо відповідь
false
5f2ea39bd61ac3e2cad0d9f157be9bea78037081
androshchyk11/Colocvium-2-semester
/22.py
1,133
4.125
4
''' Знайти добуток елементів масиву, кратних 3 і 9. Розмірність масиву - 10. Заповнення масиву здійснити випадковими числами від 5 до 500. Виконав студент групи КН-А Андрощук Артем Олександрович ''' import random answer = 1 # Ініціалізуємо змінну результат a = [random.randint(5, 500) for i in range(10)] # створюємо масив за допогою генератора списку print(a) # виводимо масив на екран for i in range(10): # проходимо по елементам масиву if (a[i] % 3 == 0 and a[i] % 9 == 0): # перевіряємо чи елемент масиву ділиться націло на 3 та 9 answer *= a[i] # якщо так, то домножаємо до результату if answer == 1: # якщо відповідь рівна 1, то таких чисел не було print("There is no such numbers") else: # інакше виводимо відповідь print(answer)
false
faea3e3b47ef0a20cb862df7f8090c336e8f5fda
jerry1210/HWs
/HW5/3.py
642
4.15625
4
''' Write a decorator called accepts that checks if a function was called with correct argument types. Usage example: # make sure function can only be called with a float and an int @accepts(float, int) def pow(base, exp): pass # raise AssertionError pow('x', 10) ''' def accepts(*types): def decorator(func): def wrapper(*args): assert {isinstance(item[0], item[1]) for item in zip(args, types)} == {True}, \ 'Arguments with wrong types passed' return func(*args) return wrapper return decorator @accepts(float, int) def pow(base, exp): print(base**exp) pow(7.0, 2)
true
0d8252d254e300ae9c60ce0ed0f9db19f6242b43
omshivpuje/Python_Basics_to_Advance
/Python primery data structures.py
1,104
4.25
4
""" Primary Data structures: 1. List 2. Tuple 3. Dictionary 4. Sets """ # List # Lists are mutable and ordered. Also can have different, duplicate members. can be declared in []. ranks = [1, 2, 3, 4, 5] fruits = ["Orange", "Mango", "Pineapple", "Strawberry"] print("ranks: {0}, fruits: {1}".format(ranks, fruits)) print("Type of list", type(ranks)) print("") # Tuple # Tuples are ordered, immutable and declared in (). t1 = ("Pune", 1, True) print("Items in t1", t1) print("Type of tuple", type(t1)) print("") # Dictionary # A dictionary is a collection which is unordered, changeable and indexed. # In Python dictionaries are written with curly brackets {}, and they have keys and values. my_car = { "Brand": "Ford", "Make": 2010, "Colour": "White", "Insurance": True } print("My car", my_car) print("Type of my car object", type(my_car)) print("") # Set # A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. copy = [1, 2, 1, 2, 3, 4, 5, 6, 1, 3, 5, 3] s1 = set(copy) print("Copy list", copy) print("Set is", s1)
true
62cefc2511642742ec4e3b31bb62de545631dd68
StrelnikovaKarina/Coding
/21.02.19.py
1,638
4.4375
4
import time counter = 3 # количество сравнений sleep = 1 # время прирывания программы clock_counter = 0 # количество раз когда time.clock() была точнее time_counter = 0 # количество раз когда time.time() была точнее # в цикле расчитывается время выполнения time.sleep(sleep) с помощью time.clock() и time.time() # и считается какая функция делала это более точно # увеличивая значение sleep и counter можно добиться большей точности while counter != 0: start_clock = time.clock() time.sleep(sleep) elapsed_clock = (time.clock() - start_clock) start_time = time.time() time.sleep(sleep) elapsed_time = (time.time() - start_time) difference_c = abs(sleep - elapsed_clock) difference_t = abs(sleep - elapsed_time) if difference_c < difference_t: clock_counter += 1 elif difference_c == difference_t: clock_counter += 1 time_counter += 1 else: time_counter += 1 counter -= 1 print('time.sleep() : ', sleep, 'second(s)') print('time.clock() : ', elapsed_clock, 'second(s)') print('time.time() : ', elapsed_time, 'second(s)') print('=======') if clock_counter < time_counter: print("time.time() is more correct") elif time_counter < clock_counter: print("time.clock() is more correct") else: print("time.time() and time.clock() are the same")
false
6b0f8a586f105c982592196a0c9c2a13f4515d34
dan8919/python
/sort/String Tokenizer/stringTokenizer.py
318
4.15625
4
string = "1+2*(3-4)" #숫자와 괄호를 분리 해주는 식 def stringTokenzier(string): result = [] for char in string: if char in ["+","-","*","/","(",")"]: result.append(char) result.append(char) return result result = stringTokenzier(string) print("result=>",result)
false
860936a58673a46d8ee2733dc2ced12968e74976
gauravk268/Competitive_Coding
/Python Competitive Program/LIST.py
1,928
4.34375
4
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> ## LISTS IN PYTHON >>> >>> list1 = [10,20,30,"hello",2.4] >>> list1 [10, 20, 30, 'hello', 2.4] >>> list1[1] 20 >>> list1[-4] 20 >>> ## Accessing the list elements >>> >>> list1 = [10,20,30,40,50,60,70,80] >>> >>> list1[0] 10 >>> # suppose i want to acess range of characters >>> >>> # so here is the format: list_var_name[start:end:skip_char] >>> >>> list1[1:7:1] [20, 30, 40, 50, 60, 70] >>> list1[7:-8:2] [] >>> ## Let's KBP >>> >>> >>> >>> >>> l = [0,1,2,3,4,5,6,7,8,9,10] >>> >>> >>> >>> >>> >>> >>> >>> >>> l[::-2] [10, 8, 6, 4, 2, 0] >>> >>> >>> >>> ## Can you tell me >>> ## how to print a list in reverse order in single line >>> >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> l[::-1] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> >>> >>> ## Changing the elements of a list >>> >>> l = [10,20,30] >>> l[2] 30 >>> ## i want to store the new element say 300 at 2nd index no >>> l[2] = 300 >>> l [10, 20, 300] >>> l[2] 300 >>> >>> >>> str_var = "Agnesh" >>> str_var[0] 'A' >>> str_var[0] = "B" Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> str_var[0] = "B" TypeError: 'str' object does not support item assignment >>> >>> >>> # suppose i want to insert rane of characters >>> >>> >>> l = [10,20,300] >>> ## let's change multiple values at a time >>> l[0:2] [10, 20] >>> l[0:2] = [11,22] >>> l [11, 22, 300] >>> l[0:2] = [1,2,3,4,5] >>> l [1, 2, 3, 4, 5, 300] >>> >>> >>> >>> >>> # List Built-In Functions >>> >>> ## append() :- it adds one element at the end of list >>> >>> l = [10,20,30] >>> l.append(40) >>> l [10, 20, 30, 40] >>> >>> >>> ## insert() :- adds element to the list based on index no >>> >>> l = [10,20,30] >>> l.insert(2,1000) >>> l [10, 20, 1000, 30] >>> >>> >>>
true
b9d676a541b0c0a52e62c39eb8b665e81f8b8c2e
gauravk268/Competitive_Coding
/Python Competitive Program/gretest element in right.py
1,087
4.5625
5
# Python Program to replace every element with the # greatest element on right side # Function to replace every element with the next greatest # element def nextGreatest(arr): size = len(arr) # Initialize the next greatest element max_from_right = arr[size-1] # The next greatest element for the rightmost element # is always -1 arr[size-1] = -1 # Replace all other elements with the next greatest for i in range(size-2,-1,-1): # Store the current element (needed later for updating # the next greatest element) temp = arr[i] # Replace current element with the next greatest arr[i]=max_from_right # Update the greatest element, if needed if max_from_right< temp: max_from_right=temp # Utility function to print an array def printArray(arr): for i in range(0,len(arr)): print (arr[i],) # Driver function to test above function arr = [16, 17, 4, 3, 5, 2] nextGreatest(arr) print ("Modified array is" ) printArray(arr)
true
570c0313be76ea30e28fbf796388b61987ffe7f0
gauravk268/Competitive_Coding
/Python Competitive Program/ifelse.py
236
4.3125
4
#-------- Senior Citizen--------- age=float(input("Enter your age : ")) if age>0 and age<=1: print("Infant") elif age>1 and age<=18: print("Child") elif age>18 and age<=60: print("Adult") else: print("Senior Citizen")
false
a2f503fe913e6103377a6aabca170c035b60896d
group6BCS1/BCS-2021
/src/chapter5/excercise1.py
485
4.21875
4
try: total = 0 count = 0 # the user will be able to input numbers repeatedly while True: x = input('enter a number') # when done is entered, the loop will be broken if x == 'done': break x = int(x) # we are finding the total, count and average of the numbers entered total = total + x count = count + 1 average = total / count print('done!') print(count, total, average) except: print('Invalid Input')
true
573530cf686edbd3264ad6a2440c2809dd3c04f1
yufanglin/Basic-Python
/sortingListsTuplesObjects.py
1,603
4.21875
4
''' Sorting Lists, Tuples, and Objects Code from following this tutorial: https://www.youtube.com/watch?v=D3JvDWO-BY4&index=21&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU ''' # sort li = [9, 1, 8, 2, 7, 3, 6, 4, 5] s_li = sorted(li) desc_li = sorted(li, reverse=True) print('Sorted Variable:\t', s_li) print('Descending Sorted:\t', desc_li) print('Original Variable:\t', li) # sort original li.sort() print('\nSorted Orignal:\t', li) li.sort(reverse=True) print('Descending Sorted:\t', li) tup = (9, 1, 8, 2, 7, 3, 6, 4, 5) s_tup = sorted(tup) print('\nTuple\t', s_tup) print('Original Variable:\t', tup) di = {'name': 'Corey', 'job': 'programming', 'age': None, 'os': 'Mac'} s_di = sorted(di) print('\nDict\t', s_di) print('Original Variable:\t', di) li = [-6, -5, -4, 1, 2, 3] s_li = sorted(li, key=abs) print("\nSorted:\t", s_li) print("Original:\t", li) class Employee(): def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary def __repr__(self): return '({}, {}, ${})'.format(self.name, self.age, self.salary) def e_sort(emp): return emp.name from operator import attrgetter e1 = Employee('Carl', 37, 70000) e2 = Employee('Sarah', 29, 80000) e3 = Employee('John', 43, 90000) employees = [e1, e2, e3] print('\nOriginal Employees List:\t', employees) s_employees = sorted(employees, key=Employee.e_sort, reverse=True) #Lambda version: # s_employees = sorted(employees, key=lambda e: e.name, reverse=True) # operator.attrgetter Version: # s_employees = sorted(employees, key=attrgetter('age')) print('\nReverse Sorted:\t', s_employees)
false
6495d47e7d6695d6c4851252bfa5c0080aef1296
yufanglin/Basic-Python
/List.py
2,474
4.46875
4
''' List practice in Python 3 ''' ############################## LISTS ############################## courses = ['History', 'Math', 'Physics', 'CompSci'] # Print the list print(courses) # length of the list print(len(courses)) # Get specific values in list print(courses[0]) # Get last value in list print(courses[-1]) # Get the second to the last item in list print(courses[-2]) # Get a range SLICING print(courses[0:2]) # range includes first but not including second value # Range: can get rid of first value if it is the first value in list, vice versa for last value print(courses[:2]) print(courses[1:]) print(courses[:]) # Get the index of specific value print("Index of CompSci: ", courses.index('CompSci')) # Check if value is in the list, return true/false print('Math' in courses) for index, course in enumerate(courses): print(index, course) ###### Methods for Lists # Add an item at the end of the lsit courses.append('Art') print(courses) # Add an item at a specific position (can also insert an entire list within a list) courses.insert(0,'CIS') print(courses) # add multiple values to the list courses2 = ['Chemisty', 'Education'] courses.extend(courses2) print(courses) # Remove the last value of the list and return it popped = courses.pop() print("Popped value: ", popped) print("Popped List: ", courses) ###### Sort list # Reverse list courses.reverse() print("Reverse: ", courses) # Sort in alphabetical order courses.sort() print("Alphabetical: ", courses) nums = [1, 5, 2, 4, 3] nums.sort() print("Number Increase: ", nums) # Reverse Alphabetical courses.sort(reverse = True) nums.sort(reverse = True) print("Reverse Alphabetical: ", courses) print("Number Decrease: ", nums) # get the sorted version of the list without altering with the original sorted_courses = sorted(courses) print("Sorted Courses List Version: ", sorted_courses) print("Original Courses List: ", courses) ##### Min Max Sum # Get min of number list print("Number Min: ", min(nums)) # Get max of number list print("Number Max: ", max(nums)) # Get the sum of number list print("Sum of Number List:", sum(nums)) ###### Joining strings course_comma_str = ', '.join(courses) courses_hyph_str = " - ".join(courses) print("Joined Comma Courses: ", course_comma_str) print("Joined Hyph Courses: ", courses_hyph_str) # can make the above string back to a list new_list = course_comma_str.split(', ') print("Resplit String to List: ", new_list)
true
181764d142ccd99845d433fbbd32e976dace9c40
clarito2021/python-course
/11.-loops.py
1,785
4.15625
4
foods = ['apples', 'bread', 'cheese', 'milk', 'graves', 'vine', 'cereal', 'banana'] print('******************************************') print("Aquí vemos la salida si imprimimos los indices especificados uno por uno") print(foods[0]) print(foods[1]) print(foods[2]) print(foods[3]) print('******************************************') print("Acá, vemos el mismo resultado en pantall, pero usando el comando for") for food in foods: print(food) print('******************************************') print("Acá, le damos una condición para que mientras se esté ejecutando el for, si encuentra la condición que solicitamos, entonces, imprime lo que solicitamos") for food in foods: if food == "cheese": print("You have to buy cheeese...") print(food) print('******************************************') print("Acá, si encuentra la palabra cheese, ejecuta un break y no se ve nada en pantalla") for food in foods: if food == "cheese": print("You have to buy cheeese...") break print('******************************************') print("Acá, también ejecutamos un break, sin embargo, le damos el comando imprir, por lo tanto, tentemos un input,") for food in foods: if food == "cheese": break print("encontramos queso en la lista, asi que imprimimos QUESO") print('******************************************') for food in foods: if food == "cheese": continue print(food) print('******************************************') for number in range(1, 10): print(number) print('******************************************') for letter in "Hello": print(letter) print('******************************************') count = 4 while count <= 10: print(count) count = count + 1
false
12f364334a3a95711444bcd45345b834a48ff47f
tb1over/datastruct_and_algorithms
/interview/CyC2018_Interview-Notebook/剑指offer/16.py
499
4.25
4
# -*- coding: utf-8 -*- """ 给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent。求 base 的 exponent 次方。 """ def _power(x, n): result = 1 while n > 0: if n & 1 == 1: # 判断是否为奇数,如果是奇数则计算result result *= x n >>= 1 x *= x return result def power(x, n): pn = n if n > 0 else -n result = _power(x, pn) return 1.0 / result if n < 0 else result print(power(2, -3))
false
d06c4e14ca6439e732ab46594b449caacf965c8b
tb1over/datastruct_and_algorithms
/number/mod_exp.py
468
4.15625
4
# -*- coding: utf-8 -*- # Given three numbers x, y and p, compute (x^y) % p. # recursive power def power_rf(x, y): if y == 1: return x return x * power(x, y-1) # for loop def power(x, y): res = 1 while y > 0: # 如果y是奇数,那么res = res * x if y & 1: res *= x y >>= 1 # 右移一位(除2) x = x*x return res def compute(x, y, p): return power(x, y) % p print(compute(2, 5, 13))
false
c603b386c71d984b3a4771028d7a960c1957dbe7
colinbazzano/recursive-sorting-examples
/src/lecture.py
1,492
4.1875
4
# ********************************************* # NEVER DO THIS, BUT... it is recursion # def my_recursion(n): # print(n) # my_recursion(n+1) # my_recursion(1) # ********************************************* # we have now added a base case to prevent infinite recursion def my_recursion(n): print(n) if n == 5: return my_recursion(n + 1) my_recursion(1) """call stack order 1. on line 21, we call my_recursion with the value of 1 2. go into the my_recursion function, and on line 15, print n, return and remove it from the stack 3. does n == 5? no, so we go to the line 18 and call my_recursion with the value of 2 (1 + 1) 4. then we go back into the function with the value of n being 2, print n, return and remove it from the stack 5. I think you see where this is going, and going, and going, and go.... from the wise Don: "So for visual purposes, once we have called the base case, the stack crumbles to the ground in the reverse order of calls" """ def my_recursion(n): print(n) if n == 3: return my_recursion(n + 1) my_recursion(n + 1) my_recursion(1) """call stack order *** PLUG THIS FUNCTION ABOVE INTO http://pythontutor.com/visualize.html#mode=edit 1. start with my_recursion(1) add and remove print() 2. on line 37 we call my_recursion() with a value of 2 and that prints() then removes the print 3. it equals 3 and removes it from the call stack 4. then we call on line 38 my_recursion() with the value of 3 """
true
baa425cca4e36d27b14c71569660ea92e6e47815
kishorchouhan/Udacity-Intro_to_CS
/Better splitting.py
1,370
4.34375
4
def split_string(source,splitlist): word_list = [''] at_split = False for char in source: if char in splitlist: at_split = True else: if at_split: # We've now reached the start of the word, time to make a new element in the list word_list.append(char) # This creates a new element in the array with the value of 'char' # Reset at_split so no more elements are created until we reach a new word at_split = False else: # Char is not in splitlist, and we're not at the start of a word, so simply concatenate # char with the last entry in word_list word_list[-1] = word_list[-1] + char # Once we've filled word list, we'll want to return the list containing all the words return word_list out = split_string("This is a test-of the,string separation-code!"," ,!-") print (out) #>>> ['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code'] out = split_string("After the flood ... all the colors came out.", " .") print (out) #>>> ['After', 'the', 'flood', 'all', 'the', 'colors', 'came', 'out'] out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",") print (out) #>>>['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']
true
ecd06a64bd206784e741f086a8bc6f0453716786
vimalkkumar/Basics-of-Python
/Factorial.py
280
4.1875
4
def main(): def factorial_number(num): result = 1 for i in range(1, num+1): result = i*result print("factorial of {} is {}".format(num, result)) factorial_number(int(input("Enter a number : "))) if __name__ == "__main__": main()
true
13bb71cc08704b55facd4fbc8ba363bfe16c04ef
lf-coder/python
/01-basicLearning/13-字典.py
353
4.40625
4
""" 1.字典是dict的实例 1.python的字典和js中的对象一模一样 2.可以使用in 和 not in判断字典中是否有该key """ # 创建一个字典 dict1 = {'name': 'lf', 'age': 23} print(dict1) dict2 = dict((('name', 'lf'), ('age', 23))) print(dict2) dict3 = dict(name='lf', age=23) print(dict3) dict3['hobby'] = 'play game' print(dict3)
false
6a7aeb4b770d80379edd2380372df614b5db4d4c
saikiran335/python-projects
/contactlist.py
2,039
4.28125
4
contacts={} print("--------Contacts---------") while True: print("\nSelect the operation") print("1.Insert the contact") print("2.Search for the contact") print("3.Delete the contact") print("4.Display all the contacts") print("5.delete all the contacts") print("6.edit the contact") print("7.Number of contacts") n=int(input("\nenter your choice")) if(n==1): contacts[input("\nenter the name")]=input("\nenter the numer") print(contacts) elif(n==2): name=input("\nenter name to search") for x,y in contacts.items(): if(name==x): print("\nname=",x + "\ncontact=",y) elif(n==3): name = input("enter name to delete") if name in contacts.keys(): contacts.pop(name) else: print("Not Found\n") print(contacts) elif(n==4): print(contacts) elif(n==5): if(len(contacts)==0): print("the list is already empty") else: del contacts print(contacts) elif(n==6): print("\n 1.name changing") print("\n 2.number change") m=int(input("enter ur choice")) if(m==1): name=input("\nenter name to edit") for x,y in contacts.items(): if(x==name): newname=input("\nenter new name to edit") newdic={newname:y} contacts.update(newdic) else: print("\n Contact not found") if(m==2): name=input("\nenter name to edit") for x,y in contacts.items(): if(x==name): newnumber=input("\nenter new number to edit") newdic={x:newnumber} contacts.update(newdic) else: print("\n Contact not found") print(contacts) elif(n==7): print(len(contacts)) else: break
true
390605ee17a9754ae7ee2f702269a61bb20908cd
Prudhvik-MSIT/cspp1-practice
/m9/Odd Tuples Exercise/odd_tuples.py
638
4.40625
4
''' Author: Prudhvik Chirunomula Date: 08-08-2018 ''' #Exercise : Odd Tuples #Write a python function odd_tuples(a_tup) that takes a some numbers # in the tuple as input and returns a tuple in which contains odd # index values in the input tuple def odd_tuples(a_tup): ''' a_tup: a tuple returns: tuple, every other element of a_tup. ''' # Your Code Here return a_tup[::2] def main(): '''main function''' data = input() data = data.split() a_tup = () for j in range(len(data)): a_tup += ((data[j]),) print(odd_tuples(a_tup)) if __name__ == "__main__": main()
true
fd998d3bc0b125e9d775521e37e4ad3d2fd0ad37
zadrozny/algorithms
/find_list_duplicates.py
1,255
4.125
4
''' Write a function that finds and returns the duplicates in a list. Write a test for this. ''' def find_duplicates_1(lst): duplicates = [] for element in set(lst): if lst.count(element) > 1: duplicates.append(element) return duplicates #Rewritten as a list comprehension def find_duplicates_2(lst): return [element for element in set(lst) if lst.count(element) > 1] #Using collections, a la http://stackoverflow.com/a/9835819/1366410 import collections def find_duplicates_3(lst): return [x for x, y in collections.Counter(lst).items() if y > 1] if __name__ == '__main__': tests = { (1, 2, 3, 4, 5, 5, 6, 6): [5, 6], (1, 2, 3, 4, 5, 6, 5): [5] } for test in tests: assert find_duplicates_1(test) == tests[test] assert find_duplicates_2(test) == tests[test] assert find_duplicates_3(test) == tests[test] import timeit print(timeit.timeit("for x in range(10, 11): find_duplicates_1(range(x))", setup="from __main__ import find_duplicates_1")) print(timeit.timeit("for x in range(10, 11): find_duplicates_2(range(x))", setup="from __main__ import find_duplicates_2")) print(timeit.timeit("for x in range(10, 11): find_duplicates_3(range(x))", setup="from __main__ import find_duplicates_3"))
true
547984f82e245a84d8d1122553600f8fd5242f79
zadrozny/algorithms
/matched_braces.py
1,299
4.125
4
''' Challenge 2: Braces Given an array of strings containing three types of braces: round (), square [] and curly {} Your task is to write a function that checks whether the braces in each string are correctly matched prints 1 to standard output (stdout) if the braces in each string are matched and 0 if they're not (one result per line) Note that your function will receive the following arguments: expressions which is an array of strings containing braces Data constraints: the length of the array will not exceed 100 the length of any string will not exceed 5000 Efficiency constraints your function is expected to print the result in less than 2 seconds Example Input Output expressions: [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ] 0 1 1 1 0 ''' def check_braces(expression): open_braces = ['(', '[', '{'] closed_braces = [')', ']', '}'] q = [] for char in expression: if char in open_braces: # Push the stack q.append(char) else: # It's a closed brace. if len(q) == 0: # First bracket closed/extra closed brackets return 0 if closed_braces.index(char) != open_braces.index(q.pop()): return 0 else: return 1 expressions = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ] for expression in expressions: print check_braces(expression)
true
74f9d1a7da0af018658e153665870d69b6259d46
HtetoOs/Practicals
/prac_03/oddName.py
223
4.125
4
name = input("Enter your name!") while len(name)<=0: print("Name is blank! Please enter your name!") name = input("Enter your name!") print(name[: : 2]) for i in range(0, len(name), 2): print(name[i], end="")
true
d4001e7b106ceb83691eba57765097493fa4571b
arthurbragav/Curso_udemy
/Aula 23 - Estruturas logicas and or not is.py
553
4.1875
4
""" Estruturas lógicas and, or, not, is Operadores unários: - not Operadores binários - and, or, is Regras de funcionamento Para o 'and', ambos os valores precisam ser True Para o 'or', um ou outro valor precisa ser True Para o 'not', o valor do booleano é invertido Para o 'is', o valor é comparado com um segundo """ ativo = False logado = False if ativo or logado: print('Bem vindo, usuário!') else: print('Ative sua conta') # O sistema pergunta: o ativo é true? Se sim, imprime True, se não, False print(ativo is True)
false
bf721957e07df6a9ab6fad30ba99e233512a0a15
gbanfi3/misc
/Euler/a001.py
331
4.15625
4
''' 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 1000. ''' lim = 1000 sum = 0 for i in range(1,lim): if not i % 3: sum +=i continue if not i % 5: sum +=i print(sum)
true
fd2d5ef7a880dc1749d489542ae72a5510f39199
Al153/Programming
/Python/Misc/maths.py
959
4.34375
4
pi=3.1415926535 from math import * n=2 operation = "go" square = 1 circle = 2 elipse = 3 rectangle = 4 while operation != "stop": operation = (input("which shape do you want to find the area of? ")) if operation == 1: print("area of a square") sidelength=float(input("side length = ")) a = sidelength**2 print("area = "+str(a)) elif operation == 2: print("area of a circle") r = float(input("radius =")) a = pi*r**2 print("area = "+str(a)) elif operation == 3: print("area of an elipse") a=float(input("major radius A = ")) b=float(input("maor radius B = ")) area = pi*a*b print("area = "+str(area)) elif operation == 4: print "area of a rectangle" a = float(input("side length a = ")) b = float(input("side lengt b = ")) area = a * b print ("area = " +str(area))
true
0b545e74b9ec8ba6284590a38cf0f7e24f9bc7bf
Al153/Programming
/Guest/Hour of code/Heapsort.py
2,174
4.25
4
def heapsort(lst): ''' Heapsort. Note: this function sorts in-place (it mutates the list). ''' compare_count = 0 print "Creating heap" for start in range((len(lst)-2)/2, -1, -1): compare_count = siftdown(lst, start, len(lst)-1,compare_count) print lst print "decomposing heap" for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] compare_count = siftdown(lst, 0, end - 1,compare_count) print lst print "result = ",lst print "\nSwapcount = ", compare_count def siftdown(lst, start, end,compare_count): root = start while True: child = root * 2 + 1 if child > end: break compare_count += 2 #two compares if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break return compare_count def bubbleSort(alist): compare_count = 0 for passnum in range(len(alist)-1,0,-1): for i in range(passnum): print alist compare_count += 1 if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp print "result = ",alist print "\nSwapcount = ", compare_count def insertionSort(alist): compare_count = 0 for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: print alist compare_count += 1 alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i<len(lefthalf) and j<len(righthalf): if lefthalf[i]<righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i<len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j<len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist)
true
8a2a07ff7d19edea0d93b5dfdb65d032ad851630
Adheethaov/InfyTQ-Python
/grade.py
647
4.21875
4
#A teacher in a school wants to find and display the grade of a student based on his/her percentage score. #The criterion for grades is as given below: #Score (both inclusive) Grade #Between 80 and 100 A #Between 73 and 79 B #Between 65 and 72 C #Between 0 and 64 D #Any other value Z score=50 if(score>=80 and score<=90): print("A") elif(score>=70 and score<=79): print("B") elif(score>=65 and score<=72): print("C") elif(score>=0 and score<=64): print("D") else: print("Z")
true
b026e0fa91ec048ff4a61a95902319a0e3439c4b
anishsaah/Learning-Python
/sample calculator.py
1,221
4.375
4
while True: print("Options:") print("Enter 'add' to add two numbers.") print("Enter 'subtract' to subtract two numbers.") print("Enter 'multiply' to multiply two numbers.") print("Enter 'divide' to divide two numbers.") print("Enter 'quit' to end the program.") a = input(": ") if a == "quit": break elif a == "add": x = float(input("Enter a number; ")) y = float(input("Enter another number; ")) z = x + y print("The sum of two numbers is; " + str(z)) elif a == "subtract": x = float(input("Enter a number; ")) y = float(input("Enter another number; ")) z = str(x - y) print("The subtraction of two numbers is; " + z) elif a == "multiply": x = float(input("Enter a number; ")) y = float(input("Enter another number; ")) z = x * y print("The multiplication of two numbers is; " + str(z)) elif a == "divide": x = float(input("Enter a number; ")) y = float(input("Enter another number; ")) z = x / y print("The division of two numbers is; " + str(z)) else: print("Unknown input.")
true
fdaab6120cacaab50010d1d2c907f6ca625359a3
SibiSagar/codekata
/problem4.py
246
4.25
4
#Check whether a character is an alphabet or not alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" char=input() if char in alphabet: print("Alphabet") elif char in alphabet.lower(): print("Alphabet") else: print("No")
true
ae86b88683c3f7a4a5bdb0575e7355ce4d6623f9
MaisenRv/EjerciciosCiclo1
/eje23_metodos_de_cadenas_caracteres.py
1,073
4.15625
4
from os import system system("cls") #miestra la letra que esta en corchetes x = "jose maria cordoba" print(x[2]) #mayuscula la primera letra print(x.capitalize()) #El tecto lo pone en mayuscula print(x.upper()) #Todo en minuscula print(x.lower()) #centra el texto entre 25 caracteres " " print(x.center(25,"-")) #alinea a la de derecha print(x.rjust(35, "*")) #alinea a la izquierda print(x.ljust(35, "*")) #muestra las letras que estan entre parentecis las pociciones 5 al 9 print(x[5:10]) #cuenta el numero de caracteres que hay en la cadena print(x.count("a")) #busca la letra en la cadena y devuelve la pocicion print(x.find("m")) #tiene otro parametro x.find("0", 2) #cuenta el numero de los caracteres print(len(x)) y = " alejandra raquel " #quita los espacios del principio y del final print(y.strip()) #derecha print(y.rstrip()) #izquierda print(y.lstrip()) #remplaza letras, el tercer parametro es el munero de letras que se quiera #remplazar print(x.replace("m","M",1)) print(x.replace("e","E")) print(x.rjust(40,"0"))
false
5f2b3fdc2e0cedcfba66a2cdd36edf2475c2ca78
ambergooch/dictionaries
/dictionaryOfWords.py
828
4.625
5
# Create a dictionary with key value pairs to represent words (key) and its definition (value) word_definitions = dict() word_definitions["Awesome"] = "The feeling of students when they are learning Python" word_definitions["Cool"] = "A descriptor word for a cucumber" word_definitions["Chill"] = "The act of sinking into the couch and watching Netflix" # Use square bracket lookup to get the definition of two words and output them to the console with `print()` print(word_definitions["Cool"]) print(word_definitions["Chill"]) for (key, value) in word_definitions.items(): print(f"The definition of {key} is {value}") """ Loop over the dictionary to get the following output: The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] The definition of [WORD] is [DEFINITION] """
true
e534b2fa2a5545f10c26be9245a37f403070c682
chamoysvoice/p_euler
/problem4.py
781
4.15625
4
# coding=utf-8 from __future__ import division from math import sqrt """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(sv): return sv == sv[::-1] def is_valid(n): return len(str(n)) == 3 def get_factors(n): for x in xrange(int(sqrt(n)), 0, -1): if n / x == int(n / x): return x, int(n / x) def problem4(): for x in xrange(999, 100, -1): temp_s = int(str(x)+str(x)[::-1]) if is_palindrome(str(temp_s)): t, y = get_factors(temp_s) if is_valid(t) and is_valid(y): return temp_s print problem4()
true
3177febbe7fdfa6e909558ecbc45a1b37d09c5a9
hidalgowo/CC1002
/Clases/Clase_05_modulos/ejsRecursion.py
2,790
4.15625
4
# potencia: num int -> num # calcula el valor de una potencia de base elevado a exponente # para exponentes enteros positivos # ejemplo: potencia (4,5) debe dar 1024 def potencia(base, exponente): if exponente == 0: return 1 else: return base*(potencia(base, exponente-1)) # test assert potencia(4,5) == 1024 assert potencia(2,4) == 16 assert potencia(-1,5) == -1 assert potencia(3,0) == 1 #digitos: int->int #cuenta digitos de un número entero #ej: dígitos(245) debe ser 3 #ej: digitos(4) debe ser 1 def digitos(n): if abs(n) < 10 : return 1 else: return 1 + digitos(n//10) # tests assert digitos(245)==3 assert digitos(-4)==1 digitos(-2456) # factorial: int -> int # calcula el valor factorial de n # ejemplo: factorial(4) debe dar 24 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) # test assert factorial(4) == 24 assert factorial(2) == 2 assert factorial(8) == 40320 # factorial: int -> int # calcula el valor factorial de n # ejemplo: factorial(4) debe dar 24 def factorial(n): assert (type(n)==int) and (n>=0), "Factorial no esta definido para n no entero, ni n negativo." if n == 0: return 1 else: return n*(factorial(n-1)) # test assert factorial(4) == 24 assert factorial(2) == 2 assert factorial(8) == 40320 #calculaListaFactoriales: None -> None #calcular factorial de lista de numeros ingresada por el teclado # (la lista termina con el valor "fin") #ej: factoriales() def calculaListaFactoriales(): respuesta=input('n ?') if respuesta=="fin": return # caso no es igual a fin n = int(respuesta) factorial_n = factorial(n) print(str(n)+'!='+str(factorial_n)) calculaListaFactoriales() # hanoi: int -> int # calcula el numero de movimientos necesarios para mover # una torre de n discos desde una vara a otra # usando 3 varas y siguiendo las restricciones del puzzle de hanoi # ejemplo: hanoi(0) debe dar 0, hanoi(1) debe dar 1, hanoi(2) debe dar 3 def hanoi(n): if n<2: return n else: return 1+2*hanoi(n-1) # test assert hanoi(0)==0 assert hanoi(1)==1 assert hanoi(2)==3 assert hanoi(4)==15 assert hanoi(5)==31 # Programa principal # Usa funciones definidas arriba print("potencia(-2,7) es ",str(potencia(-2,7))) print("factorial de 0 es ",str(factorial(0))) print("factorial de 10 es ",str(factorial(10))) # Descomentar lo siguiente si quieren probar el assert dentro de la funcion factorial #print("El factorial de -1 es... (lo siguiente debe dar error!)... ") #print(str(factorial(1))) print("El factorial de 4 es ",str(factorial(4))) print ("Calcular lista de factoriales") calculaListaFactoriales() print("hanoi(4) es ",str(hanoi(4)))
false