blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
86e74e6b83be3976ba48f90728a50334811df18a
cycho04/python-automation
/game-inventory.py
1,879
4.3125
4
# You are creating a fantasy video game. # The data structure to model the player’s inventory will be a dictionary where the keys are string values # describing the item in the inventory and the value is an integer value detailing how many of that item the player has. # For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} # means the player has 1 rope, 6 torches, 42 gold coins, and so on. # Write a function named displayInventory() that would take any possible “inventory” and display it like the following: # Inventory: # 12 arrow # 42 gold coin # 1 rope # 6 torch # 1 dagger # Total number of items: 62 #then.. # Imagine that a vanquished dragon’s loot is represented as a list of strings like this: # dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # Write a function named addToInventory(inventory, addedItems), where the inventory parameter # is a dictionary representing the player’s inventory (like in the previous project) # and the addedItems parameter is a list like dragonLoot. The addToInventory() function # should return a dictionary that represents the updated inventory. # Note that the addedItems list can contain multiples of the same item. stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(inventory): print('Inventory: ') item_count = 0 for k, v in inventory.items(): item_count += int(v) print(v, k) print('Total number of items:', item_count) def addToInventory(inventory, addedItems): for i in addedItems: if i in inventory: inventory[i] += 1 else: inventory[i] = 1 return inventory modified = addToInventory(stuff, dragonLoot) displayInventory(modified)
true
fc68579b36277493e624b0401ac7be7fdf1b4f5c
AdityaKuranjekarMYCAPTAIN/Python-Project-2-PART-1-
/Fibonacci.py
253
4.125
4
n = int(input("How many numbers of fibonacci series do you want to see?: ")) x = 0 y = 1 z = 0 i = 1 while (n >= i): print (z) x = y y = z z = x+y i += 1 #>>>>>>>>>>>>>>>>>>.................HAPPY CODING....................<<<<<<<<<<<<<<<<<<<<<<<
false
70a3ee1c969065898bdb77d2aa0b8004a0364fbf
rajmohanram/PyLearn
/003_Conditional_Loop/06_for_loop_dict.py
582
4.5
4
# let's look at an examples of for loop # - using a dictionary # define an interfaces dictionary - items: interface names interface = {'name': 'GigabitEthernet0/2', 'mode': 'trunk', 'vlan': [10, 20, 30], 'portfast_enabled': False} # let's check the items() method for dictionary interface_items = interface.items() print("Dictionary items:", interface_items) print("\t---> items() method produce Tuples in a list") # loop through items in the list print("\n---> Iterating through dictionary...") for key, value in interface.items(): print("key:", key, " - value:", value)
true
0cd762b867fbd84b8319eeb89b10c0fcb73675ef
rajmohanram/PyLearn
/004-Functions/01_function_intro.py
758
4.46875
4
""" Functions: - Allows reuse of code - To create modular program - DRY - Don't Repeat Yourselves """ # def: keyword to define a function # hello_func(): name of the function - Prints a string when called # () - used to get the parameters: No parameters / arguments used in this function def hello_func(): print("Hello World!, Welcome to Python function") # hello_func_return(): name of the function - Returns a string when called def hello_func_return(): welcome = "Hello World! Welcome to PYTHON FUNCTION" return welcome # main program if __name__ == "__main__": # call the function by its name hello_func() # get a value returned from a function & print it greeting = hello_func_return() print(greeting)
true
d8d9a875d2a71f214c7041c2df0b0fcf298e4c8b
jda5/scratch-neural-network
/activation.py
2,158
4.21875
4
import numpy as np class ReLU: def __init__(self): self.next = None self.prev = None def forward(self, inputs): """ Implements Rectified Linear Unit (ReLU) function - all input values less than zero are replaced with zero. Finally it sets two new attributes: (1) the inputs being passed to the activation function - so that this can be referenced later during backpropagation; (2) the output of the layer - so that this can be passed on to the following layer. :param inputs: the values being passed to the activation function from the associated layer """ output = np.maximum(0, inputs) setattr(self, 'output', output) setattr(self, 'inputs', inputs) def backward(self, dvalues): """ The derivative of the ReLU function with respect to its inputs are zero if the input is less than zero. Since we are modifying the dvalues variable inplace, it's best to make a copy of them. :param dvalues: The derivatives received from the proceeding layer :return: """ dinputs = dvalues.copy() dinputs[self.inputs < 0] = 0 setattr(self, 'dinputs', dinputs) class Softmax: def forward(self, inputs): """ First the function exponentiates each value. However, it subtracts the largest of the inputs (row-wise) before doing the exponentiation to avoid the NaN trap. This creates un-normalized probabilities. Then we normalize these probabilities by dividing by the sum of the rows. Finally the output and input values are saves so that they can be referenced during backpropagation. :param inputs: the values being passed to the activation function from the associated layer """ exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) output = exp_values / np.sum(exp_values, axis=1, keepdims=True) setattr(self, 'output', output) setattr(self, 'inputs', inputs) # No need for a backwards function as this will be handled by the combined Softmax and Categorical Cross Entropy class
true
ad0394942b9f519406945e58c72e7da25dda27eb
BigNianNGS/AI
/python_base/class2.py
1,562
4.3125
4
class Dog(): """构造方法""" def __init__(self,name,age,weight=5): self.name = name self.age = age self.weight = weight # ~ return self 不需要,程序已经内设 def set_weight(self,weight): self.weight = weight def eat_bone(self): print(self.name + 'is eating bone') def bark(self): print(self.name+' is barking') def get_string(self): print('my name is '+ self.name+',my age is '+ str(self.age)) #初始化 对象 并调用 my_dog = Dog('lichan\'dog',10,90) #1 修改属性 my_dog.name = 'other' #2 修改属性 set方法 my_dog.set_weight(100) #打印属性 print(my_dog.name) #设置默认属性 print(my_dog.weight) my_dog.eat_bone() my_dog.bark() my_dog.get_string() print('------') #对象初始化子对象 class Family(): def __init__(self,dad,mama): self.dad = dad self.mama = mama self.brother = [] def get_dad(self): return self.dad def get_mama(self): return self.mama # ~ 继承 class PetDog(Dog): def __init__(self,name,age): #if python2 # super(PetDog,self).__init__(name,age) super().__init__(name,age) self.food = [] self.family = Family('lichan','lidewife') def print_food(self): if self.food: print(self.food) else: print('no food') #重写 def eat_bone(self): print(self.name + 'can not eating bone') my_pet_dog = PetDog('my_pet_dog',999) print(my_pet_dog.name) my_pet_dog.bark() my_pet_dog.food = ['a','b','c'] my_pet_dog.print_food() my_pet_dog.eat_bone() dad = my_pet_dog.family.get_dad() print(dad)
false
594edacffdac059e2f6b34a514d402659b9ed4a1
leon-lei/learning-materials
/binary-search/recursive_binary_search.py
929
4.1875
4
# Returns index of x in arr if present, else -1 def binarySearch(arr, left, right, x): # Check base case if right >= left: mid = int(left + (right - left)/2) # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be present in left subarray elif arr[mid] > x: return binarySearch(arr, left, mid-1, x) # Else the element can only be present in right subarray else: return binarySearch(arr, mid+1, right, x) else: # Element is not present in the array return -1 ### Test arr = [2, 3, 4, 10, 40, 55, 90, 122, 199] x = 55 # Function call result = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print('Element is present at index {}'.format(result)) else: print('Element is not present in array') print('Done')
true
70b705fc1378b524560ac03c727748133b8919bd
Lipones/ScriptsPython
/estruturas de repetição2.py
293
4.15625
4
# -*- coding: utf-8 -*- lista1 = [1,2,3,4,5] lista2 = ["olá", "mundo", "!"] lista3 = [0, "olá", "biscoito", "bolacha", 9.99, True]#comando for é utilizado para percorrer listas e exibir resultados for i in lista1: print(i) for i in lista2: print(i) for i in lista3: print(i)
false
1421aac5bb5d2864179392ec3580146803b0dc22
signalwolf/Algorithm
/Chapter2 Linked_list/Insert a node in sorted linked list.py
1,244
4.28125
4
# https://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/ # insert by position class LinkedListNode(object): def __init__(self, val): self.val = val self.next = None def create_linked_list(arr): dummy_node = LinkedListNode(0) prev = dummy_node for val in arr: curr = LinkedListNode(val) prev.next = curr prev = curr return dummy_node.next def printLinked_list (head): res = [] while head != None: res.append (head.val) head = head.next print res def insert(head, val): dummy_node = LinkedListNode(0) dummy_node.next = head prev, curr= dummy_node, head # print curr.val, prev.val while curr and curr.val < val: curr= curr.next prev = prev.next prev.next = LinkedListNode(val) if curr: prev.next.next = curr return dummy_node.next head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 100)) head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 0)) head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 5)) # Output: # [1, 3, 4, 7, 8, 10, 100] # [0, 1, 3, 4, 7, 8, 10] # [1, 3, 4, 5, 7, 8, 10]
true
cc2ca652d4ef4f7b5b6f4198f1e92a6f3a85ad63
YSreylin/HTML
/1101901079/list/Elist10.py
289
4.21875
4
#write a Python program to find the list of words that are longer than n from a given list of words a = [] b = int(input("Enter range for list:")) for i in range(b): c = input("Enter the string:") a.append(c) for j in a: d = max(a, key=len) print("\n",d,"is the longest one")
true
97d96de1162239c5e135bc9ce921625b5c88a080
YSreylin/HTML
/1101901079/Array/array.py
242
4.40625
4
#write python program to create an array of 5 integers and display the array items. #access individual element through indexes. import array a=array.array('i',[]) for i in range(5): c=int(input("Enter array:")) a.append(c) print(a)
true
7d6b9fc6ddd4a6cc4145d1568965666b48b030ed
YSreylin/HTML
/1101901079/0012/04.py
204
4.125
4
#this program is used to swap of two variable a = input('Enter your X variable:') b = input('Enter your Y variable:') c=b d=a print("Thus") print("The value of X is:",c) print("The value of Y is:",d)
true
1a1d300c97c45ce4e321530f3a30d296fe165bf2
YSreylin/HTML
/1101901079/0012/Estring6.py
394
4.25
4
'''write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. if the string lenth of the given string is less then 3, leave it unchanged''' a = input("Enter the word:") x = a[-3:] if len(a)>3: if x=='ing': print(a+"ly") else: print(a+"ing") else: print(a)
true
4373addc9af220054ff54a7d6abb1073bf7a602d
TaviusC/cti110
/P3HW2_MealTipTax_Cousar.py
1,327
4.25
4
# CTI-110 # P3HW2 - MealTipTax # Tavius Cousar # 2/27/2019 # # Enter the price of the meal # Display tip choices # Enter the tip choice # Calculate the total price of meal (price of meal * tip + price) # Calculate the sales tax (charge * 0.07) # Calculate the total (charge + sales tax) # if tip == '0.15', '0.18', or '0.2' # Display tip # Display tax # Display total # else: # Display Error # Enter the price of meal price = float(input('Enter the price of the meal: ')) # Enter tip choices print('You have three choices for tip percentages:') print('15% - type: 0.15') print('18% - type: 0.18') print('20% - type: 0.2') tip = float(input('Enter tip: ')) # Calculations charge = price * tip + price tax = float(0.07) sales_tax = charge * tax total = charge + sales_tax # Display the tip, sales tax, and total if tip == float('0.15'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) elif tip == float('0.18'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) elif tip == float('0.2'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) else: print('Error')
true
59c807425fc3d05a2492fd09fdd09b70b2ff82a7
ImayaDismas/python-programs
/boolean.py
622
4.125
4
#!/usr/bin/python3 def main(): boo = (5 == 5) print(boo) print(type(boo)) print('logical operator AND') #logical operator AND a = (True and True) print(a) b = (True and False) print(b) c = (False and True) print(c) d = (False and False) print(d) print('logical operator OR') #logical operator OR a = (True or True) print(a) b = (True or False) print(b) c = (False or True) print(c) d = (False or False) print(d) print('different part') a, b = 0, 1 x, y = 'zero', 'one' t = x < y print(t) if a < b and x > y: print('yes') else: print('no') if __name__ == '__main__':main()
false
09e2ea08b77fa1a4e33180cac2ed46e872f281fb
ImayaDismas/python-programs
/variables_dict.py
455
4.3125
4
#!/usr/bin/python3 def main(): d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} for k in sorted(d.keys()): #sorted sorts the alphabetically print(k, d[k]) #using a different definition of the dictionaries a = dict( one=1, two = 2, three = 3, four = 4, five = 'five' )#usually are mutable a['seven'] = 7#one can add this for k in sorted(a.keys()): #sorted sorts the alphabetically print(k, a[k]) if __name__ == "__main__": main()
true
278144e8d19ad06065719defc62f8b4c2e29c786
Mansalu/python-class
/003-While/main.py
1,093
4.34375
4
# While Loops -- FizzBuzz """ Count from 1 to 100, printing the current count. However, if the count is a multiple of 3, print "Fizz" instead of the count. If the count is a multiple of 5 print "Buzz" instead. Finally, if the count is a multiple of both print "FizzBuzz" instead. Example 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz """ #Intro print("This is a FizzBuzz game.") #Defining Count and Limit for Fizz Buzz. Count = 0 Limit = 100 # Running while loop of count from 0 to 100 in increments of 1. while (Count < Limit): Count += 1 # If Count is divisible by 5 and 3 then the program prints Fizz Buzz. if (Count % 5 == 0 and Count % 3 == 0 ): print ("Fizz Buzz") # Else if the previous condition is not satisfied, # then check if count is divisible by 5 then print Buzz if it is. elif (Count % 5 == 0): print ("Buzz") elif (Count % 3 == 0): print("Fizz") # If none of these conditions are satisfied then the count is printed. else: print (Count) print ("END OF FIZZ BUZZ") # END
true
d741d285f023ad8223a5c095775a8d0b225f4b4a
cabhishek/python-kata
/loops.py
1,045
4.3125
4
def loop(array): print('Basic') for number in array: print(number) print('Basic + Loop index') for i, number in enumerate(array): print(i, number) print('Start from index 1') for i in range(1, len(array)): print(array[i]) print('Choose index and start position') for i, number in enumerate(array[1:], start=1): print(i, number) print('Basic while loop') i = 0 while i < len(array): print(i, array[i]) i +=1 print('Simulate \'while\' with \'for\'') for i in range(len(array)): print(i, array[i]) print('Basic backward loop') for number in array[::-1]: print(number) print('Backward loop with index') for i in range(len(array)-1, -1,-1): print(array[i]) print('Loops with flexible step number') for number in array[::2]: print(number) print('Iterate Curr and next element') for (curr, next) in zip(array, array[1:]): print(curr, next) loop([1,2,3,4,5,6,7,8,9,10])
true
a1d66f9acca5ecd0062f9842e07a5158b109587b
cabhishek/python-kata
/word_break.py
1,280
4.28125
4
""" Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". """ def word_break_2(word, dict): for i in range(len(word)): first = word[:i] second = word[i:] if first in dict and second in dict: return True return False print(word_break_2("leetcode", ["leet", "code"])) dict = ["leet", "code", "is", "great", "mark", "for"] string = "leetcodeismark" # More general case. def word_break(string, dict): words = [] def find_words(string): for i in range(len(string)+1): prefix = string[:i] if prefix in dict: words.append(prefix) find_words(string[i:]) find_words(string) return " ".join(words) print(word_break(string, dict)) # without closure def word_break_3(string, dict): if string in dict: return [string] for i in range(len(string)+1): prefix = string[:i] if prefix in dict: return [prefix] + word_break_3(string[i:], dict) return [] print(" ".join(word_break_3(string, dict)))
true
ec077fa4521bd2584b13d15fe3b3866dd4ff4fde
rtyner/python-crash-course
/ch5/conditional_tests.py
337
4.34375
4
car = 'mercedes' if car == 'audi': print("This car is made by VW") else: print("This car isn't made by VW") if car != 'audi': print("This car isn't made by VW") car = ['mercedes', 'volkswagen'] if car == 'volkswagen' and 'audi': print("These cars are made by VW") else: print("Not all of these cars are made by VW")
true
89573fb8b24671dd322e22c6dfcfabea58d578ed
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/kclark75/assignment07/untitled0.py
570
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 1 18:43:13 2019 @author: kenclark Class: Python 210A-Fall Teacher: David Pokrajac, PhD Assignment - """ from math import pi class Circle(object): def __init__(self, r): self.radius = r def area(self): return self.radius**2*pi def perimeter(self): return 2*self.radius*pi circle_01 = Circle(8) circle_02 = Circle(10) print(circle_01.area()) print(circle_01.perimeter()) print(circle_02.area()) print(circle_02.perimeter())
false
0c04919a425328f8a1dfcf7e612a6d8f1780e61d
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/matthew_denko/lesson03/slicing_lab.py
1,731
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 28 15:08:38 2019 @author: matt.denko """ """Write some functions that take a sequence as an argument, and return a copy of that sequence: with the first and last items exchanged. with every other item removed. with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. with the elements reversed (just with slicing). with the last third, then first third, then the middle third in the new order.""" # with the first and last items exchanged sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def exchange_first_last(seq): f = seq[0] l = seq[-1] seq[0]= l seq[-1] = f return print(seq) exchange_first_last(sequence) # with every other item removed. def every_other_removed(seq): f = seq[0] l = seq[-1] seq = [] seq.append(l) seq.append(f) return print(seq) every_other_removed(sequence) # with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def keep_the_middle(seq): del seq[0:4] del seq[-4:] return print(seq) keep_the_middle(sequence) # with the elements reversed (just with slicing). sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def elements_reversed(seq): seq[::-1] return print(sequence) elements_reversed(sequence) # with the last third, then first third, then the middle third in the new order sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def thirds_switched(seq): first = seq[-5:] second = seq[0:5] third = seq[5:10] seq = [] seq = first + second + third return print(seq) thirds_switched(sequence)
true
51cf6b8c764ffef5e24eede476fff19f76d66df4
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/jraising/lesson02/series.py
2,261
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 17 17:09:09 2019 @author: jraising """ def fibo(n): fib = [0,1] for i in range(n-1): fib.append(fib[i] + fib[i+1]) return (fib[n]) ans = fibo(5) print (ans) def lucas(n): luc = [2,1] for i in range(n-1): luc.append(luc[i] + luc[i+1]) print(luc) return (luc[n]) luca = lucas(6) print(luca) """ This function has one required parameter and two optional parameters. The required parameter will determine which element in the series to print. The two optional parameters will have default values of 0 and 1 and will determine the first two values for the series to be produced. Calling this function with no optional parameters will produce numbers from the fibo series (because 0 and 1 are the defaults). Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers. Other values for the optional parameters will produce other series. Note: While you could check the input arguments, and then call one of the functions you wrote, the idea of this exercise is to make a general function, rather than one specialized. So you should re-implement the code in this function. """ def sumseries(n, first = 0, second = 1): series =[first, second] for i in range(n): series.append(series[i] + series[i+1]) return series[n] result = sumseries(6,2,1) print(result) if __name__ == "__main__": # run some tests assert fibo(0) == 0 assert fibo(1) == 1 assert fibo(2) == 1 assert fibo(3) == 2 assert fibo(4) == 3 assert fibo(5) == 5 assert fibo(6) == 8 assert fibo(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 # test that sumseries matches fibo assert sumseries(5) == fibo(5) assert sumseries(7, 0, 1) == fibo(7) # test if sumseries matched lucas assert sumseries(5, 2, 1) == lucas(5) # test if sumseries works for arbitrary initial values assert sumseries(0, 3, 2) == 3 assert sumseries(1, 3, 2) == 2 assert sumseries(2, 3, 2) == 5 assert sumseries(3, 3, 2) == 7 assert sumseries(4, 3, 2) == 12 assert sumseries(5, 3, 2) == 19 print("tests passed")
true
e1f1be756bda5a8452dd18deec0c7e936c17f673
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/jammy_chong/lesson03/list_lab.py
1,919
4.3125
4
def create_list(): global fruit_list fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] #Seris 1 create_list() print(fruit_list) new_fruit = input("Add another fruit to the end of the list: ") fruit_list.append(new_fruit) print(fruit_list) user_number = input(f"Choose a number from 1 to {len(fruit_list)} to display fruit: ") print(f"The fruit you chose is {fruit_list[int(user_number)-1]}") second_fruit = input("Add another fruit to the beginning of the list: ") fruit_list = [second_fruit] + fruit_list print(fruit_list) third_fruit = input("Add another fruit to the beginning of the list: ") fruit_list.insert(0, third_fruit) print(fruit_list) print("The fruits that start with P are: " ) for fruit in fruit_list: if fruit[0] == "P": print(fruit) #Series 2 create_list() fruit_list.pop() print(fruit_list) #Bonus fruit_list = fruit_list * 2 print(fruit_list) #confirm_delete = 1 while True: delete_fruit = input("Type the fruit you want to delete :") if delete_fruit in fruit_list: for x in range(fruit_list.count(delete_fruit)): fruit_list.remove(delete_fruit) break #confirm_delete = 0 print(fruit_list) #Series 3 create_list() print(fruit_list) fruits_to_delete = [] for fruit in fruit_list: like = input(f"Do you like {fruit}?: ") while like not in("yes","no"): like = input("Please enter yes or no: ") if like == "no": fruits_to_delete.append(fruit) for fruit in fruits_to_delete: fruit_list.remove(fruit) if len(fruit_list) > 1: print(f"You like these fruits: {fruit_list}.") elif len(fruit_list) == 1: print(f"You like this fruit: {fruit_list[0]}.") else: print("You don't like any fruit from the list.") #Series 4 create_list() new_list = [] for item in fruit_list: new_list.append(item[::-1]) fruit_list.pop() print(f"Original list: {fruit_list}. New List: {new_list}.")
true
45e749325dc2d163416366a6a3046a83d97bbd76
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/matthew_denko/lesson02/fizz_buzz.py
603
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 21 20:51:19 2019 @author: matt.denko """ """Write a program that prints the numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number. For the multiples of five print “Buzz” instead of the number. For numbers which are multiples of both three and five print “FizzBuzz” instead.""" for i in range (1,101): if ((i % 3) + (i % 5)) < 1: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)
true
45f3e57a623f550857bb4261f6bb66287c7203ce
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/bishal_gupta/lesson03/list_lab.py
2,041
4.25
4
#!/usr/bin/env python3 """ Created on Mon Oct 28 18:25:04 2019 @author: Bishal.Gupta """ #Series 1 fruitlist = ['Apples','Pears','Oranges','Peaches'] print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) new_fruit = input("What fruit would you like to add? ") fruitlist.append(new_fruit) print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) new_number = input("What number order of fruit would you like to see? ") new_number = int(new_number) print("The", new_number, "nd or nth fruits is:", fruitlist[new_number]) fruitlist2 = ['Orange'] fruitlist = fruitlist2 + fruitlist print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) fruitlist.insert(0,'Banana') print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) for f in fruitlist: if 'P' in f: print(f) #Series 2 print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) fruitlist.pop(-1) print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) delete_fruit = input("What fruit would you like to delete? ") fruitlist.remove(delete_fruit) print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) #Series3 fruitlist = ['Apples','Pears','Oranges','Peaches'] print("The list has following fruit", len(fruitlist), "fruits:", fruitlist) lowercase_fruit = input("Do you like apples? ") fruit1 = fruitlist[0] fruit1 = fruit1.lower() fruitlist = [fruit1,'Pears','Oranges','Peaches'] lowercase_fruit = input("Do you like Pears? ") fruit2 = fruitlist[1] fruit2 = fruit2.lower() fruitlist = [fruit1,fruit2,'Oranges','Peaches'] lowercase_fruit = input("Do you like Oranges? ") fruit3 = fruitlist[3] fruit3 = fruit2.lower() fruitlist = [fruit1,fruit2,fruit3,'Peaches'] lowercase_fruit = input("Do you like Peaches? ") fruit4 = fruitlist[0] fruit4 = fruit4.lower() fruitlist = [fruit1,fruit2,fruit3,fruit4] print("The list has following fruit", len(fruitlist), "fruits:", fruitlist)
false
dda29cfb852c6093c19b19bbb8a3f4d74b5d6450
Rupesh2010/python-pattern
/pattern1.py
245
4.125
4
num = 1 for i in range(0, 3): for j in range(0, 3): print(num, end=" ") num = num + 1 print("\r") num = 0 for i in range(0, 3): for j in range(0, 3): print(num, end=" ") num = num + 1 print("\r")
false
000a7bafb0c973ba1869c322e84efb75ee41e6f1
mohamedamine456/AI_BOOTCAMP
/Week01/Module00/ex01/exec.py
249
4.125
4
import sys result = "" for i, arg in enumerate(reversed(sys.argv[1:])): if i > 0: result += " " result += "".join(char.lower() if char.isupper() else char.upper() if char.islower() else char for char in reversed(arg)) print(result)
true
dffcce747fb2c794585df237849517bd8b637d9f
data-pirate/Algorithms-in-Python
/Arrays/Two_sum_problem.py
1,690
4.21875
4
# TWO SUM PROBLEM: # In this problem we need to find the terms in array which result in target sum # for example taking array = [1,5,5,15,6,3,5] # and we are told to find if array consists of a pair whose sum is 8 # There can be 3 possible solutions to this problem #solution 1: brute force # this might not be the best choice to get the job done but will be easy to implement # time complexity: O(n^2) def two_sum_brute_force(arr, target): for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[i] + arr[j] == target: print(arr[i], arr[j]) return True return False arr = [9,3,1,4,5,1] target = 13 print(two_sum_brute_force(arr, target)) # prints 9 4 True # solution 2: Hash table # Time Complexity: O(n) # Space Complexity: O(n) def two_sum_hash_table(A, target): ht = dict() for i in range(len(A)): if A[i] in ht: print(ht[A[i]], A[i]) return True else: ht[target - A[i]] = A[i] return False A = [-2, 1, 2, 4, 7, 11] target = 13 print(two_sum_hash_table(A,target)) # solution 3: Using to indices # Here, we have two indices that we keep track of, # one at the front and one at the back. We move either # the left or right indices based on whether the sum of the elements # at these indices is either greater than or less than the target element. # Time Complexity: O(n) # Space Complexity: O(1) def two_sum(A, target): i = 0 j = len(A) - 1 while i < j: if A[i] + A[j] == target: print(A[i], A[j]) return True elif A[i] + A[j] < target: i += 1 else: j -= 1 return False A = [-2, 1, 2, 4, 7, 11] target = 13 print(two_sum(A,target))
true
aa990f7844b6d49bc9eb2c019150edbc65b32833
oskar404/code-drill
/py/fibonacci.py
790
4.53125
5
#!/usr/bin/env python # Write a function that computes the list of the first 100 Fibonacci numbers. # By definition, the first two numbers in the Fibonacci sequence are 0 and 1, # and each subsequent number is the sum of the previous two. As an example, # here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. import sys def fibonacci(size): buf = [0, 1] if size <= 2: return buf[:size] size -= 2 while size >= 0: buf.append(buf[-1]+buf[-2]) size -= 1 return buf def main(): assert len(sys.argv) == 2, "Missing number argument or too many arguments" size = int(sys.argv[1]) assert size >= 0, "Number argument must be positive" print("{}".format(fibonacci(size))) if __name__ == '__main__': main()
true
959cd3062b855c030b92cfe0f2edbbe141018508
kctompkins/my_netops_repo
/python/userinput.py
220
4.125
4
inputvalid = False while inputvalid == False: name = input("Hey Person, what's your name? ") if all(x.isalpha() or x.isspace() for x in name): inputvalid = True else: inputvalid = False print(name)
true
920db86935bce4a965494006d2e4bb255183dbc5
rvaccari/uri-judge
/01-iniciante/1008.py
1,259
4.21875
4
""" Salário Escreva um programa que leia o número de um funcionário, seu número de horas trabalhadas, o valor que recebe por hora e calcula o salário desse funcionário. A seguir, mostre o número e o salário do funcionário, com duas casas decimais. Entrada O arquivo de entrada contém 2 números inteiros e 1 número com duas casas decimais, representando o número, quantidade de horas trabalhadas e o valor que o funcionário recebe por hora trabalhada, respectivamente. Saída Imprima o número e o salário do funcionário, conforme exemplo fornecido, com um espaço em branco antes e depois da igualdade. No caso do salário, também deve haver um espaço em branco após o $. https://www.urionlinejudge.com.br/judge/pt/problems/view/1008 -- employee_id = int(input()) hours = float(input()) value = float(input()) salary = hours * value print('NUMBER = %i' % employee_id) print('SALARY = U$ %.2f' % salary) -- >>> resolve(25, 100, 5.50) NUMBER = 25 SALARY = U$ 550.00 >>> resolve(1, 200, 20.50) NUMBER = 1 SALARY = U$ 4100.00 >>> resolve(6, 145, 15.55) NUMBER = 6 SALARY = U$ 2254.75 """ def resolve(employee_id, hours, value): salary = hours * value print('NUMBER = %i' % employee_id) print('SALARY = U$ %.2f' % salary)
false
3759abcbab3aff89acc59fe4228f0146ee2eaa56
HSabbir/Design-pattern-class
/bidding/gui.py
1,717
4.1875
4
import tkinter as tk from tkinter import ttk from tkinter import * from bidding import biddingraw # this is the function called when the button is clicked def btnClickFunction(): print('clicked') # this is the function called when the button is clicked def btnClickFunction(): print('clicked') # this is the function called when the button is clicked def btnClickFunction(): print('clicked') root = Tk() # This is the section of code which creates the main window root.geometry('880x570') root.configure(background='#F0F8FF') root.title('bidding') # This is the section of code which creates the a label Label(root, text='this is a label', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=300, y=77) # This is the section of code which creates a button Button(root, text='Bidder 1', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=179, y=289) # This is the section of code which creates the a label Label(root, text='bid value', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=188, y=239) # This is the section of code which creates a button Button(root, text='Bidder 2', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=362, y=297) # This is the section of code which creates a button Button(root, text='Bidder 3 ', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=571, y=299) # This is the section of code which creates the a label Label(root, text='bid val 2', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=371, y=246) # This is the section of code which creates the a label Label(root, text='bid val 3', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=577, y=249) root.mainloop()
true
cd79e3b1ce72569bb62b994695e4483798346a0c
Luke-Beausoleil/ICS3U-Unit3-08-Python-is_it_a_leap_year
/is_it_a_leap_year.py
926
4.28125
4
#!/usr/bin/env python3 # Created by: Luke Beausoleil # Created on: May 2021 # This program determines whether inputted year is a leap year def main(): # this function determines if the year is a leap year # input year_as_string = input("Enter the year: ") # process & output try: year = int(year_as_string) if year > 0: if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("\nIt is not a leap year.") else: print("\nIt is a leap year.") else: print("\nIt is a leap year.") else: print("\nIt is not a leap a year.") else: print("\nInvalid Input.") except (Exception): print("\nInvalid Input.") finally: print("\nDone.") if __name__ == "__main__": main()
true
322be9bbf093725a12f82482cd5b9d0ffdf98dcc
bgschiller/thinkcomplexity
/Count.py
1,966
4.15625
4
def count_maker(digitgen, first_is_zero=True): '''Given an iterator which yields the str(digits) of a number system and counts using it. first_is_zero reflects the truth of the statement "this number system begins at zero" It should only be turned off for something like a label system.''' def counter(n): i = 0 for val in count(digitgen, first_is_zero): yield val if i > n: break i += 1 return counter def count(digitgen, first_is_zero=True): '''Takes an iterator which yields the digits of a number system and counts using it. If first_is_zero is True, digitgen begins counting with a zero, so when we roll over to a new place, the first value in the new place should be the element following zero. compare the two test cases for a better understanding.''' def subcount(digitgen, places): if places == 1: for d in digitgen(): yield d else: for d in digitgen(): for ld in subcount(digitgen, places - 1): yield d + ld for d in digitgen(): yield d places = 2 while True: first = first_is_zero for d in digitgen(): if first: first = False continue for ld in subcount(digitgen, places - 1): yield d + ld places += 1 if __name__ == "__main__": import string def labelelements(): for char in string.ascii_lowercase: yield char for char in string.ascii_uppercase: yield char def base2(): for d in range(2): yield str(d) label_counter = count_maker(labelelements, first_is_zero=False) for label in label_counter(200): print label base2_counter = count_maker(base2, first_is_zero=True) for b2 in base2_counter(200): print b2
true
a8f2158fe199c282b8bdc33f257f393eb70e6685
iamaro80/arabcoders
/Mad Libs Generator/06_word_transformer.py
737
4.21875
4
# Write code for the function word_transformer, which takes in a string word as input. # If word is equal to "NOUN", return a random noun, if word is equal to "VERB", # return a random verb, else return the first character of word. from random import randint def random_verb(): random_num = randint(0, 1) if random_num == 0: return "run" else: return "kayak" def random_noun(): random_num = randint(0,1) if random_num == 0: return "sofa" else: return "llama" def word_transformer(word): # your code here if word == 'NOUN': return random_noun() if word == 'VERB': return random_verb() else: return word[0] print word_transformer('verb')
true
7c017d73da7b2e702aecf6fa81114580389afe09
Numa52/CIS2348
/Homework1/3.18.py
862
4.25
4
#Ryan Nguyen PSID: 180527 #getting wall dimensions from user wall_height = int(input("Enter wall height (feet):\n")) wall_width = int(input("Enter wall width (feet):\n")) wall_area = wall_width * wall_height print("Wall area:", wall_area, "square feet") #calculating gallons of paint needed #1 gallon of paint covers 350 square feet paint_needed = wall_area / 350 print("Paint needed:", '{:.2f}'.format(paint_needed), "gallons") #rounding paint_needed to nearest whole to get # of cans needed cans = round(paint_needed) print("Cans needed:", cans, "can(s)\n") #asking user for color selection color = input("Choose a color to paint the wall:\n") if (color == 'red'): cost = cans * 35 elif (color == 'blue'): cost = cans * 25 elif (color == 'green'): cost = cans * 23 #printing the final cost print("Cost of purchasing", color, "paint: $" + str(cost))
true
f5540eb90b304d519809c8c010add05fc11e491f
sindhumudireddy16/Python
/Lab 2/Source/sortalpha.py
296
4.375
4
#User input! t=input("Enter the words separated by commas: ") #splitting words separated by commas which are automatically stored as a list. w=t.split(",") #sorting the list. w1=sorted(w) #iterating through sorted list and printing output. for k in w1[:-1]: print(k+",",end='') print(w1[-1])
true
9791dc9cb5195fba0fd7b3237a6d8d39b089a20e
GreatHayat/Sorting_Data_Structures
/insertion_sort.py
382
4.28125
4
# Insertion Sort Algorithm def insertionSort(array): n = len(array) for i in range(1, n): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j = j - 1 array[j + 1] = key # Calling the function array = [5,4,3,2,1] insertionSort(array) for i in range(len(array)): print(array[i])
false
b9cf4f68c2bcb975561600f6504248a832b565a2
letwant/python_learning
/learn_liaoxuefeng_python/函数式编程/高阶函数/高阶函数介绍.py
912
4.25
4
# -*- coding: utf-8 -*- # 高阶函数英文叫Higher-order function。什么是高阶函数?我们以实际代码为例子,一步一步深入概念。 print(abs(-10)) # 10 print(abs) # <built-in function abs> # abs(-10)是函数调用,而abs是函数本身 # 函数本身也可以赋值给变量,即:变量可以指向函数 # 如果一个变量指向了一个函数,那么,可以通过该变量来调用这个函数 f = abs value = f(-10) print(value) # 10 # 【函数名也是变量】 abs = 10 # abs(-10) # TypeError: 'int' object is not callable # 【传入函数】 # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以就收另一个函数作为参数, # 这种函数就称之为【高阶函数】 # 【小结】 # 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式
false
263387b1a516c9558c26c0d6fd2df142ff9edcc6
muondu/caculator
/try.py
528
4.40625
4
import re def caculate(): #Asks user to input operators = input( """ Please type in the math operation you will like to complete + for addition - for subtraction * for multiplication / for division """ ) #checks if the opertators match with input if not re.match("^[+,-,*,/]*$", operators): print ("Error! Only characters above are allowed!") caculate() # checks empty space elif operators == "" : print('please select one of the above operators') caculate() caculate()
true
1edd3809d431ece230d5d70d15425bd2fa62e43a
jabhij/DAT208x_Python_DataScience
/FUNCTIONS-PACKAGES/LAB3/L1.py
445
4.3125
4
""" Instructions -- Import the math package. Now you can access the constant pi with math.pi. Calculate the circumference of the circle and store it in C. Calculate the area of the circle and store it in A. ------------------ """ # Definition of radius r = 0.43 # Import the math package import math # Calculate C C = 2*math.pi*r # Calculate A A = math.pi*(r**2) # Build printout print("Circumference: " + str(C)) print("Area: " + str(A))
true
c82f373f42c0124c42d3ec8dd89184a0897998a1
jabhij/DAT208x_Python_DataScience
/NUMPY/LAB1/L2.py
614
4.5
4
""" Instructions -- Create a Numpy array from height. Name this new array np_height. Print np_height. Multiply np_height with 0.0254 to convert all height measurements from inches to meters. Store the new values in a new array, np_height_m. Print out np_height_m and check if the output makes sense. """ # height is available as a regular list # Import numpy import numpy as np # Create a Numpy array from height: np_height np_height = np.array(height) # Print out np_height print (np_height) # Convert np_height to m: np_height_m np_height_m = (0.0254 * np_height) # Print np_height_m print (np_height_m)
true
1c0357c5d25156eb2b9024fa411639ad0ff2aec9
Atrociou/Saved-Things
/todo.py
619
4.1875
4
print("Welcome to the To Do List") todoList = ["Homework", "Read", "Practice" ] while True: print("Enter a to add an item") print("Enter r to remove an item") print("Enter p to print the list") print("Enter q to quit") choice = input("Make your choice: ") if choice == "q": exit() break elif choice == "a": add = input("What would you like to add? ") todoList.append("Run") elif choice == "r": # remove an item from the list todoList.pop() print("The item has been removed. ") elif choice == "p": print(todoList) # print the list else: print("That is not a choice")
true
7ca8bdfb4b5f89ec06fb494a75413184f153401d
NISHU-KUMARI809/python--codes
/abbreviation.py
522
4.25
4
# python program to print initials of a name def name(s): # split the string into a list l = s.split() new = "" # traverse in the list for i in range(len(l) - 1): s = l[i] # adds the capital first character new += (s[0].upper() + '.') # l[-1] gives last item of list l. We # use title to print first character in # capital. new += l[-1].title() return new # Driver code s = "Avul pakir Jainulabdeen Abdul Kalam" print(name(s))
true
6c8e860f0ac34f6199c71ba0b528622dc980e61a
xdc7/pythonworkout
/chapter-03/01-extra-02-sum-plus-minus.py
1,155
4.15625
4
""" Write a function that takes a list or tuple of numbers. Return the result of alternately adding and subtracting numbers from each other. So calling the function as plus_minus([10, 20, 30, 40, 50, 60]) , you’ll get back the result of 10+20-30+40-50+60 , or 50 . """ import unittest def plus_minus(sequence): sumResult = 0 for i in range (0, len(sequence)): if i % 2 == 0 and i != 0: sumResult = sumResult - sequence[i] else: sumResult = sumResult + sequence[i] return sumResult print(plus_minus([10, 20, 30, 40, 50, 60])) print(plus_minus([10, -20, 30, 40, -50, 60])) print(plus_minus([-10, 20, 30, 40, 50, 60])) print(plus_minus([10, 20, 30, 40, -50, 60])) # class TeststringListTranspose(unittest.TestCase): # def test_blank(self): # self.assertEqual(even_odd_sums(''), [0,0]) # def test_valid01(self): # self.assertEqual(even_odd_sums([10, 20, 30, 40, 50, 60]) , [90, 120]) # # def test_valid02(self): # # self.assertEqual(even_odd_sums('Beckham Zidane Maldini Aguero Lampard'), 'Aguero,Beckham,Lampard,Maldini,Zidane') # if __name__ == '__main__': # unittest.main()
true
182bc373458a808387825084a7927ff50288e270
xdc7/pythonworkout
/chapter-02/05-stringsort.py
984
4.25
4
""" In this exercise, you’ll explore this idea by writing a function, strsort, that takes a single string as its input, and returns a string. The returned string should contain the same characters as the input, except that its characters should be sorted in order, from smallest Unicode value to highest Unicode value. For example, the result of invoking strsort('cba') will be the string abc. """ import unittest def strsort(inputString): return ''.join(sorted(inputString)) class TeststringListTranspose(unittest.TestCase): def test_blank(self): self.assertEqual(strsort(''), '') def test_valid01(self): self.assertEqual(strsort('abc'), 'abc') def test_valid02(self): self.assertEqual(strsort('cba'), 'abc') def test_valid03(self): self.assertEqual(strsort('defjam'), 'adefjm') def test_valid04(self): self.assertEqual(strsort('bcfa'), 'abcf') if __name__ == '__main__': unittest.main()
true
92188bb3349159b96640692939e9b784426ee41d
xdc7/pythonworkout
/chapter-04/03-restaurant.py
1,383
4.28125
4
""" create a new dictionary, called menu, representing the possible items you can order at a restaurant. The keys will be strings, and the values will be prices (i.e., integers). The program will then ask the user to enter an order: If the user enters the name of a dish on the menu, then the program prints the price and the running total. It then asks what else the user wants to order. If the user enters the name of a dish not on the menu, then the program scolds the user (mildly). It then asks what else the user wants to order. If the user enters an empty string, then the program stops asking, and prints the total amount. For example, a session with the user might look like this: Note that you can always check to see if a key is in a dict with the in operator. That returns True Order: sandwich sandwich costs 10, total is 10 Order: tea tea costs 7, total is 17 Order: elephant Sorry, we are fresh out of elephant today. Order: <enter> Your total is 17 """ menu = {'sandwich' : 10, 'tea' : 7, 'soup' : 9, 'soda' : 4,} totalBill = 0 while True: print('Please enter an item to order and add it to your cart. Just hit enter when you are done ordering') choice = input().strip() if not choice: break if choice not in menu: print(f'Sorry we are out of fresh {choice}') continue totalBill += menu.get(choice) print(f'Your total bill is {totalBill}')
true
a265236d9b35352de75c292cd30b2b66301aae55
xdc7/pythonworkout
/chapter-02/01-pig-latin.py
987
4.25
4
"""write a Python program that asks the user to enter an English word. Your program should then print the word, translated into Pig Latin. You may assume that the word contains no capital letters or punctuation. # How to translate a word to pig latin: * If the word begins with a vowel (a, e, i, o, or u), then add way to the end of the word. So air becomes airway and eat becomes eatway . * If the word begins with any other letter, then we take the first letter, put it on the end of the word, and then add ay . Thus, python becomes ythonpay and computer becomes omputercay . """ def wordToPiglatin(word): if len (word) < 1: return None word = word.lower() result = '' if word[0] in 'aeiou': result = word + 'way' else: result = word[1:] + word[0] + 'ay' return result print (wordToPiglatin('air')) print (wordToPiglatin('eat')) print (wordToPiglatin('python')) print (wordToPiglatin('computer')) print (wordToPiglatin('a'))
true
476c3f377be42a32630992fd0fbbc18bce1c9288
xdc7/pythonworkout
/chapter-05/5.2.2-factors.py
1,054
4.28125
4
""" Ask the user to enter integers, separated by spaces. From this input, create a dictionary whose keys are the factors for each number, and the values are lists containing those of the users' integers that are multiples of those factors. """ def calculateFactors(num): factors = [] for i in range (1, num + 1): if num % i == 0: factors.append(i) return factors uniqueFactors = [] result = {} integerInput = input('Enter integers separated by spaces...\n') integers = integerInput.split() for integer in integers: # print(f"{integer}") integer = int(integer) factors = calculateFactors(integer) for factor in factors: if factor not in uniqueFactors: uniqueFactors.append(factor) for integer in integers: integer = int(integer) for factor in uniqueFactors: if factor % integer == 0: if result.get(factor): result[factor].append(integer) else: result[factor] = [integer] print(result)
true
bfdc1168bf7bbbf621d41de4efb479b1bf4a11fe
xdc7/pythonworkout
/chapter-01/05-extra-01-hex-to-dec.py
1,737
4.25
4
""" Write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen. Implement the above program such that it doesn’t use the int function at all, but rather uses the builtin ord and chr functions to identify the character. This implementation should be more robust, ignoring characters that aren’t legal for the entered number base. """ def hexToDec(userInput): userInput = list(str(userInput)) userInput.reverse() result = 0 for i, digit in enumerate(userInput): temp = 0 if (ord(digit) >= 48 and ord(digit) <= 57) or (ord(digit) >= 65 and ord(digit) <= 70) or (ord(digit) >= 97 and ord(digit) <= 102): if ord(digit) == 48: temp = 0 elif ord(digit) == 49: temp = 1 elif ord(digit) == 50: temp = 2 elif ord(digit) == 51: temp = 3 elif ord(digit) == 52: temp = 4 elif ord(digit) == 53: temp = 5 elif ord(digit) == 54: temp = 6 elif ord(digit) == 55: temp = 7 elif ord(digit) == 56: temp = 8 elif ord(digit) == 57: temp = 9 elif ord(digit) == 65 or ord(digit) == 97: temp = 10 elif ord(digit) == 66 or ord(digit) == 98: temp = 11 elif ord(digit) == 67 or ord(digit) == 99: temp = 12 elif ord(digit) == 68 or ord(digit) == 100: temp = 13 elif ord(digit) == 69 or ord(digit) == 101: temp = 14 elif ord(digit) == 70 or ord(digit) == 102: temp = 15 else: return "Invalid hexadecimal number" tempResult = temp * 16 ** i result += tempResult return result print(hexToDec(50)) print(hexToDec('ABC')) print(hexToDec(0)) print(hexToDec('FEDC134'))
true
38a591219f2e390385353788fa8c1eb969e4d253
maurice-gallagher/exercises
/chapter-5/ex-5-6.py
2,004
4.5
4
# Programming Exercise 5-6 # # Program to compute calories from fat and carbohydrate. # This program accepts fat grams and carbohydrate grams consumed from a user, # uses global constants to calculate the fat calories and carb calories, # then passes them to a function for formatted display on the screen. # Global constants for fat calories per gram and carb calories per gram # define the main function # Define local float variables for grams of fat, grams of carbs, calories from fat, # and calories from carbs # Get grams of fat from the user. # Get grams of carbs from the user. # Calculate calories from fat. # Calculate calories from carbs. # Call the display calorie detail function, passing grams of fat, grams of carbs, # calories from fat and calories from carbs as arguments # Define a function to display calorie detail. # This function accepts grams of fat, grams of carbs, calories from fat, # and calories from carbs as parameters, # performs no calculations, # but displays this information formatted for the user. # print each piece of information with floats formatted to 2 decimal places. # Call the main function to start the program FAT_CAL_PER_GRAM = 9 CARB_CAL_PER_GRAM = 4 def main(): grams_fat = 0.0 grams_carbs = 0.0 cals_fat = 0.0 cals_carbs = 0.0 grams_fat = float(input('How many grams of fat: ')) grams_carbs = float(input('How many grams of carbs: ')) cals_fat = grams_fat * FAT_CAL_PER_GRAM cals_carbs = grams_carbs * CARB_CAL_PER_GRAM calorie_details(grams_carbs, grams_fat, cals_carbs, cals_fat) def calorie_details(grams_carbs, grams_fat, cals_carbs, cals_fat): print('Grams of fat:', format(grams_fat, ".2f")) print('Grams of carbs', format(grams_carbs, ".2f")) print('Calories from fat', format(cals_fat, ".2f")) print('Calories from carbs', format(cals_carbs, ".2f")) main()
true
667c668af92cafa7af07828df395d4d43b948b75
nazariyv/leetcode
/solutions/medium/bitwise_and_of_numbers_range/main.py
554
4.3125
4
#!/usr/bin/env python # Although there is a loop in the algorithm, the number of iterations is bounded by the number of bits that an integer has, which is fixed. def bit_shift(m: int, n: int) -> int: shifts = 0 while m != n: m >>= 1 n >>= 1 shifts += 1 return 1 << shifts # if n >= 2 * m: # return 0 # else: # r = m # # time complexity is O(n - m) # for i in range(m + 1, n + 1): # r &= i # return r if __name__ == '__main__': print(bit_shift(4, 6))
true
bc33ce706a85ee11b4aeb822256b4c23bf7f1a5e
karina-chi/python-10-2020
/Lesson2/task2.py
716
4.21875
4
# Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). items = input("Укажите значения списка через запятую:").split(",") a = 0 for i in range(int(len(items)/2)): items[a], items[a+1] = items[a+1], items[a] a += 2 print(items)
false
e305999659409116a695be650da868d41cad775c
sandeepbaldawa/Programming-Concepts-Python
/recursion/regex_matching_1.py
1,453
4.28125
4
''' Implement a regular expression function isMatch that supports the '.' and '*' symbols. The function receives two strings - text and pattern - and should return true if the text matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.' and '*' do not appear in the text string and are used as special symbols only in the pattern string. Logic ===== 1. Pattern and Text match and reach end of size 2. Text reaches end of size but pattern does not 3. Pattern reaches end of size but text does not 4. Character match or "." followed by "*" 5. Pattern and Text match ''' def match_regex(s, p): T = [[False] * (len(p)+1) for _ in range(len(s)+1)] T[0][0] = True for i in xrange(1, len(T[0])): if p[i-1] == "*": T[0][i] = T[0][i-2] for i in xrange(1, len(T)): for j in xrange(1, len(T[0])): if p[j-1] == "." or s[i-1] == p[j-1]: T[i][j] = T[i-1][j-1] elif p[j-1] == "*": T[i][j] = T[i][j-2] # * consume zero characters if s[i-1] == p[j-2] or p[j-2] == ".": # * consumes one or more T[i][j] = T[i-1][j] else: T[i][j] = False return T[len(s)][len(p)] assert match_regex("aaa","aa") == False assert match_regex("aaa","aaa") == True assert match_regex("ab","a.") == True assert match_regex("abbb","ab*") == True assert match_regex("a","ab*") == True assert match_regex("abbc","ab*") == False
true
96a0bc369ee2198c2bc03d5d555d6449a4339693
sandeepbaldawa/Programming-Concepts-Python
/recursion/cryptarithm.py
2,093
4.28125
4
Cryptarithm Overview The general idea of a cryptarithm is to assign integers to letters. For example, SEND + MORE = MONEY is “9567 + 1085 = 10652” Q. How to attack this problem? -Need list of unique letters -Try all possible assignments of single digits -Different arrangement would produce a different answer So, we want a permutation of the number of unique letters with unique numbers. First we need to get an expression… def cryptarithm(expr): We need to have a function that takes in a word and replaces the letters with digits, so it gives 3 5 6 4 instead of SEND. We can define this now inside cryptarithm and call it later. def makeCryptValue(word, map): # MakeCryptValue("SEND", {"S":5, "E":2, "N":1, "D":8 }) returns 5218 result = 0 for letter in word: #Walk through the result, get the digit and shift result = 10*result + map[letter] #10*result is the shift, map[letter] is the digit value return result # 1) Make list of words, so word[0] + word[1] = word[2]. Assume that the expression is well-formed. # Words = ["SEND", "MORE", "MONEY"] words = expr.replace("+"," ").replace("="," ").split(" ") #use str.split() # 2) Want a list of unique letters. Use sets for uniqueness letters = sorted(set("".join(words))) #Returns unique letters for digitAssignment in permutations(range(10), len(letters)): #Try every permutation of digits against letters #If 4 letters, groups of 4. If more than 10 letters, change the base map = dict(zip(letters, digitAssignment)) #Create tuples of letter/digit and put into a dictionary values = [makeCryptValue(word, map) for word in words] #Now call the function that we created earlier if (0 in [map[word[0]] for word in words]): #The first number of any word cannot be a leading 0! We can create a map to check this continue if (values[0] + values[1] == values[2]): #We win! return "%d+%d=%d" % (values[0], values[1], values[2]) return None
true
d39cf9c6a416f7678bf3b98e36ab52b6ac17997a
sandeepbaldawa/Programming-Concepts-Python
/recursion/crypto_game.py
2,243
4.34375
4
''' Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it. Input formula is a string; output is a digit-filled-in string or None. Where are we spending more time? if we run CProfile on CProfile.run('test()') we see maximum time is spent inside valid function, so how do we optimize the same? In valid function we use eval which repeated parses all tokens, we might not have to do this always. copiling this once is fine >>> f = lambda Y, M, E, U, O:(1*U+10*O+100*Y) == (1*E+10*M)**2 >>> f(2,1,7,9,8) True >>> f(1,2,3,4,5) False Check faster version in cryptogame_faster.py ''' from __future__ import division import itertools, string, re, time import cProfile def solve(formula): """Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it. Input formula is a string; output is a digit-filled-in string or None.""" for f in fill_in(formula): if valid(f): return f def fill_in(formula): "Generate all possible fillings-in of letters in formula with digits." letters = ''.join(set(re.findall('[A-Z]',formula))) #should be a string for digits in itertools.permutations('1234567890', len(letters)): table = string.maketrans(letters, ''.join(digits)) yield formula.translate(table) def valid(f): """Formula f is valid if and only if it has no numbers with leading zero, and evals true.""" try: return not re.search(r'\b0[0-9]', f) and eval(f) is True except ArithmeticError: return False tests = ("TWO + TWO == FOUR\n" "X/X == X\n" "A**N + B**N == C**N \n" "GLITTERS is not GOLD\n" "ONE < TWO and FOUR < FIVE\n" "ONE < TWO < THREE\n" "PLUTO not in set([PLANETS])\n" "ODD + ODD == EVEN\n" "sum(range(AA)) == BB\n" "sum(range(POP)) == BOBO\n" "RAMN == RA**3 + MN**3\n" "ATOM**0.5 == A + TO + M \n").splitlines() def test(): t0 = time.clock() print tests for each in tests: t_each = time.clock() print "Problem : %s Result: %s" % (each, solve(each)), print " Time Taken : ", time.clock() - t_each print "Total Time Taken : ", time.clock() - t0 print cProfile.run('test()')
true
16494f0438fe6af0cfc369187fa8c8708bda7925
sandeepbaldawa/Programming-Concepts-Python
/lcode/amazon/medium_sort_chars_by_freq.py
504
4.25
4
''' Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" ''' from collections import defaultdict class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ res = defaultdict(int) for each in s: res[each] += 1 res = sorted(res.items(), key = lambda i: i[1], reverse=True) return "".join([key*val for key,val in res])
true
4fcf4d2382a0222c93bcd328383399ea292ea031
isrishtisingh/python-codes
/URI-manipulation/uri_manipulation.py
1,173
4.125
4
# code using the uriModule # the module contains 2 functions: uriManipulation & uriManipulation2 import uriModule # choice variable is for choosing which function to use for manipulating the URL/URI choice = -1 try: choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/URL \n")) except ValueError: print("Invalid input\n") exit() if (choice == 1): print(" \n Enter any of the following numbers to get parts of the URI/URL : ") n = input(" 1 for scheme \n 2 for sub-domain \n 3 for domain \n 4 for directory/path \n 5 for sub-directory/query \n 6 for page/fragment\n\n ") try: if (type(n) != int): uriModule.uriManipulation(n) except TypeError: print("Your input must be a number\n") elif(choice == 2): url = input("Enter a URL: ") print(" \n Enter any of the following numbers to get parts of the URI/URL : ") n = int(input(" 1 for scheme \n 2 for authority+domain \n 3 for directory/path \n 4 for sub-directory/query \n 5 page/fragment\n\n ")) print(uriModule.uriManipulation2(url, n)) else: print("\nInvalid choice\n")
true
89ea463ab59b1aa03b14db54ec8d86a8a4168fcf
iriabc/python_exercises
/exercise3.py
2,082
4.46875
4
from collections import deque def minimum_route_to_treasure(start, the_map): """ Calculates the minimum route to one of the treasures for a given map. The route starts from one of the S points and can move one block up, down, left or right at a time. Parameters ---------- the_map: list of lists Matrix containing the points of the map e.g. [ [‘S’, ‘O’, ‘O’, 'S', ‘S’], [‘D’, ‘O’, ‘D’, ‘O’, ‘D’], [‘O’, ‘O’, ‘O’, ‘O’, ‘X’], [‘X’, ‘D’, ‘D’, ‘O’, ‘O’], [‘X', ‘D’, ‘D’, ‘D’, ‘O’], ] Map with different features: - S is a point you can start from - O is a point you can sail in - D is a dangerous point you can't sail in - X is the point with the treasure """ # Map dimensions width = len(the_map) height = len(the_map[0]) # Check that the map has some dimensions if width == 0 or height == 0: raise ValueError("Please provide a valid map") # Define start point and features treasure = "X" danger = "D" # Create a queue to store the track queue = deque([[start]]) visited = [start] # Find the path while queue: path = queue.popleft() x, y = path[-1] # Check if we have found the treasure if the_map[x][y] == treasure: return path # Move using one of the possible movements for x2, y2 in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): if 0 <= x2 < width and 0 <= y2 < height and the_map[x2][y2] != danger \ and (x2, y2) not in visited: queue.append(path + [(x2, y2)]) visited.append((x2, y2)) def min_route_to_many_treasures(the_map): # Filter the starting points starts = [(0, 0), (0, 3), (0, 4)] paths = [minimum_route_to_treasure(start, the_map) for start in starts] shortest_path = min(paths, key=len) return shortest_path
true
a3c232a6c220ad1a72284e764c9e70f19fc672b8
NoName3755/basic-calculator
/calculator.py
1,108
4.21875
4
calculate = True while calculate: try: x = int(input("Enter your first number: ")) y = int(input("Enter your second number: ")) except(ValueError): print("not an integer") else: o = input("enter your operator in words :") if o == "addition" or o == "+": a = x + y print(f"{x} + {y} = {a}") elif o == "subtraction" or o == "-": a = x - y print(f"{x} - {y} = {a}") elif o == "division" or o == "/": a = x * y print(f"{x} / {y} = {a}") elif o == "multiplication" or o == "*": a = x * y print(f"{x} * {y} = {a}") else: print("wrong operator") print(((""" type addition for addition or "+" type subtraction for subtraction or "-" type multiplication for multiplication or "*" type division for division or "/" """))) try_again = input("do you want to try again y/n : ") if try_again == "yes" or "y": calculate = True else: calculate = False
false
19d10ffc36a71b8e662857b9f83cbdecdb47114e
TnCodemaniac/Pycharmed
/hjjj.py
567
4.125
4
import turtle num_str = input("Enter the side number of the shape you want to draw: ") if num_str.isdigit(): s= int(num_str) angle = 180 - 180*(10-2)/10 turtle.up x = 0 y = 0 turtle.setpos(x,y) numshapes = 8 for x in range(numshapes): turtle.color("red") x += 5 y += 5 turtle.forward(x) turtle.left(y) for i in range(squares): turtle.begin_fill() turtle.down() turtle.forward(40) turtle.left(angle) turtle.forward(40) print (turtle.pos()) turtle.up() turtle.end_fill()
true
653c0e75c90f2f607eb46df5a885b47cbbd8d107
Prolgu/PyExamples
/Diccionario-For_menu.py
1,605
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Diccionario-For_menu.py # # # import os salir = False dic={'1': '0', '2': '0', '3': '0', '4': '0'}#defino mi diccionario def menu(): #mi memu principal os.system('clear') print("Esto parece un menu:") print("\t1 - Ingresar valores") print("\t2 - Leer valores") print("\tq - Para salir") def ingreso(): os.system('clear') #limpio for key in dic.keys(): #Bucle de ingreso dic[key]=input(f"Valor[{key}]: ") #repito hasta ingresar un dato por cada entrada del diccionario def imprimo(): os.system('clear') #limpio print("Ingresaste estos valores:") for key in dic.keys(): #bucle de impresion print(key, "->",dic[key]) #Imprimo #def menu_salida(): while not salir: menu() a = input("Inserta un valor >> ") if a=="1": ingreso() input("\nPresiona una tecla para continuar.") elif a=="2": imprimo() input("\nPresiona una tecla para continuar.") elif a=="q": salida = False while not salida: os.system('clear') b = input("Desea salir?\n1 - Si.\n2 - No.\n") if b=="1": salir = True os.system('clear') break elif b=="2": os.system('clear') salida = True else: print("") input("Ingresa algo del menu.") else: print("") input("Ingresa algo del menu.\n")
false
2d5a337a4cef68a85705c164d5dcdfbd4edb5e17
nembangallen/Python-Assignments
/Functions/qn10.py
384
4.15625
4
""" 10. Write a Python program to print the even numbers from a given list. Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8] """ def get_even(my_list): even_list = [] for item in my_list: if (item % 2 == 0): even_list.append(item) else: pass return even_list print(get_even([1, 2, 3, 4, 5, 6, 7, 8, 9]))
true
8a872760535ef1b17100bdd9faee4ff6609c1b8d
nembangallen/Python-Assignments
/Functions/qn13.py
395
4.21875
4
""" 13. Write a Python program to sort a list of tuples using Lambda. """ def sort_tuple(total_student): print('Original List of tuples: ') print(total_student) total_student.sort(key=lambda x: x[1]) print('\nSorted:') print(total_student) total_student = [('Class I', 60), ('Class II', 53), ('Class III', 70), ('Class V', 40)] sort_tuple(total_student)
true
040902675356f5d842d290c5b0570546bc83c9cb
nembangallen/Python-Assignments
/Functions/qn8.py
387
4.28125
4
""" 8. Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5] """ def unique_list(my_list): unique_list = [] for x in my_list: if x not in unique_list: unique_list.append(x) return unique_list print(unique_list([1, 2, 3, 3, 3, 4, 5, 5]))
true
ecedcca7da6cd799acc1bce8c0e2b4361c9652a4
BlaiseMarvin/pandas-forDataAnalysis
/sortingAndRanking.py
1,820
4.34375
4
#sorting and ranking # to sort lexicographically, we use the sort_index method which returns a new object import pandas as pd import numpy as np obj=pd.Series(range(4),index=['d','a','b','c']) print(obj) print("\n") print(obj.sort_index()) #this sorts the indices #with a dataframe, you can sort by index on either axis frame=pd.DataFrame(np.arange(8).reshape((2,4)),index=['three','one'],columns=['d','a','b','c']) print("\n") print(frame) print("\n") print(frame.sort_index()) # it originally sorts the row index #sorting the column index print(frame.sort_index(axis=1)) #by default, the data is sorted in ascending order, we can change that though print(frame.sort_index(axis=1,ascending=False)) #to sort a series by its values, you make use of the sort_values method obj=pd.Series([4,7,-3,2]) print(obj) print(obj.sort_values()) #Any missing values are always sorted to the end #when sorting,you can sort by some data frame= pd.DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]}) print(frame) print(frame.sort_values(by='b')) #to sort by multiple columns, we pass a list of names print(frame.sort_values(by=['a','b'])) #Ranking #ranking assigns ranks from one through the number of valid data points in an array #The rank method for series and Dataframe are the place to look, ties are broken by assigning the mean rank obj=pd.Series([7,-5,7,4,2,0,4]) print("\n") print(obj) print("\n") print(obj.rank()) #Ranks can also be assigned acoording to the order in which they're observed in the data print(obj.rank(method='first')) #Ranks can also be assigned in descending order print(obj.rank(ascending=False,method='max')) #A dataframe can compute ranks over the columns and rows frame=pd.DataFrame({'b':[4.3,7,-3,2],'a':[0,1,0,1],'c':[-2,5,8,-2.5]}) print(frame) print("\n") print(frame.rank(axis='columns'))
true
7d44b3978280fed567e2422c24f0d2488c28d89d
vandent6/basic-stuff
/elem_search.py
893
4.15625
4
def basic_binary_search(item, itemList): """ (str, sequence) -> (bool) Uses binary search to split a list and find if the item is in the list. Examples: basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> True basic_binary_search(99,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> False """ found = False while found == False: half = round(len(itemList)/2) if not half % 2: half -= 1 if len(itemList) == 1: return itemList[0] == item if itemList[half] == item: found == True if item >= itemList[half]: itemList = itemList[half:] elif item < itemList[half]: itemList = itemList[:half] return found print(basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]))
true
2817f68fa0dc08ba61921f04a3c4ea5eccc31b38
ltrii/Intro-Python-I
/src/cal.py
1,702
4.6875
5
# """ # The Python standard library's 'calendar' module allows you to # render a calendar to your terminal. # https://docs.python.org/3.6/library/calendar.html # Write a program that accepts user input of the form # `calendar.py month [year]` # and does the following: # - If the user doesn't specify any input, your program should # print the calendar for the current month. The 'datetime' # module may be helpful for this. # - If the user specifies one argument, assume they passed in a # month and render the calendar for that month of the current year. # - If the user specifies two arguments, assume they passed in # both the month and the year. Render the calendar for that # month and year. # - Otherwise, print a usage statement to the terminal indicating # the format that your program expects arguments to be given. # Then exit the program. # """ import sys import calendar from datetime import datetime dt = datetime.today() if len(sys.argv) == 3: month = str(sys.argv[1]) year = str(sys.argv[2]) elif len(sys.argv) == 2: month = str(sys.argv[1]) year = dt.year elif len(sys.argv) == 1: month = dt.month year = dt.year month = int(month) year = int(year) if month & year == None: print("Please provide at least one argument (month, year).") if year == None: year = datetime.date.today().strftime("%Y") if month == None: month = datetime.date.today().strftime("%B") if month > 12: print("Month provided is above range") elif month < 1: print("Month provided is below range") else: month = int(month) year = int(year) cal = calendar.TextCalendar(firstweekday=6) curCal = "\n" + cal.formatmonth(year, month) print(curCal)
true
4d726618926c5e8d18a6f6a1f6b69fe670c46ad5
JayVer2/Python_intro_week2
/7_dictionaries.py
469
4.125
4
#Initialize the two dictionaries meaningDictionary = {} sizeDictionary = {} meaningDictionary["orange"] = "A Fruit" sizeDictionary["orange"] = 5 meaningDictionary["cabbage"] = "A vegetable" sizeDictionary["cabbage"] = 10 meaningDictionary["tomato"] = "Widely contested" sizeDictionary["tomato"] = 5 print("What definition do you seek?") query = input() print("The size of " + query + " is " +str(sizeDictionary[query]) + ", it means: " + meaningDictionary[query])
true
b019d0cd997e8c94e5af01ff7f05f0ff8496ba70
avyartemis/UoPeople.CS1101.PythonProgrammingAssignments
/RainbowColors (Inverted Dictionary).py
1,544
4.28125
4
# CS1101(Intro To Python). Chapter 11: Dictionaries. Week 7. By Avy Artemis. # Theme: Creating an Artistic Inverted Dictionary RainbowColors = {'C1': ['Red', 'Rose', 'Sangria', 'Scarlet', 'Warm Colours'], 'C2': ['Orange', 'Carrot', 'Sandstone', 'Warm Colours'], 'C3': ['Yellow', 'Bumble Bee', 'Dandelion', 'Warm Colours'], 'C4': ['Green', 'Chartreuse', 'Olive', 'Calming Effects'], 'C5': ['Blue', 'Navy', 'Ocean', 'Denim', 'Cerulean', 'Cool Colours', 'Calming Effects'], 'C6': ['Indigo', 'Purple', 'berry', 'Cool Colours', 'Calming Effects'], 'C7': ['Violet', 'Purple', 'Lavender', 'Cool Colours', 'Calming Effects']} print('Original dictionary contains', RainbowColors) print('\n') def invert_dict(d): inverse = dict() for key in d: val = d[key] for sub_key in val: if sub_key not in inverse: inverse[sub_key] = [key] else: inverse[sub_key].append(key) return inverse inverted_Rainbow = invert_dict(RainbowColors) print('Inverted colorful dictionary now contains', inverted_Rainbow) # My dictionary describes the 7 colors of a rainbow and lists examples of its shade. # My inverted dictionary helps to tell an artist which color is 'warm' or 'cool' colors especially if the palette name # is new and obscure to them. This can potentially teach and help them to organize hundreds to thousands of # color codings in design software.
false
b56bdb3019523f776ca7e6078a04ca14f9a2bd92
mohitsharma98/DSA-Practice
/queue.py
563
4.125
4
class queue: def __init__(self): self.s = [] def enqueue(self, x): self.s.append(x) def dequeue(self): if len(self.s)>=1: self.s = self.s[1:] else: print("Queue is empty!") def show(self): print(self.s) if __name__ == "__main__": q = queue() q.enqueue(1) q.enqueue(3) q.enqueue(8) q.enqueue(5) print("Queue after the enqueue operation : {}".format(q.show())) q.dequeue() print("Queue after the dequeue operation : {}".format(q.show()))
false
4207246674a228f5ab87bf29c41ef6677a1165fc
jaclynchorton/Python-MathReview
/Factorial-SqRt-GCD-DegreeAndRadians.py
556
4.15625
4
#------------------From Learning the Python 3 Standard Library------------------ #importing math functions import math #---------------------------Factorial and Square Root--------------------------- # Factorial of 3 = 3 * 2* 1 print(math.factorial(3)) # Squareroot of 64 print(math.sqrt(64)) # GCD-Greatest Common Denominator. Useful for reducing fractions # 8/52 = 2/13 # GCD between 8 and 52 is 4, so we can divide the numerator and denominator by 4 # to get a reduced fraction print(math.gcd(52, 8)) print(math.gcd(8, 52)) print(8/52) print(2/13)
true
d0c7bab49992c2e2fc6dbd76104d6846183eb51a
pilihaotian/pythonlearning
/leehao/learn104.py
746
4.125
4
# 继承、派生 # 继承是从已有类中派生出新类,新类具有原类的行为和属性 # 派生是从已有类中衍生出新类,在新类中添加新的属性和行为 # 基类、超类、父类、派生类、子类 # 单继承 class Human: def say(self, what): print("说", what) def walk(self, distance): print("走了", distance, "公里") class Student(Human): # 重写父类 def say(self, what): print("学生说", what) def study(self, subject): print("学生正在学习", subject) class Teacher(Human): # 重写父类 def say(self, what): print("老师", what) stu1 = Student() stu1.say("今天天气不错") stu1.walk(10) stu1.study('python')
false
b582d0dced5a0303819dd5a8a3cb3b7d50fbe648
sevkembo/code_examples
/dice.py
1,094
4.21875
4
from random import randint class Dice: def __init__(self, sides=6): self.sides = sides def roll_dice(self): if self.sides == 6: print(randint(1, 6)) elif self.sides == 10: print(randint(1, 10)) elif self.sides == 20: print(randint(1, 20)) while True: try: user_input = int(input('How many faces does a dice have? ')) except ValueError: print("Enter an integer !!!") continue else: user = Dice(user_input) if user_input == 6 or user_input == 10 or user_input == 20: print(f'Random number from a dice with {user_input} faces: ') user.roll_dice() roll_again = input('Do you want to roll again? (yes/no) ') if roll_again == 'yes': continue elif roll_again == 'no': break else: break else: print('Possible values: 6, 10, 20') input("Thanks for the game. Press 'ENTER' to exit.")
false
0eacae023b58e7727bcfcec37684d47ab49ddfbb
Jabed27/Data-Structure-Algorithms-in-Python
/Algorithm/Graph/BFS/bfs.py
1,508
4.25
4
# https://www.educative.io/edpresso/how-to-implement-a-breadth-first-search-in-python from collections import defaultdict visited = [] # List to keep track of visited nodes. queue = [] #Initialize a queue #initializing a default dictionary with list graph=defaultdict(list) parent=[] dist=[] def init(n): for i in range(n+1): dist.append(-1) for i in range(n+1): parent.append(-1) def shortestPath(i): if(parent[i]==-1): print(i,end=' ') return shortestPath(parent[i]) print(i,end=' ') def ShortestDistance(source): for i in range(1,len(visited)+2): if(i != source): if(dist[i]!=-1): dist[i]*=6 print("\n"+str(i)+"->"+str(dist[i]),end='\n') print("Shortest path: ") shortestPath(i) def bfs(visited, graph, source): visited.append(source) queue.append(source) dist[source]=0 print("BFS traversals: ") while queue: s = queue.pop(0) print (s, end = " ") for neighbour in graph[s]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) dist[neighbour]=dist[s]+1 parent[neighbour]=s print("\n") ShortestDistance(source) # Driver Code node,edge=input().split() for i in range(int(edge)): a,b= input().split() graph[int(a)].append(int(b)) graph[int(b)].append(int(a)) starting_node=int(input()) init(int(node)) bfs(visited, graph, starting_node)
true
a4a2e639b8c672ebfdb7f8b67f1f567c1ebc704e
Programmer7129/Python-Basics
/Functions.py
444
4.25
4
# For unknown arguments in a function def myfunc(**name): print(name["fname"]+" "+name["lname"]) myfunc(fname="Emily", lname="Scott") def func(*kids): print("His name is: "+ kids[1]) func("Mark", "Harvey", "Louis") # Recursion def recu(k): if(k > 0): result = k + recu(k-1) print(result) else: result = 0 return result print("The Recursion Example Results \n") recu(3)
true
79072e55960b5de9f56486db34748bfaa55c08b9
FayazGokhool/University-Projects
/Python Tests/General Programming 2.py
2,320
4.125
4
def simplify(list1, list2): list1_counter,list2_counter = 0,0 #This represents the integer in each array that the loop below is currently on list3 = [] #Initialise the list list1_length, list2_length = len(list1), len(list2) #Gets the length of both lists and stores them as varibales so they don't have to be called again and again both_lists_checked = False #Used for While Loop, False until all integers in both arrays checked while both_lists_checked == False: if list1_counter <= list1_length-1: #checks if counter still in range list1_number = list1[list1_counter] #sets current integer in each array (so that it doesn't have to be called again and again) if list2_counter <= list2_length-1: list2_number = list2[list2_counter] if list1_counter>=list1_length and list2_counter>=list2_length: #Checks both lists have been fully iterated through both_lists_checked=True #Exits loop elif list1_counter>=list1_length: # this and the next elif checks if either list has been fully chekced for i in range(list2_counter,list2_length): #if yes, it adds all the remaining items in the other list to the final list (but not repeats) if not list2[i] in list3: list3.append(list2[i]) both_lists_checked = True; elif list2_counter>=list2_length: for i in range(list1_counter,list1_length): if not list1[i] in list3: list3.append(list1[i]) both_lists_checked = True; if list1_number==list2_number and not (list1_number in list3): #Checks if two numbers are the same and not in final list list3.append(list1[list1_counter]) #If yes, adds it to the final list and increments the counter for both list1_counter+=1 list2_counter+=1 elif list1_number>list2_number and not (list2_number in list3): # The next two elifs Checks if number in one list is greater than the element being analysed in the next list list3.append(list2[list2_counter]) #if yes, adds the lesser number to the final list and increments the list where the number was found's counter list2_counter+=1 elif list2_number>list1_number and not (list1_number in list3): list3.append(list1[list1_counter]) list1_counter+=1 return list3 list2 = [1,2,3] list1 = [0,1,3,4] #Simple test case, returns correct answer final_list = simplify(list1,list2) print(final_list)
true
39fdd0263563f932f80ce91303ba69e74bf67259
leilii/com404
/1-basics/3-decision/4-modul0-operator/bot.py
214
4.375
4
#Read whole number UserWarning. #work out if the number is even. print("Please enter a number.") wholenumber=int(input()) if (wholenumber%2 == 0): print("The number is even") else: print("The number is odd")
true
b7d81a61e20219298907d2217469d74539b10ac4
fwparkercode/Programming2_SP2019
/Notes/RecursionB.py
806
4.375
4
# Recursion - function calling itself def f(): print("f") g() def g(): print("g") # functions can call other functions f() def f(): print("f") f() g() def g(): print("g") # functions can also call themselves #f() # this causes a recursion error # Controlling recursion with depth def controlled(depth, max_depth): print("Recursion depth:", depth) if depth < max_depth: controlled(depth + 1, max_depth) print("Recursion depth", depth, "has closed") controlled(0, 10) # Factorial def factorial(n): total = 1 for i in range(1, n + 1): total *= i return total print(factorial(1000)) def recursive_factorial(n): if n > 1: return n * recursive_factorial(n - 1) else: return n print(recursive_factorial(1000))
true
21f141bbd269f85b302c1950cc0f2c8705f97854
tejasgondaliya5/advance-python-for-me
/class_variable.py
615
4.125
4
class Selfdetail: fname = "tejas" # this is class variable def __init__(self): self.lname = "Gondaliya" def printdetail(self): print("name is :", obj.fname, self.lname) # access class variable without decorator @classmethod # access class variable with decorator def show(cls): print(cls.fname) obj = Selfdetail() obj.printdetail() Selfdetail.show() # access calss variable outside class with decorator print(Selfdetail.fname) # Access class variable outside only class_name.variable_name
true
298c5f852cc317067c7dfcceb529273bbc89ec66
tejasgondaliya5/advance-python-for-me
/Method_Overloding.py
682
4.25
4
''' - Method overloding concept is does not work in python. - But Method ovrloding in diffrent types. - EX:- koi ek method ma different different task perform thay tene method overloading kehvay 6. ''' class Math: # def Sum(self, a, b, c): def Sum(self, a = None, b=None, c=None): # this one method but perform differnt task that reason this is method overloading if a!=None and b!=None and c!=None: s = a+b+c elif a!=None and b!=None: s = a=b else: s = "Provide minimum two argument" return s obj = Math() print(obj.Sum(10, 20, 30)) print(obj.Sum(10, 20)) print(obj.Sum(10))
true
08421cdc822d1ee9fb6a906927bb4836f1bc691f
YuanchengWu/coding-practice
/problems/1.4.py
605
4.1875
4
# Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin­ drome. # A palindrome is a word or phrase that is the same forwards and backwards. # A permutation is a rearrangement of letters. # The palindrome does not need to be limited to just dictionary words. def palindrome_permutation(s): seen = set() counter = 0 for c in s: if c != ' ': if c not in seen: seen.add(c) counter += 1 return counter % 2 == len(''.join(s.split())) % 2 s = input('Enter string: ') print(palindrome_permutation(s))
true
767b3239ad235c29906cc7f903713ac0c67712c7
laboyd001/python-crash-course-ch7
/pizza_toppings.py
476
4.34375
4
#write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you'll add that to their pizza. prompt = "\nPlease enter the name of a topping you'd like on your pizza:" prompt += "\n(Enter 'quit' when you are finished.) " while True: topping = input(prompt) if topping == 'quit': break else: print("I'll add " + topping + " to your pizza!")
true
77a0cf7be579cd67bf2f9a449d8615c682924d6f
dipeshdc/PythonNotes
/loops/for.py
782
4.125
4
""" For Loop """ sentence = "the cat sat on the mat with"# the rat cat and rat were playing in the mat and the cat was happy with rat on the mat" ''' print("Sentence is: ",sentence) print("Length of sentence:", len(sentence)) print("Number of Occurrences of 'cat': ", sentence.count('t')) #3 ''' count=0 for char in sentence: #foreach char inside sentence: count = count+1 #1 2 3 4 5.....20 print(count," > ",char) #range(start, stop[, step]) print("\n Range range(startfrom,stopat,interval)") for num in range(1,22,2): print("Range : ",num) ''' for i in range(10): print("Range : ",i) #xrange() used for very long ranges, Python 3 handles same with range() for i in range(5000): #xrange(5000) if(i%100==0): print("xRange % 100 : ",i) '''
true
014db87928669d171b65f3c43c09aca9345843bc
MrLVS/PyRep
/HW5.py
621
4.15625
4
print("Введите неотрицательные целые числа, через пробел: ") answer = input("--> ") def find_min_int_out_of_string(some_string): """ A function to find the minimum number outside the list. """ int_list = list(map(int, some_string.split())) for i in range(1, max(int_list)+1): if i not in int_list: print(i) break elif i not in int_list and i == 1: print(max(int_list)+1) break elif i == max(int_list): print(max(int_list)+1) break find_min_int_out_of_string(answer)
true
35d0fce23734caccf4dc22ddec7175a2230b3c5d
MrLVS/PyRep
/HW10.py
496
4.21875
4
# Solution of the Collatz Hypothesis def сollatz(number): """ A function that divides a number by two if the number is even, divides by three if the number is not even, and starts a new loop. Counts the number of cycles until the number is exactly 1. """ i = 0 while number > 1: if number % 2 == 0: number = number / 2 i += 1 elif number % 2 != 0: number = number * 3 + 1 i += 1 print(i) Collatz(12)
true
4dc8fcf6c516ca8bf19c652eef0ab235aa0dc1c4
frederatic/Python-Practice-Projects
/palindrome.py
509
4.3125
4
# Define a procedure is_palindrome, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. def is_palindrome(s): if s == "": # base case return True else: if s[0] == s[-1]: # check if first and last letter match return is_palindrome(s[1:-1]) # repeat using rest else: return False print is_palindrome('') #>>> True print is_palindrome('abab') #>>> False print is_palindrome('abba') #>>> True
true
6a141c1e62a9565c54b544ea6ec058d650d03e0d
olimpiojunior/Estudos_Python
/Section_9/list_comprehension_p1.py
1,062
4.1875
4
""" list Comprehension Utilizadando list comprehension nós podemos gerar ovas listas com dados processados a partir de outro iterável #Parte 01 #1 num = [1,2,3,4,5] res = [i * 10 for i in num if i%2 != 0] print(res) #2 print([i**2 for i in [1,2,3,4,5]]) #3 nome = 'olimpio' print([l.upper() for l in nome]) #4 lista = 'maria', 'julia', 'guilherme', 'vanessa' def caixa_alta(nome): nome = nome.replace(nome[0], nome[0].upper()) return nome print([caixa_alta(nome) for nome in lista]) #5 print([bool(valor) for valor in [0, [], '', True, 1, 3.14]]) #6 print([str(valor) for valor in range(0,10, 2)]) """ #Parte2 #1 num = [1,2,3,4,5,6,8, 9] par = [x for x in num if x%2 == 0] impar = [x for x in num if x%2 == 1] #ou #Em numeros pares, o módulo de 2 é zero, em python 0 == False (not False = True) pares = [x for x in num if not x % 2] impares = [x for x in num if x % 2] print(par) print(impar) print(pares) print(impares) #2 res = [n*2 if n%2 == 0 else n/2 for n in num] rit = [n**2 if n == 2 else n-5 for n in num] print(res) print(rit)
false
2c8aaddc8adb1e71d2d44161c44e2842a686354e
olimpiojunior/Estudos_Python
/testes/Teste4.py
1,376
4.28125
4
""" mypy só funciona quando se utiliza o type hinting type hinting é a utilização de atributos com os tipos sendo passados dentro da função, como abaixo """ import math def cabecalho(texto: str, alinhamento: bool = True) -> str: if alinhamento: return f"{texto.title()}\n{'-'*len(texto)}" else: return f" {texto.title()} ".center(50, '+') nome = cabecalho('olimpio junior') nome2 = cabecalho('olimpio junior', alinhamento=False) print(nome) print(nome2) print(type(nome)) print(type(nome2)) nome3 = cabecalho('olimpio junior', alinhamento=True) print(nome3) def circunf(raio: float) -> float: return 2 * math.pi * raio ** 2 print(circunf(2.)) num: float = 5. print(__annotations__) print(circunf.__annotations__) print(' olimpio junior '.center(50, '#').title()) class Pessoa: def __init__(self, nome: str, idade: int, peso: float): self.__nome = nome self.__idade = idade self.__peso = peso @property def nome(self): return self.__nome def andar(self): return f'{self.__nome} está andando!' olimpio = Pessoa('Olimpio', 24, 81.4) print(olimpio.__dict__) print(olimpio.andar()) print(olimpio.nome) # Obs: Classe não tem annotations, mas é possivel acessar com __init__ print(olimpio.andar.__annotations__) # Retorna um dict vazio print(olimpio.__init__.__annotations__)
false
da3d214c93118d4ba3947536ca5dd7163298b59a
olimpiojunior/Estudos_Python
/Section 8/funcoes_com_parametros.py
1,002
4.34375
4
''' Funções com parametros funções que recebem dados para serem processados dentro da função entrada -> processamento -> saida A função é feita com parametros, Ao usar essa funão é passado os argumentos ----------------------------------------------------- def quadrado(x): return x**2 print(quadrado(2)) print(quadrado(3)) print(quadrado(4)) ----------------------------------------------------------- def nome_completo(nome, sobre): return f'Certificamos que {nome.title()} {sobre.title()} concluiu o curso com exito' print(nome_completo('olimpio', 'barbosa dos santos junior')) ------------------------------------------------------------ def nome_completo(nome, sobre): return f'Certificamos que {nome.title()} {sobre.title()} concluiu o curso com exito' #Argumentos nomeados nome = 'olimpio' sobre = 'junior' print(nome_completo(nome, sobre)) print(nome_completo(nome = 'bartolomeu', sobre = 'judioli')) print(nome_completo(sobre = 'graciel', nome = 'emanuel')) '''
false
9f6e71d2b6edee357d69aef795a686b0ce85e1ff
olimpiojunior/Estudos_Python
/Section_10/map.py
1,110
4.5
4
""" map - função map realiza mapeamento de valores para função function - f(x) dados - a1, a2, a3 ... an map object: map(f, dados) -> f(a1), f(a2), f(a3), ...f(an) ------------------------------------------------------------------- import math def calc(r): return math.pi * (r**2) raios = [1, 2.2, 3., 4, 5.7, 8] lista = [] for i in raios: lista.append(calc(i)) print(lista) #Usando map - map(função, intervalo), retorna um map object areas2 = map(calc, raios) print(list(areas2)) print(type(areas2)) #map com lambda print(list(map(lambda r: math.pi * r**2, raios))) print(tuple(map(lambda r: math.pi * r**2, raios))) print(set(map(lambda r: math.pi * r**2, raios))) #OBS: Após utilizar a função map(), após a primeira utilização dos resultados, os valores são zerados ----------------------------------------------------------------------------------------------------- """ cidades = [('Berlin', 45), ('Tókio', 55), ('Rio', 27), ('Nairobi', 34), ('cairo', 65), ('Paris', 12)] print(cidades) c_para_f = map(lambda dado: (dado[0], (9/5)*dado[1]+32), cidades) print(list(c_para_f))
false
ed9f95a6170b0477fa4ea6a336b336735a452702
abidtkg/Practices
/python/json.py
680
4.3125
4
# full_name = input("Enter your name: ") # birth_year = int(input("Enter your age: ")) # print(f'Hi, {full_name}. How are you today?') # feeling = input("Type: ") # print(f'Hey {full_name}, your birth year is {birth_year} ? is it true?') # age_confirm = input("y/n? :") # print(f'you are {feeling} tody so, it\'s a good chance for do it') # if age_confirm == "y": # print("true") # elif age_confirm == "y": # print("False") # else: # print("google.com") full_name = input("What's your name? : ") todays_year = int(input("Enter today's year : ")) born_age = int(input("What is your age? : ")) age = todays_year - born_age print(f'Hi, {full_name} your birth date {age}')
false
916c450d31f5c5cc27f4aa1158f53be1ae761e2b
AlanEstudo/Estudo-de-Python
/aula17a.py
905
4.1875
4
# Variáveis Compostas (Listas) # .append(' ') => adiciona um elemento no final da lista # .insert(0, ' ') => adiciona um elemento no inicio ou no indice da lista # del variavel[3] => apaga o elemento na indice 3 # variavel.pop(3) => apaga o elemento no indice 2, caso não passa o indici apaga o ultimo elemento # variavel.remove('item') => remove pelo valor da lista # valores = list(range(4, 11)) => cria uma lista # lista.sort() => colocar em ordem os valores dentro da lista # lista.sort(reverse=True) => colocar os valores e orden decrescente # len(lista) => saber quantos elementos tem na lista #valores = [] #for cont in range(0, 5): # valores.append(int(input('Digite um valor: '))) #for c, v in enumerate(valores): # print(f'Na posição {c} encontrei o valor {v} !') #print('Cheguei no final da lista.') a = [2, 3, 4, 7] b = a[:] b[2] = 8 print(f'lista A: {a}') print(f'lista B: {b}')
false
b6fe10e17b9e4aa330841cb6a82c5719d85bc2b9
AlanEstudo/Estudo-de-Python
/ex075.py
768
4.1875
4
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.No final mostre: # quantas vezes apareceu o valor 9. # Em que posição foi digitado o primeiro valor 3. # Quais foram os números pares. numeros = ( int(input('Digite um número: ')), int(input('Digite outro númeror: ')), int(input('Digite mais um número: ')), int(input('Digite o último número: ')) ) print(f'Você digitou os valores{numeros}') print(f'O numero 9 apareceu {numeros.count(9)} vezes') if 3 in numeros: print(f'O valor 3 apareceu na {numeros.index(3)+1}º posição') else: print('O vaor 3 não foi digitado em nenhuma posição') print('Os valores pares digitados foram ',end=' ') for c in numeros: if c % 2 == 0: print(c)
false
50558d02725abf9c04eff5efe7806cca7510bfc2
ukrduino/PythonElementary
/Lesson02/Exercise2a1.py
553
4.15625
4
# Write a bubble-sort function def bubble_sort(un_list): """ Bubble-sort function >>> unsorted_list = [54, 26, 93, 17, -77, 31, 44, 55, 200000] >>> bubble_sort(unsorted_list) >>> print unsorted_list [-77, 17, 26, 31, 44, 54, 55, 93, 200000] """ for pass_number in range(len(un_list) - 1, 0, -1): for i in range(pass_number): if un_list[i] > un_list[i + 1]: un_list[i], un_list[i + 1] = un_list[i + 1], un_list[i] if __name__ == "__main__": import doctest doctest.testmod()
false
9185f60dee9625d663bcecea816da0255507f7a3
ukrduino/PythonElementary
/Lesson02/Exercise2_1.py
724
4.65625
5
# Write a recursive function that computes factorial # In mathematics, the factorial of a non-negative integer n, denoted by n!, # is the product of all positive integers less than or equal to n. For example, # 5! = 5 * 4 * 3 * 2 * 1 = 120. def factorial_rec(n): """ Computing factorial using recursion >>> print factorial_rec(10) 3628800 """ if n < 2: return 1 else: return n * factorial_rec(n - 1) def factorial_loop(n): """ Computing factorial using loop >>> print factorial_loop(10) 3628800 """ fact = 1 for i in range(2, n + 1): fact *= i return fact if __name__ == "__main__": import doctest doctest.testmod()
true
a273d9b05d584d3818c2cfbd2a020d11c8d927f9
rootzilopochtli/python-notes
/programming_in_python/classes.py
1,205
4.1875
4
# 15. Classes # class class Car: def __init__(self,name,gear,miles): self.name = name self.gear = gear self.miles = miles def drive(self,miles): self.miles = self.miles + miles def shift_gear(self,gear): self.gear = gear car = Car("Tesla", 0, 0) car.shift_gear(6) del car #print(car.gear) # object oriented programming # inheritence # employee # common class is called the parent class Employee: def __init__(self, name, age, dob, job_description): self.name = name self.age = age self.dob = dob self.job_description = job_description def get_salary(self): print("salary printend") # child class class Manager(Employee): def __init__(self, name, age, dob, job_description, department, employees): super().__init__(name, age, dob, job_description) self.department = department self.employees = employees def add_employee(self): print("adding employee") def get_salary(self): print("salary printend for manager") manager = Manager("kim", 28, "23-8-2000", "manages everything", "engineering department", 87) manager.get_salary() manager.add_employee()
false
4c289536721da7f0aacf1d7a09483102add0d98d
rootzilopochtli/python-notes
/programming_in_python/comparison_operators.py
590
4.125
4
# 10. Comparison operators # compare n1 = 5 n2 = 10 # greater than n1_gt_n2 = n1 > n2 # return a boolean #print(n1_gt_n2) # less than n1_lt_n2 = n1 < n2 #print(n1_lt_n2) #print(83 < 120) # greater than eqal #print(n1 >= n2) #print(99 >= 99) # less than eqal #print(5 <= 5) # not eqal to #print( 5 != 9 ) # eqal to #print(n1 == 5) password = input("password: ") # 123456 = correct correct_pass = "123456" #if password == correct_pass: if len(password) >= 6 : #print("correct password") print("nice length") else : #print("incorrect password") print("to short password")
false
ec90fa2fe745ef77be5573534260e1261f3a0d87
Anku-0101/Python_Complete
/String/03_StringFunction.py
329
4.15625
4
story = "once upon a time there lived a guy named ABC he was very intelliget and motivated, he has plenty of things to do" # String Function print(len(story)) print(story.endswith("Notes")) print(story.count("he")) print(story.count('a')) print(story.capitalize()) print(story.find("ABC")) print(story.replace("ABC", "PQR"))
true