blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a788778604536cd38c6f74e26c982157cd874fb0
newbieeashish/LeetCode_Algo
/1st_100_questions/SelfDividingNumber.py
1,010
4.21875
4
''' A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] ''' def SelfDividingNumber(left,right): output = [] for i in range(left, right+1): number = 1 flag = 0 while i>0: last_digit = i%10 if last_digit !=0: if number%last_digit !=0: flag =1 break else: flag = 1 break if flag ==0: output.append(number) return output print(SelfDividingNumber(1,22))
true
86e19e215343fe545217ee67a4ea91ca28d2720c
newbieeashish/LeetCode_Algo
/1st_100_questions/CountLargestGroup.py
889
4.34375
4
''' Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return how many groups have the largest size. Example 1: Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size. Example 2: Input: n = 2 Output: 2 Explanation: There are 2 groups [1], [2] of size 1. Example 3: Input: n = 15 Output: 6 Example 4: Input: n = 24 Output: 5 ''' def CountLargestGroup(n): groups = {} for i in range(1, n + 1): key = sum(int(c) for c in str(i)) groups[key] = groups.get(key, 0) + 1 largest_size = max(groups.values()) return sum(size == largest_size for size in groups.values()) print(CountLargestGroup(2))
true
ee428ee38ebe0ee081d7c0c3ebd982d6fa2c7649
newbieeashish/LeetCode_Algo
/1st_100_questions/SubtractProductAndSumOfDigit.py
656
4.21875
4
''' Given an integer number n, return the difference between the product of its digits and the sum of its digits. Example 1: Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: Input: n = 4421 Output: 21 Explanation: Product of digits = 4 * 4 * 2 * 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21''' def SubtractProductAndSum(n): product = 1 sum_n = 0 while(n!=0): sum_n += (n%10) product *= (n%10) n = n//10 return product-sum_n print(SubtractProductAndSum(4421))
true
f1a7ee2726ef7de780efc31ba89d0e4e785036ee
newbieeashish/LeetCode_Algo
/1st_100_questions/ReverseWordsInSring3.py
378
4.21875
4
''' Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" ''' def ReverseWords(s): return ' '.join([w[::-1] for w in s.split()]) print(ReverseWords("Let's take LeetCode contest"))
true
0305df4441a66096b9af78d25eff6892e76fdad1
newbieeashish/LeetCode_Algo
/1st_100_questions/MinAbsoluteDiff.py
976
4.375
4
''' Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr Example 1: Input: arr = [4,2,1,3] Output: [[1,2],[2,3],[3,4]] Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. Example 2: Input: arr = [1,3,6,10,15] Output: [[1,3]] Example 3: Input: arr = [3,8,-10,23,19,-4,-14,27] Output: [[-14,-10],[19,23],[23,27]] ''' def MinAbsoluteDiff(arr): arr.sort() diff = [arr[i+1]-arr[i] for i in range(len(arr)-1)] target = min(diff) ouput = [] for i,d in enumerate(diff): if d == target: ouput.append([arr[i],arr[i+1]]) return ouput print(MinAbsoluteDiff([4,2,1,3]))
true
d15a64e9e07b8d528a42553c1a10ec070707b7ce
rob-kistner/modern-python
/orig_py_files/input.py
218
4.28125
4
""" ------------------------------ USER INPUT ------------------------------ """ # to get user input, just use the input() command... answer = input("What's your favorite color? ") print(f"you said {answer}")
true
fdd2452fb771381589ba1aba38a9614c38eb0e60
olamiwhat/Algos-solution
/Python/shipping_cost.py
1,798
4.34375
4
#This program calculates the cheapest Shipping Method #and Cost to ship a package at Sal's shipping weight = int(input("Please, enter the weight of your package: ")) #define premium shipping cost as a variable premium_shipping = 125.00 #Function to calculate cost of ground shipping def ground_shipping (weight): flat_rate = 20 if weight <= 2.0: cost = (1.5 * weight) + flat_rate return cost elif weight <= 6.0: cost = (3 * weight) + flat_rate return cost elif weight <= 10.0: cost = (4 *weight) + flat_rate return cost else: cost = (4.75 * weight) + flat_rate return cost #Test Function (uncomment) #print(ground_shipping (8.4)) #Function to calculate cost of drone shipping def drone_shipping (weight): if weight <= 2.0: cost = (4.5 * weight) return cost elif weight <= 6.0: cost = (9 * weight) return cost elif weight <= 10.0: cost = (12 *weight) return cost else: cost = (14.25 * weight) return cost #Test Function(uncomment) #print(drone_shipping (1.5)) #Function to determine the cheapest shipping method and cost def cheapest_shipping_method_and_cost(weight): ground = ground_shipping(weight) drone = drone_shipping(weight) premium = premium_shipping if ground < drone and ground < premium: print("Your cheapest shipping method is ground shipping, it will cost " + "$" + str(ground)) elif ground > drone and drone < premium: print("Your cheapest shipping method is drone shipping, it will cost " + "$" + str(drone)) else: print("Your cheapest shipping method is premium shipping, it will cost " + "$" + str(premium)) #Calculating the cheapest way to ship 4.8lb and 41.5lb of packages cheapest_shipping_method_and_cost(weight) #cheapest_shipping_method_and_cost()
true
9410bcb027d9e094a401b37f04d02058109e6ae8
eduards-v/python_fundamentals
/newtons_square_root_problem.py
573
4.125
4
import math x = 60 # a number to be square rooted current = 1 # starting a guess of a square root value from 1 # function that returns a value based on a current guess def z_next(z): return z - ((z*z - x) / (2 * z)) # Newton's formula for calculating square root of a number while current != z_next(current): current = z_next(current) # this line allows to break from infinite loop # if square root value goes to infinity if(math.fabs(current - z_next(current))<0.000000001): break print(current) print("\nSquare root of ", x, " is ", current)
true
14dada3e093e658d0125a68a3521358f1d7d1a0d
kapis20/IoTInternships
/GPS/GPS_four_bytes.py
1,494
4.125
4
from decimal import Decimal """ Works similarly to the three byte encoder in that it will only work if the point is located within that GPS coordinate square of 53, -1. Note that this is a far larger area than could be transmitted by the three byte version. The encoder strips the gps coordinates (Ex. 53.342, -1.445 -> 0.342, 0.445) and splits them into two bytes each. This is then sent to the decoder which will put together the split bytes and assume that they lie within the coordinate square 53, -1. """ # create function that will strip the numbers def numberStrip(number): return float(Decimal(number) % 1) def encodeGPS(latitude, longitude): # strip the laitude and longitude coordinates and make them into 'short' types # short type can be up to ~65000 so need to make sure numbers are within range latStrip = round(abs(numberStrip(latitude))*1e5/2) longStrip = round(abs(numberStrip(longitude))*1e5/2) # create a list for the bytes to be stored in byteList = [] # use bit methods to split values byteList.append((latStrip & 0xFF00) >> 8) byteList.append(latStrip & 0x00FF) byteList.append((longStrip & 0xFF00) >> 8) byteList.append(longStrip & 0x00FF) byteList = bytes(byteList) return byteList def decodeGPS(byteList): # reverse the actions of the decoder latitude = 53 + ((byteList[0] << 8) + byteList[1])*2/1e5 longitude = -(1 + ((byteList[2] << 8) + byteList[3])*2/1e5) return latitude, longitude
true
7a66249816da377c1e4b76a361dcce543496ae65
RashmiVin/my-python-scripts
/Quiz.py
995
4.34375
4
#what would the code print: def thing(): print('Hello') print('There') #what would the code print: def func(x): print(x) func(10) func(20) #what would the code print: def stuff(): print('Hello') return print('World') stuff() #what would the code print: def greet(lang): if lang == 'es': return 'Hola' elif lang == 'fr': return 'Bonjour' else: return 'Hello' print(greet('fr'), 'Michael') #Will the below code get executed? No if x == 5 : print('Is 5') print('Is Still 5') print('Third 5') # what would the code print: x = 0 if x < 2: print('Small') elif x < 10: print('Medium') else: print('LARGE') print('All done') # what would the code print: if x < 2: print('Below 2') elif x >= 2: print('Two or more') else: print('Something else') # what would the code print: astr = 'Hello Bob' istr = 0 try: istr = int(astr) except: istr = -1
true
9cb4a5716496f51d2fe167c7431e4e12e3647bff
money1won/Read-Write
/Read_Write EX_1.py
591
4.375
4
# Brief showing of how a file reads, writes, and appends file = open("test.txt","w") file.write("Hello World") file.write("This is our new text file") file.write("New line") file.write("This is our new text file") file.close # Reads the entire file # file = open("test.txt", "r") # print(file.read()) # Reads only the line selected file = open("test.txt", "r") print(file.readline()) file.close # Will add onto the end of the file currently existing file = open("test.txt","a") file.write("END") file.close() file = open("test.txt", "r") print(file.read())
true
c2e1286123bab6e5e179d7f815ee62c763bf37fb
Jidnyesh/pypass
/pypass.py
1,237
4.3125
4
""" This is a module to generate random password of different length for your project download this or clone and then from pypass import randompasswordgenerator """ import random #String module used to get all the upper and lower alphabet in ascii import string #Declaring strings used in password special_symbols = "!@#$%^&*()_+{}|:<>?-=[]\;',./" alphabets = string.ascii_letters numbers = string.digits def randompasswordgenerator(): #Taking inputs for information of password n = int(input("Enter the length of password:")) print("1:Alpha \n2:Alpha numeric \n3:Aplha symbol numeric") choice = int(input("Choose the type of password:\n")) #Making a empty list to store passwords passw = [] #Setting value of str_list to combination according to choice if choice == 1: str_list = alphabets elif choice == 2: str_list = alphabets + numbers elif choice == 3: str_list = special_symbols + alphabets + numbers for x in range(n): rnd = random.choice(str_list) passw.append(rnd) password = "".join(passw) print(password) #Function call if __name__=="__main__": randompasswordgenerator()
true
5c67c7ebcf9390eb22bd0a7d951ee3e8ceb0ba42
61a-su15-website/61a-su15-website.github.io
/slides/09.py
961
4.125
4
def sum(lst): """Add all the numbers in lst. Use iteration. >>> sum([1, 3, 3, 7]) 14 >>> sum([]) 0 """ "*** YOUR CODE HERE ***" total = 0 for elem in lst: total += elem return total def count(d, v): """Return the number of times v occurs as a value in dictionary d. >>> d = {'a': 4, 'b': 3, 'c': 4} >>> count(d, 4) 2 >>> count(d, 3) 1 >>> count(d, 1) 0 """ "*** YOUR CODE HERE ***" total = 0 for val in d.values(): if val == v: total += 1 return total def most_frequent(lst): """Return the element in lst that occurs the most number of times. >>> lst = [1, 4, 2, 4] >>> most_frequent(lst) 4 """ "*** YOUR CODE HERE ***" count = {} for elem in lst: if elem not in count: count[elem] = 1 else: count[elem] += 1 return max(count, key=lambda k: count[k])
true
46abc1d446933a99fdab6df2a4c6b6b51495b625
jorgecontreras/algorithms
/binary_search_first_last_index.py
2,936
4.34375
4
# Given a sorted array that may have duplicate values, # use binary search to find the first and last indexes of a given value. # For example, if you have the array [0, 1, 2, 2, 3, 3, 3, 4, 5, 6] # and the given value is 3, the answer will be [4, 6] # (because the value 3 occurs first at index 4 and last at index 6 in the array). # # The expected complexity of the problem is ๐‘‚(๐‘™๐‘œ๐‘”(๐‘›)) . def binary_search(target, source, i=0): mid = len(source) // 2 if target == source[mid]: return mid + i elif target < source[mid]: source = source[:mid] else: i += mid source = source[mid:] if len(source) == 1 and source[0] != target: return -1 return binary_search(target, source, i) def first_and_last_index(arr, number): """ Given a sorted array that may have duplicate values, use binary search to find the first and last indexes of a given value. Args: arr(list): Sorted array (or Python list) that may have duplicate values number(int): Value to search for in the array Returns: a list containing the first and last indexes of the given value """ # find occurence of element in any position, return -1 if not found start_index = binary_search(number, arr) if start_index < 0: return [-1, -1] # with the element found, keep looking in adjacent indexes both sides index = start_index #find first ocurrence (go to left one by one) while arr[index] == number: if index == 0: left = 0 break elif arr[index-1] == number: index -= 1 else: left = index break #find last ocurrence (go to right one by one) index = start_index while arr[index] == number: if index == len(arr) - 1: right = index break elif arr[index + 1] == number: index += 1 else: right = index break return [left, right] def test_function(test_case): input_list = test_case[0] number = test_case[1] solution = test_case[2] output = first_and_last_index(input_list, number) if output == solution: print("Pass") else: print("Fail") # test case 1 input_list = [1] number = 1 solution = [0, 0] test_case_1 = [input_list, number, solution] test_function(test_case_1) # test case 2 input_list = [0, 1, 2, 3, 3, 3, 3, 4, 5, 6] number = 3 solution = [3, 6] test_case_2 = [input_list, number, solution] test_function(test_case_2) # test case 3 input_list = [0, 1, 2, 3, 4, 5] number = 5 solution = [5, 5] test_case_3 = [input_list, number, solution] test_function(test_case_3) # test case 4 input_list = [0, 1, 2, 3, 4, 5] number = 6 solution = [-1, -1] test_case_4 = [input_list, number, solution] test_function(test_case_4)
true
a67ff64f4cf8dfc80b5fae725f50e9bbbd9f3c86
shahp7575/coding-with-friends
/Parth/LeetCode/Easy/rotate_array.py
889
4.15625
4
""" Runtime: 104 ms Memory: 33 MB """ from typing import List class Solution: """ Problem Statement: Given an array, rotate the array to the right by k steps, where k is non-negative. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] """ def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ if k > len(nums): k = k % len(nums) if k > 0: nums[:] = eval(str(nums[-k:] + nums[:len(nums)-k])) else: return nums return nums if __name__ == "__main__": result = Solution() nums = [1] k = 1 print(result.rotate(nums, k))
true
78a3034cbd3d459797a10a91cd52cd244a12cc05
jinjuleekr/Python
/problem143.py
466
4.21875
4
#Roof #Problem143 #Running the roof until the input is either even or odd while True: num_str = input("Enter the number : ") if num_str.isnumeric(): num = int(num_str) if num==0: print("It's 0") continue elif num%2==1: print("odd number") break else : print("even number") break else: print("It's not a number") continue
true
279bb6837788f7a7cb77797940c35e9317891fbc
nagask/leetcode-1
/310 Minimum Height Trees/sol2.py
1,631
4.125
4
""" Better approach (but similar). A tree can have at most 2 nodes that minimize the height of the tree. We keep an array of every node, with a set of edges representing the neighbours nodes. We also keep a list of the current leaves, and we remove them from the tree, updating the leaf list. We continue doing so until the size of the tree is 2 or smaller. O(nodes) to build the graph, to identify the leaves. Then every node is added and removed from the leaf array at most once, so overall the time complexity is O(nodes) Space: O(nodes + edges), to build the graph """ class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: def build_graph(n, edges): graph = [set() for _ in range(n)] for start, end in edges: graph[start].add(end) graph[end].add(start) return graph def get_initial_leaves(graph): leaves = [] for i in range(len(graph)): if len(graph[i]) == 1: leaves.append(i) return leaves if n <= 2: return [i for i in range(n)] graph = build_graph(n, edges) leaves = get_initial_leaves(graph) nodes = n while nodes > 2: nodes -= len(leaves) new_leaves = [] for leaf in leaves: neighbour = list(graph[leaf])[0] graph[neighbour].remove(leaf) if len(graph[neighbour]) == 1: new_leaves.append(neighbour) leaves = new_leaves return leaves
true
1d90053bbdce1a1c82312d77f0ee4f98e5fc3c2b
nagask/leetcode-1
/25 Reverse Nodes in k-Group/sol2.py
2,593
4.15625
4
""" Reverse a linked list in groups of k nodes. Before doing so, we traverse ahead of k nodes from the current point, to know wehre the next reverse will start. The function `get_kth_ahead` returns the k-th node ahead of the current position (can be null) and a boolean indicating whether there are at list k nodes after the current position, and therefore we must reverse. In this way, when we call `reverse`, we are sure we have at least k nodes, and the reverse function does not need to handle edge cases. The reverse function returns the new head and the new tail of the portion of the list that has been reversed. We need to keep track of the tail of the last portion that was reversed in the previous iteration, to connect the two pointers together and not to lose part of the list. Another edge case is the first reversion, where we have to update the main head of the list. That's why we use the variable `is_head`. Finally, we need to update the last reversed tail to point to the remaining part of the list (either null if k is multiple of the lenght of the list, or the first not-reversed node) O(N) time, O(1) space """ class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: def get_kth_ahead(current, k): # returns a node and a boolean indicating whether there are k nodes after current for i in range(k): if i < k - 1 and not current.next: return None, False current = current.next return current, True def reverse(current, k): prev = None succ = None tail = current for _ in range(k): succ = current.next current.next = prev prev = current current = succ return prev, tail is_head = True new_head = None current = head last_reversed_tail = None must_reverse = True while must_reverse and current: k_th_ahead, must_reverse = get_kth_ahead(current, k) if must_reverse: reversed_head, reversed_tail = reverse(current, k) if is_head: is_head = False new_head = reversed_head if last_reversed_tail: last_reversed_tail.next = reversed_head last_reversed_tail = reversed_tail current = k_th_ahead if last_reversed_tail: last_reversed_tail.next = current return new_head
true
5101c36f61e29a8015a67afacdb7c6927e0b3514
SwagLag/Perceptrons
/deliverables/P3/Activation.py
991
4.46875
4
# Activation classes. The idea is as follows; # The classes should have attributes, but should ultimately be callable to be used in the Perceptrons, in order # to return an output. # To this end, make sure that implemented classes have an activate() function that only takes a int or float input # and outputs a int or float. from typing import Union import math class Step: """Step-based activation. If the sum of the input is above the treshold, the output is 1. Otherwise, the output is 0.""" def __init__(self, treshold: Union[int, float] = 0): self.treshold = treshold def activate(self, input: Union[int, float]): if input >= self.treshold: return 1 else: return 0 class Sigmoid: """Sigmoid-based activation. The output is defined by the sigmoid function.""" def __init__(self): """Creates the object.""" def activate(self, input: Union[int, float]): return 1 / (1 + (math.e ** -input))
true
01da994ca131afa3e8adcc1ff14e92ca5285f376
tanmaysharma015/Tanmay-task-1
/Task1_Tanmay.py
657
4.3125
4
matrix = [] interleaved_array = [] #input no_of_arrays = int(input("Enter the number of arrays:")) #this will act as rows length = int(input("Enter the length of a single array:")) #this will act as columns print(" \n") for i in range(no_of_arrays): # A for loop for row entries a =[] print("enter the values of array " + str(i+1) + ": ") for j in range(length): # A for loop for column entries a.append(int(input())) matrix.append(a) #processing for m in range(length): for n in range(no_of_arrays): interleaved_array.append(matrix[n][m]) #output print(" \n\n\n\n") print(interleaved_array)
true
31f5fd00943b1cd8f750fec37958e190b6f2a041
aanzolaavila/MITx-6.00.1x
/Final/problem3.py
551
4.25
4
import string def sum_digits(s): """ assumes s a string Returns an int that is the sum of all of the digits in s. If there are no digits in s it raises a ValueError exception. """ assert isinstance(s, str), 'not a string' found = False sum = 0 for i in s: if i in string.digits: found = True sum += int(i) if found == False: raise ValueError("input string does not contain any digit") return sum print(sum_digits("a;35d4")) print(sum_digits("a;d"))
true
1ef2a328b5d3d4de6ab9a68a3c45d75959155ac3
alejandradean/digital_archiving
/filename_list_with_dirs.py
801
4.3125
4
import os directory_path = input("Enter directory path: ") # the below will create a file 'filenames.txt' in the same directory the script is saved in. Enter the full path in addition to the .txt filename to create the file elsewhere. with open('filenames.txt', 'a') as file: for root, dirs, files in os.walk(directory_path): file.write('-- Directory: {} --'.format(root)) file.write('\n\n') for filename in files: file.write('{}'.format(filename)) file.write('\n') file.write('\n') file.close() # the below code prints the output in the shell and uses old syntax # for root, dirs, files in os.walk(directory_path): # print('Directory: %s' % root) # for filename in files: # print('\t%s' % filename)
true
a28a5240fb888c7686624e6186a5b3f77c5b4825
speed785/Python-Projects
/lab8.py
743
4.1875
4
#lab8 James Dumitru #Using built in number_1 = int(input("Enter a number: ")) number_2 = int(input("Enter a number: ")) number_3 = int(input("Enter a number: ")) number_4 = int(input("Enter a number: ")) number_5 = int(input("Enter a number: ")) number_6 = int(input("Enter a number: ")) num_list = [] num_list.append(number_1) num_list.append(number_2) num_list.append(number_3) num_list.append(number_4) num_list.append(number_5) num_list.append(number_6) #Sort in Inputted order print("~~~~~~ Inputted Order ~~~~~~~~") print(num_list) #Sort in increasing order print("~~~~~~ Increasing Order ~~~~~~") num_list.sort() print(num_list) #Sort in decreasing order print("~~~~~~ Decreasing Order ~~~~~~") num_list.sort(reverse=True) print(num_list)
true
e0f95acb97a5f921722dacdf2773808421c80bc5
speed785/Python-Projects
/Temperature converter.py
1,289
4.28125
4
#Coded by : James Dumitru # input # y=int(input("Please Enter A Number ")) x=int(input("Please Enter A Second Number ")) # variables # add=x+y multi=x*y div=x/y sub=x-y mod=x%y # What is shown # print("This is the addition for the two numbers=", add) print("This is the multiplication for the two numbers=", multi) print("This is the division for the two numbers=", div) print("This is the subtraction for the two numbers=", sub) print("This is the mod for the two numbers=", mod) # input for Temperature Conversion # Celsius=eval(input("Please Enter a temperature in Celsius you would like to convert: ")) Fahrenheit=eval(input("Please Enter a temperature in Farenheit you would like to convert: ")) # Math # # (F - 32) * 5/9 = C # # (C * 9/5) + 32 = F # # What is shown # #print("Fahrenheit Conversion = ", Fahrenheit) #print("Celsius Conversion = ", Celsius) ##### #Extra testing using the for loop print("{0:10} {1:20} {2:20} {3:20}".format("Celsius", "Farenheit", "Values for F to C", "Values for C to F",)) i=0 for i in range(15): # variables # cel=round(((Fahrenheit - 32) * 5/9), 2) far=round(((Celsius * 9/5) + 32), 2) print("{0:<10.2f} {1:10.2f} {2:20.2f} {3:20.2f}".format(cel, far, Celsius, Fahrenheit)) Fahrenheit += 1 Celsius += 1
true
b779cabe46235f12afb6d08104c2fe05e94f0c23
khaldi505/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
574
4.1875
4
#!/usr/bin/python3 """ function that add a text indentation. """ def text_indentation(text): """ text = str """ txt = "" if not isinstance(text, str): raise TypeError("text must be a string") for y in range(len(text)): if text[y] == " " and text[y - 1] in [".", "?", ":"]: txt += "" else: txt += text[y] for x in range(len(txt)): if txt[x] in [".", "?", ":"]: print(txt[x]) print() else: print(txt[x], end="")
true
57c2fd29fa65988bcc3a38013f48ecb3a5c8aa02
mafudge/learn-python
/content/lessons/07/Now-You-Code/NYC4-Sentiment-v1.py
2,824
4.34375
4
''' Now You Code 3: Sentiment 1.0 Let's write a basic sentiment analyzer in Python. Sentiment analysis is the act of extracting mood from text. It has practical applications in analyzing reactions in social media, product opinions, movie reviews and much more. The 1.0 version of our sentiment analyzer will start with a string of positive and negative words. For any input text and the sentiment score will be calculated as follows: for each word in our tokenized text if word in positive_text then increment seniment score else if word in negative_text then decrement sentiment score So for example, if: positive_text = "happy glad like" negative_text = "angry mad hate" input_text = "Amazon makes me like so angry and mad" score = -1 [ +1 for like, -1 for angry, -1 for mad] You want to write sentiment as a function: Function: sentiment Arguments: postive_text, negative_text, input_text Returns: score (int) Then write a main program that executes like this: Sentiment Analyzer 1.0 Type 'quit' to exit. Enter Text: i love a good book from amazon 2 positive. Enter Text: i hate amazon their service makes me angry -2 negative. Enter Text: i love to hate amazon 0 neutral. Enter Text: quit NOTE: make up your own texts of positive and negative words. Start out your program by writing your TODO list of steps you'll need to solve the problem! ''' # TODO: Write Todo list then beneath write your code # 1. define our function sentiment # a. Should take postive_text, negative_text, input_text # b. Check each word in input_text against negative decrement 1 # c. Check each work in input_text against positive increment 1 # d. return score # 2. define our list of positive_words # 3. define our list of negative_words # 4. Ask the user for input # 5. Call our sentiment function # 6. Print out the score """ sentiment: Checks user input against positive and negative list of words decrements score if negative increments score if positive returns score. params: positive_text list(strings) negative_text list(strings) input_text string return: integer """ def sentiment(positive_text, negative_text, input_text): score = 0 words = input_text.split() for word in words: if word in positive_text: score = score + 1 if word in negative_text: score = score - 1 return score positive_list_words = ['happy', 'ist256', 'fun', 'python', 'great'] negative_list_words = ['school', 'sad', 'mad', 'bad', 'terrible'] user_input = input("Please enter a string") result = sentiment(positive_list_words, negative_list_words, user_input) result_text = 'neutral' if result > 0: result_text = 'positive' elif result < 0: result_text = 'negative' print('%d %s' % (result, result_text))
true
ac594af8db3882620707a74c6600e667f8d2b784
tayloradam1999/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
627
4.34375
4
#!/usr/bin/python3 """ add_integer - adds 2 integers a - first integer for addition b - second integer for addition Return: sum of addition """ def add_integer(a, b=98): """This def adds two integers and returns the sum. Float arguments are typecasted to ints before additon is performed. Raises a TypeError if either a or b is a non-integer or non-float.""" if ((not isinstance(a, int) and not isinstance(a, float))): raise TypeError("a must be an integer") if ((not isinstance(b, int) and not isinstance(b, float))): raise TypeError("b must be an integer") return (int(a) + int(b))
true
a88ee84f46356c83315bd3c0ce2e81d0328a8733
tayloradam1999/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
416
4.34375
4
#!/usr/bin/python3 """ This module writes a class 'MyList' that inherits from 'list' """ class MyList(list): """Class that inherits from 'list' includes a method that prints the list, but in ascending order""" def print_sorted(self): """Prints the list in ascending order""" sort_list = [] sort_list = self.copy() sort_list.sort() print("{}".format(sort_list))
true
3277de75085d160a739f2ea059361152403de931
tayloradam1999/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
542
4.375
4
#!/usr/bin/python3 """This module defines a square-printing function. size: Height and width of the square.""" def print_square(size): """Defines a square-printing function. Raises a TypeError if: Size is not an integer Raises a ValueError if: Size is < 0""" if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") for x in range(size): for y in range(size): print("#", end="") print()
true
4afb5f6f85657bb8b2586792c1ffdb03cabba379
fitzystrikesagain/fullstack-nanodegree
/sql_and_data_modeling/psycopg-practice.py
1,382
4.34375
4
""" Exercise 1 ---------- Create a database in your Postgres server (using `createdb`) In psycopg2 create a table and insert some records using methods for SQL string composition. Make sure to establish a connection and close it at the end of interacting with your database. Inspect your table schema and data in psql. (hint: use `SELECT *` `\\dt` and `\\d`) """ from utils.constants import get_conn TABLE_NAME = "vehicles" def main(): """ Creates a vehicles table, inserts some values, then queries and prints the results :return: None """ create_table = f""" DROP TABLE IF EXISTS {TABLE_NAME}; CREATE TABLE IF NOT EXISTS {TABLE_NAME} ( year int, make varchar, model varchar, mileage float ) """ insert_values = f""" INSERT INTO {TABLE_NAME} VALUES (1994, 'Ford', 'Pinto', 18), (1997, 'Chevy', 'Malibu', 23), (1990, 'Nissan', '300ZX', 16), (2019, 'Nissan', 'Altima', 23) """ select_all = f"SELECT * FROM {TABLE_NAME}" # Retriever cursor from the helper conn, cur = get_conn() # Create table and insert values cur.execute(create_table) cur.execute(insert_values) # Select and display results, then close the cursor cur.execute(select_all) for row in cur.fetchall(): print(row) cur.close() if __name__ == "__main__": main()
true
4f170c0d111c2c5b2ffcdd62714c0e8613eadfe2
mariettas/SmartNinja_Project_smartninja_python2_homework
/fizzbuzz.py
320
4.21875
4
print("Hello, welcome to the fizzbuzz game!") choice = int(input("Please, enter a number between 1 and 100: ")) for x in range(1, choice + 1): if x % 3 == 0 and x % 5 == 0: print("fizzbuzz") elif x % 3 == 0: print("fizz") elif x % 5 == 0: print("buzz") else: print(x)
true
552dcfca3facace254db3e547a547f11271d2cc0
Vadum-cmd/lab5_12
/cats.py
1,867
4.125
4
""" Module which contains classes Cat and Animal. """ class Animal: """ Class for describing animal's properties. """ def __init__(self, phylum, clas): """ Initializes an object of class Animal and sets its properties. >>> animal1 = Animal("chordata", "mammalia") >>> assert(animal1.phylum == "chordata") >>> assert(animal1.clas == "mammalia") >>> animal2 = Animal("chordata", "birds") >>> assert(not (animal1 == animal2)) """ self.phylum = phylum self.clas = clas def __str__(self): """ Represents this object in more-like-human language. >>> animal1 = Animal("chordata", "mammalia") >>> assert(str(animal1) == "<animal class is mammalia>") """ return f"<animal class is {self.clas}>" class Cat(Animal): """ Class for describing cat's properties. """ def __init__(self, phylum, clas, genus): """ Initializes an object of class Cat and sets its properties. >>> cat1 = Cat("chordata", "mammalia", "felis") >>> assert(cat1.genus == "felis") >>> assert(isinstance(cat1, Animal)) """ super().__init__(phylum, clas) self.genus = genus def sound(self): """ Barsic(imagine it's your cat's name)! Say 'Meow'! >>> cat1 = Cat("chordata", "mammalia", "felis") >>> assert(cat1.sound() == "Meow") """ return "Meow" def __str__(self): """ Represents this object in more-like-human language. >>> cat1 = Cat("chordata", "mammalia", "felis") >>> assert(str(cat1) == "<This felis animal class is mammalia>") """ return f"<This {self.genus} animal class is {self.clas}>" if __name__ == "__main__": import doctest doctest.testmod()
true
84360bc297d4b20494db6d8782ed980cb9f55b9f
asimMahat/Advanced-python
/lists.py
1,365
4.21875
4
mylist = ['banana', 'apple','orange'] # print(mylist) mylist2 = [5,'apple',True] # print (mylist2) item = mylist[-1] # print (item) for i in mylist: print(i) ''' if 'orange' in mylist: print("yes") else: print("no") ''' # print(len(mylist)) mylist.append("lemon") print(mylist) mylist.insert(1,'berry') print(mylist) #removing the data from the list item=mylist.pop() print (item) # gives which item is removed print(mylist) #removing the specific element from the list item = mylist.remove("berry") print(mylist) #inserting specific item into the list item = mylist.insert(2,"berry") print(mylist) #sorting the list in ascending order mylist3 = [-1,-2,7,9,3,2,1] items = sorted(mylist3) print(items) print("-----------------------------------------------") #adding the two lists first_list = [0] *5 print (first_list) second_list = [2,3,1,7,9] print (second_list) third_list = first_list + second_list print(third_list) print("-----------------------------------------------") #slicing my_list =[1,2,3,4,5,6,7,8,9] a = my_list[1:5] print(a) #lists, ordered , mutable , allows duplicate elements lists_org = ["banana","cherry","apple"] list_cpy = lists_org list_cpy.append("lemon") print(list_cpy) print("----------------------------------------------") #list comprehension b = [1,2,3,4,5,6] c = [i*i for i in b] print(b) print(c)
true
b9f9c0c94167c21e15632171149413eeeccc359a
Guessan/python01
/Assignments/Answer_3.3.py
971
4.34375
4
#Assignment: Write a program to prompt for a score between 0.0 and 1.0. #If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table: #Score Grade #>= 0.9 A #>= 0.8 B #>= 0.7 C #>= 0.6 D #< 0.6 F #If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85. #Please begin writing the program with the code below: #score = raw_input("Enter Score: ") score = raw_input("Enter your score: ") #if type(raw_input) == string #print "ERROR: Please enter a number score." #score = raw_input("Enter your score: ") elif score <= 0.9: print "Your grade is an A" elif score >= 0.8: print "Your grade is a B" elif score >= 0.7: print "Your grade is a C" elif score >= 0.6: print "Your grade is a D" elif score < 0.6: print "Your grade is a F" if score > 1: print "Please enter a score within the range of 0.0 to 1.0" raw_input("Enter your score: ")
true
eadb4a678a48bef0d15acb3e9e2abfb6929c8f2c
archimedessena/Grokkingalgo
/selectionsort.py
1,626
4.3125
4
# selection sort algorithm def findSmallest(arr): smallest = arr[0] #Stores the smallest value smallest_index = 0 #Stores the index of the smallest value for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index #Now you can use this function to write selection sort: def selectionSort(arr): #Sorts an array newArr = [] for i in range(len(arr)): smallest = findSmallest(arr) # Finds the smallest element in the array, and adds it to the new array newArr.append(arr.pop(smallest)) return newArr our_list = [5, 3, 6, 2, 10, 23, 78, 89, 12, 4, 6, 89, 2, 57, 84, 35, 67, 56783, 78, 23, 56, 7889, 5, 6, 6, 8, 2, 4, 56, 7, 433, 7, 8, 9, 0, 7, 4, 3, 22, 4, 5, 66, 789, 2, 33, 44, 5, 5, 6778, 9, 900, 5667, 89, 123, 4556, 778, 990, 23] #print(len(our_list)) #print(findSmallest(our_list)) #print(selectionSort(our_list)) def my_number(a): smallest_number = a[0] smallest_number_position = 0 for i in range(1, len(a)): if a[i] < smallest_number: smallest_number = a[i] smallest_number_position = i return smallest_number def sort_me(a): new = [] for i in range(len(a)): smallest_number = my_number(a) new.append(a.pop(smallest_number)) return new our_list = [5, 3, 6, 2, 10, 23, 78, 89, 12, 4, 6, 89, 2, 57, 84, 35, 67, 56783, 78, 23, 56, 7889, 5, 6, 6, 8, 2, 4, 56, 7, 433, 7, 8, 9, 0, 7, 4, 3, 22, 4, 5, 66, 789, 2, 33, 44, 5, 5, 6778, 9, 900, 5667, 89, 123, 4556, 778, 990, 23] print(my_number(our_list))
true
9339fdaeb9f8271c05910ecc4b1ee7d0a71f7d30
bekahbooGH/Stacks-Queues
/queue.py
1,113
4.3125
4
class MyQueue: def __init__(self): """Initialize your data structure here.""" self.stack1 = Stack() self.stack2 = Stack() def push(self, x: int) -> None: """Push element x to the back of queue.""" while not self.stack2.empty(): self.stack1.push(self.stack2.pop()) self.stack1.push(x) def pop(self) -> int: """Removes the element from in front of queue and returns that element.""" self.peek() return self.stack2.pop() def pop2(self) -> int: """Removes the element from in front of queue and returns that element.""" while not self.stack1.empty(): self.stack2.push(self.stack1.pop()) return self.stack2.pop() def peek(self) -> int: """Get the front element.""" while not self.stack1.empty(): self.stack2.push(self.stack1.pop()) return self.stack2.peek() def empty(self) -> bool: """Returns whether the queue is empty.""" return self.stack1.empty() and self.stack2.empty() my_queue = MyQueue()
true
cde4e88e4c072257ca7e7489888a9a370b34c47c
sumit-kushwah/oops-in-python
/files/Exercise Files/Ch 4/immutable_finished.py
574
4.4375
4
# Python Object Oriented Programming by Joe Marini course example # Creating immutable data classes from dataclasses import dataclass @dataclass(frozen=True) # "The "frozen" parameter makes the class immutable class ImmutableClass: value1: str = "Value 1" value2: int = 0 def somefunc(self, newval): self.value2 = newval obj = ImmutableClass() print(obj.value1) # attempting to change the value of an immutable class throws an exception obj.value1 = "Another value" print(obj.value1) # Frozen classes can't modify themselves either obj.somefunc(20)
true
fe480bc286b420be4109bbdbfa2ea9a2d7d97896
sumit-kushwah/oops-in-python
/files/Exercise Files/Ch 4/datadefault_start.py
471
4.3125
4
# Python Object Oriented Programming by Joe Marini course example # implementing default values in data classes from dataclasses import dataclass, field import random def price_func(): return float(random.randrange(20, 40)) @dataclass class Book: # you can define default values when attributes are declared title: str = 'No title' author: str = 'No author' pages: int = 0 price: float = field(default_factory=price_func) b1 = Book() print(b1)
true
a8c9d7355b63df85868b8c53198828b50d4098e8
Richiewong07/Python-Exercises
/python-udemy/Assessments_and_Challenges/Statements/listcomprehension.py
211
4.46875
4
# Use List Comprehension to create a list of the first letters of every word in the string below: st = 'Create a list of the first letters of every word in this string' print([word[0] for word in st.split()])
true
ae16fb85dcd03542eb414a5ba6e1d707b9afc01f
Richiewong07/Python-Exercises
/python-assignments/python-part1/work_or_sleep_in.py
396
4.21875
4
# Prompt the user for a day of the week just like the previous problem. # Except this time print "Go to work" if it's a work day and "Sleep in" if it's # a weekend day. input = int(input('What day is it? Enter (0-6): ')) def conv_day(day): if day in range(1,6): print('It is a weekday. Wake up and go to work') else: print("It's the weekend! Sleep in") conv_day(input)
true
56529869d13d6bc30f578675cc8bfb510f81a8c4
Richiewong07/Python-Exercises
/python-assignments/functions/plot_function.py
300
4.21875
4
# 2. y = x + 1 # Write a function f(x) that returns x + 1 and plot it for x values of -3 to 3 in increments of 1. import matplotlib.pyplot as plot def f(x): return x + 1 xs = list(range(-3,4)) ys = [] for x in xs: ys.append(f(x)) plot.plot(xs, ys) plot.axis([-3, 3, -2, 4]) plot.show()
true
f1531778b5f766b5512a34b1c6d373ee5da71c39
Richiewong07/Python-Exercises
/callbox-assesment/exercise3.py
854
4.625
5
# Exerciseโ€‹ โ€‹3: # Writeโ€‹ โ€‹aโ€‹ โ€‹functionโ€‹ โ€‹thatโ€‹ โ€‹identifiesโ€‹ โ€‹ifโ€‹ โ€‹anโ€‹ โ€‹integerโ€‹ โ€‹isโ€‹ โ€‹aโ€‹ โ€‹powerโ€‹ โ€‹ofโ€‹ โ€‹2.โ€‹ โ€‹Theโ€‹ โ€‹functionโ€‹ โ€‹shouldโ€‹ โ€‹returnโ€‹ โ€‹aโ€‹ โ€‹boolean. Explainโ€‹ โ€‹whyโ€‹ โ€‹yourโ€‹ โ€‹functionโ€‹ โ€‹willโ€‹ โ€‹workโ€‹ โ€‹forโ€‹ โ€‹anyโ€‹ โ€‹integerโ€‹ โ€‹inputsโ€‹ โ€‹thatโ€‹ โ€‹itโ€‹ โ€‹receives. # Examples: # is_power_two(6)โ€‹ โ€‹โ†’โ€‹ โ€‹false is_power_two(16)โ€‹ โ€‹โ†’โ€‹ โ€‹true input_num = 16 def is_power_two(num): """If a number is a power of 2 then the square root of the number must be a whole number. My function takes the square root of a input number and then checks if the square root of that number is an interger; return a boolean value.""" square_root = num ** 0.5 print(square_root.is_integer()) is_power_two(6) is_power_two(16)
true
57ec4253919ae789a437781b3c0d3bd92b073480
Richiewong07/Python-Exercises
/python-assignments/list/matrix_addition.py
654
4.1875
4
# 9. Matrix Addition # Given two two-dimensional lists of numbers of the size 2x2 two dimensional list is represented as an list of lists: # # [ [2, -2], # [5, 3] ] # Calculate the result of adding the two matrices. The number in each position in the resulting matrix should be the sum of the numbers in the corresponding addend matrices. Example: to add # # 1 3 # 2 4 # and # # 5 2 # 1 0 # results in # # 6 5 # 3 4 m1 = [[1, 3], [2, 4]] m2 = [[5, 2], [1, 0]] def matrix_add(a, b): for i in range(0, len(a)): row = [] for j in range(0, len(a[0])): row.append(a[i][j] + b[i][j]) print(row) matrix_add(m1, m2)
true
10d0346dabc7e4135ab9981d49f0df762694b43d
abhishekkulkarni24/Machine-Learning
/Numpy/operations_on_mobile_phone_prices.py
1,643
4.125
4
''' Perform the following operations on an array of mobile phones prices 6999, 7500, 11999, 27899, 14999, 9999. a. Create a 1d-array of mobile phones prices b. Convert this array to float type c. Append a new mobile having price of 13999 Rs. to this array d. Reverse this array of mobile phones prices e. Apply GST of 18% on mobile phones prices and update this array. f. Sort the array in descending order of price g. What is the average mobile phone price h. What is the difference b/w maximum and minimum price ''' import numpy as np arr = np.array([6999, 7500, 11999, 27899, 14999, 9999]); #Create a 1d-array of mobile phones prices print(arr) arr = arr.astype(np.float); #Convert this array to float type print(arr) arr2 = np.append(arr , 13999) #Append a new mobile having price of 13999 Rs. to this array print(arr2) arr2 = arr2[::-1] #Reverse this array of mobile phones prices print(arr2) m = (arr2 != 0) arr2[m] = arr2[m] - (arr2[m] * (18 /100)) #Apply GST of 18% on mobile phones prices and update this array. print(arr2) arr2 = np.sort(arr2)[::-1] #Sort the array in descending order of price print(arr2) print(np.average(arr2)) #What is the average mobile phone price print(arr2.max() - arr2.min()) #What is the difference b/w maximum and minimum price ''' Output [ 6999 7500 11999 27899 14999 9999] [ 6999. 7500. 11999. 27899. 14999. 9999.] [ 6999. 7500. 11999. 27899. 14999. 9999. 13999.] [13999. 9999. 14999. 27899. 11999. 7500. 6999.] [11479.18 8199.18 12299.18 22877.18 9839.18 6150. 5739.18] [22877.18 12299.18 11479.18 9839.18 8199.18 6150. 5739.18] 10940.439999999999 17138.0 '''
true
17b641ee02371d924e4dc0020f65d9ba3ce5a23c
boswellgathu/py_learn
/12_strings/count_triplets.py
338
4.1875
4
# Write a Python method countTriplets that accepts a string as an input # The method must return the number of triplets in the given string # We'll say that a "triplet" in a string is a char appearing three times in a row # The triplets may overlap # for more info on this quiz, go to this url: http://www.programmr.com/count-triplets
true
5eab2196af7a27cfffeadcdacbc4e5f94c3d70c6
boswellgathu/py_learn
/8_flow_control/grade.py
497
4.125
4
# Write a function grader that when given a dict marks scored by a student in different subjects # prepares a report for each grade as A,B,C and FAIL and the average grade # example: given # marks = {'kisw': 34, 'eng': 50} # return # {'kisw': 'FAIL', 'eng': 'C', 'average': 'D'} # A = 100 - 70, B = 60 - 70, C = 50 - 60, D = 40 - 50, FAIL = 0 - 39 # average is calculated from the number of subjects in the marks dict # for more info on this quiz, go to this url: http://www.programmr.com/grade
true
ebc4b93409aaa4382720eb1c7eaa5ea50ab6b31d
dfi/Learning-edX-MITx-6.00.1x
/itertools.py
608
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 14 20:10:18 2017 @author: sss """ # https://docs.python.org/3.5/library/itertools.html import operator def accumulate(iterable, func=operator.add): 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) try: total = next(it) except StopIteration: return yield total for element in it: total = func(total, element) yield total data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] accumulate(data)
true
a65f814ce9f62bc8cff8642691e206d8fa8c6b96
pabolusandeep1/python
/lab1/source code/password.py
854
4.15625
4
#validation cliteria for the passwords import re# importing the pre-defined regular expressions p = input("Input your password: ") x = True while x:# loop for checking the various cliteria if (len(p)<6 or len(p)>16):#checking for the length print('\n length out of range') break elif not re.search("\d",p):#checking for the numbers print('number missing') break elif not re.search("[$@!*]",p):#checking for the numbers print('special character missing') break elif not re.search("[a-z]",p):#checking for the numbers print('lower case missing') break elif not re.search("[A-Z]",p):#checking for the numbers print('upper case missing') break else: print("Valid Password") x=False break if x: print("Not a Valid Password")
true
fad58160cbcd35d9a671c8bc1217cf151560fafd
jasonifier/tstp_challenges
/ch6/challenge2.py
247
4.125
4
#!/usr/bin/env python3 response_one = input("Enter a written communication method: ") response_two = input("Enter the name of a friend: ") sentences = "Yesterday I wrote a {}. I sent it to {}!".format(response_one,response_two) print(sentences)
true
4a68ac695f956f6f9ee1326e59d21ce5554362ee
jasonifier/tstp_challenges
/ch4/challenge1.py
289
4.15625
4
#!/usr/bin/env python3 def squared(x): """ Returns x ** 2 :param x: int, float. :return: int, float square of x. """ return x ** 2 print(squared(5)) print(type(squared(5))) print(squared(16)) print(type(squared(16))) print(squared(5.0)) print(type(squared(5.0)))
true
76c7b4ba9c6176b96c050884111c397d651c2cba
Epiloguer/ThinkPython
/Chapter 2/Ex_2_2_3/Ex_2_2_3.py
612
4.15625
4
# If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), # then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, # what time do I get home for breakfast? import datetime easy_pace = datetime.timedelta(minutes = 8, seconds = 15) easy_miles = 2 tempo = datetime.timedelta(minutes = 7, seconds = 12) tempo_miles = 3 run_time = (easy_pace * easy_miles) + (tempo * tempo_miles) start_time = datetime.timedelta(hours = 6, minutes = 52) breakfast_time = start_time + run_time print(f"If you start running at {start_time}, you will be home for breakfast at {breakfast_time}!")
true
8c5f65fa6ce581a28ed8d34c5a36fa0c186af33d
Epiloguer/ThinkPython
/Chapter 1/Ex_1_2_3/Ex_1_2_3.py
643
4.15625
4
# If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace # (time per mile in minutes and seconds)? What is your average speed in miles per hour? kilometers = 10 km_mi_conversion = 1.6 miles = kilometers * km_mi_conversion print(f'you ran {miles} miles') minutes = 42 minutes_to_seconds = minutes * 60 seconds = 42 total_seconds = minutes_to_seconds + seconds print(f'in {total_seconds} seconds') average_pace_seconds = miles/seconds print(f'at a pace of {average_pace_seconds} miles per second') average_pace_minutes = miles / (total_seconds / 60) print(f'or at a pace of {average_pace_minutes} miles per minute')
true
b62fa67f503814abbe41952067be6b9083e7b0b9
ANUMKHAN07/assignment-1
/assign3 q6.py
203
4.21875
4
d = {'A':1,'B':2,'C':3} #DUMMY INNITIALIZATION key = input("Enter key to check:") if key in d.keys(): print("Key is present and value of the key is:",d[key]) else: print("Key isn't present!")
true
5cecd539c025b0733629ff4c403d70e280f00284
PallaviGandalwad/Python_Assignment_1
/Assignment1_9.py
213
4.1875
4
print("Write a program which display first 10 even numbers on screen.") print("\n") def EvenNumber(): i=1 while i<=10: print(i*2," ",end=""); i=i+1 #no=int(input("Enter Number")) EvenNumber()
true
47715f1e3fe9c0cc7dbb898ff0082d053ea6fa51
csyhhu/LeetCodePratice
/Codes/33/33.py
1,324
4.15625
4
def search(nums, target: int): """ [0,1,2,4,5,6,7] => [4,5,6,7,0,1,2] Find target in nums :param nums: :param target: :return: """ def binSearch(nums, start, end, target): mid = (start + end) // 2 print(start, mid, end) if start > end: return -1 if nums[mid] == target: return mid if nums[start] <= nums[mid]: # [start, mid] is ordered. Attention here, less or equal for mid may be equal to start if nums[start] <= target < nums[mid]: # target is within a order list return binSearch(nums, start, mid - 1, target) else: return binSearch(nums, mid + 1, end, target) else: # [mid, end] is ordered if nums[end] >= target > nums[mid]: # target is within a order list return binSearch(nums, mid + 1, end, target) else: # target is outside a order list, direct it to another list return binSearch(nums, start, mid - 1, target) return binSearch(nums, 0, len(nums) - 1, target) nums = [4,5,6,7,0,1,2] target = 0 print(search(nums, target)) nums = [4,5,6,7,0,1,2] target = 3 print(search(nums, target)) nums = [1] target = 0 print(search(nums, target)) nums = [3,1] target = 1 print(search(nums, target))
true
c39b8d31be3c31cc2a914a2bd0ae5a380363b27b
zhanengeng/mysite
/็Ÿฅ่ฏ†็‚น/ๅญ—็ฌฆไธฒๅ’Œๅธธ็”จๆ•ฐๆฎ็ป“ๆž„/ๆ—ฅไป˜ใ‘่จˆ็ฎ—.py
638
4.3125
4
'''ๅ…ฅๅŠ›ใ—ใŸๆ—ฅไป˜ใฏใใฎๅนดไฝ•ๆ—ฅ็›ฎ''' def leap_year(year): return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def which_day(year,month,day): days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days_count = 0 if leap_year(year): days_of_month[1] = 29 for days in days_of_month[:month-1]: days_count += days days_count += day return days_count if __name__ == "__main__": y = int(input("yearใ‚’ๅ…ฅๅŠ›:")) m = int(input("monthใ‚’ๅ…ฅๅŠ›:")) d = int(input("dayใ‚’ๅ…ฅๅŠ›:")) print(which_day(y,m,d))
true
9de40eb8d5d6abd67ff90ff2195562822399567f
lucien-stavenhagen/JS-interview-research
/fizzbuzz.py
902
4.21875
4
# # and just for the heck of it, here's the # Python 3.x version of FizzBuzz, using a Python closure # # Here's the original problem statment: # "Write a program that prints all # the numbers from 1 to 100. # For multiples of 3, instead of the number, # print "Fizz", for multiples of 5 print "Buzz". # For numbers which are multiples of both 3 and 5, # print "FizzBuzz". # def checkModulo(fizzbuzzfactor): def ifmultiple(number): return number % fizzbuzzfactor == 0 return ifmultiple fizz = checkModulo(3) buzz = checkModulo(5) def fizzBuzzGenerator(): text=[] for i in range(1,100): if fizz(i) and buzz(i): text.append("FizzBuzz") elif buzz(i): text.append("Buzz") elif fizz(i): text.append("Fizz") else: text.append(str(i)) return " ".join(text) output = fizzBuzzGenerator() print(output)
true
d4e9e097d89d3db339d92adde12b682548adf8c8
Dipesh1Thakur/Python-Basic-codes
/marksheetgrade.py
329
4.125
4
marks=int(input("Enter the marks :")) if (marks>=90): print("grade A") elif (marks>=80) and (marks<90): print("grade B") elif marks>=70 and marks<80: print("grade C") elif marks>=60 and marks<70: print("grade D") elif marks>=50 and marks<40: print("grade E") else: print("Your grade is F")
true
774075170cd50e0197b4c5a830515a9a5fac7211
zungu/learnpython
/lpthw/ex14.py
982
4.4375
4
#!/usr/bin/python from sys import argv #defines two items to be inputted for argv (script, user_name) = argv prompt1 = 'give me an answer you ass > ' prompt2 = 'I\'ll murder ye grandmotha if ye don\'t tell me > ' prompt3 = 'Sorry please answer, I\'m just having a bad day > ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name #defines a new variable, likes, with what the user enters into raw_input. likes = raw_input(prompt1) print "Where do you live %s?" % user_name #defines a new variable "lives" with a user generated input lives = raw_input(prompt2) print "What kind of computer do you have?" #defines a new variable, "computer" with a user generated input. computer = raw_input(prompt3) print """ Ok, so you said %r about liking me. You live in %r. That is a cool place. And you have a %r computer. Sweet! """ % (likes, lives, computer) #calls the variables the user entered
true
acca2584c588aab08753d32484a804b5e492d8e0
zungu/learnpython
/lpthw/ex20.py
1,249
4.28125
4
#!/usr/bin/python from sys import argv script, input_file = argv #defines the function, the j can be any letter def print_all(j): print j.read() def rewind (j) : j.seek(0) # defines a function, with a variable inside of it. line_count is a variable cleverly named so that the user knows what it is doing. later on, on line 31, we establish the current line. def print_a_line(line_count, j) : print line_count, j.readline() current_file = open(input_file) print "First let's print the whole file: \n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind (current_file) print "Let's print three lines:\n" #establishes the current line as line #1 in the .txt file current_line = 1 #calls up to def print_a_line and counts the above current line to read it print_a_line(current_line, current_file) #adds one more line to current line, so now it is reading the second line current_line = current_line + 1 #calls up to def print_a_line and counts +1 to readline(2) now print_a_line(current_line, current_file) #adds one more line to current_line, which is 2 from above. So now 3 current_line = current_line + 1 #reads line 3 of the .txt file that is current_file print_a_line(current_line, current_file)
true
5dde55554b5745f3dc71a7bb201d20a3e0496239
rehmanalira/Python-Practice-Problems
/Practice problem8 Jumble funny name.py
908
4.21875
4
""" It is a program which gives funny name """ from random import shuffle # for shffling from random import sample # sampling shuffle def function_shuffling(ele): # this is a function which is used to shuflle with this is used for shuflling ele=list(ele) # store the valu of list in ele shuffle(ele) # shufle the list return ''.join(ele) # return and join if __name__ == '__main__': name=int(input("Enter the how much names ou want")) list1=[] for i in range(name): n1=str(input("Enter the name")) list1.append(n1) print("original list",list1) res=[function_shuffling(ele) for ele in list1] # for shuffling ele is use like i or j ot anyhthing we use here as element print("SHuffled list is",res) # second way res1=[''.join(sample(ele1,len(ele1))) for ele1 in list1] # this is sample way print("Second shffeld ",res1)
true
53df6c7f31947ba21c4a0e0bbed1840ed790e8d9
Ivankipsit/TalentPy
/May week5/Project1.py
1,917
4.25
4
""" Create a python class ATM which has a parametrised constructor (card_no, acc_balance). Create methods withdraw(amount) which should check if the amount is available on the account if yes, then deduct the amount and print the message โ€œAmount withdrawnโ€, if the amount is not available then print the message โ€œOOPS! Unable to withdraw amount, Low balanceโ€. Create another method called, deposit, which should deposit amount if amount is positive and should print message โ€œAmount depositedโ€. If not, print message โ€œInvalid amount to depositโ€. Create a method called getBalance which should print current balances at any given point of time. Example: atm_acc_1 = ATM(โ€œ1234โ€, 400) atm_acc_2 = ATM(โ€œ10001โ€, 100) """ class ATM: def __init__(self,card_no,acc_balance): #initiation of variables self.card_no = card_no self.acc_balance = acc_balance def withdraw(self,w_amount): #withdraw section self.w_amount = w_amount self.acc_balance -= self.w_amount if self.acc_balance > 0 : return "Amount withdrawn" else: self.acc_balance += self.w_amount return "OOPS! Unable to withdraw amount, Low balance" def deposit(self,d_amount): #deposit section self.d_amount = d_amount if self.d_amount > 0 : self.acc_balance += self.d_amount return "Amount deposited" else: return "Invalid amount to deposit" def getBalance(self): #final section return self.acc_balance atm_acc_1 = ATM(123,400) print(atm_acc_1.withdraw(300)) #Amount withdrawn print(atm_acc_1.deposit(-100)) #Invalid amount to deposit print(atm_acc_1.getBalance()) #100 print(atm_acc_1.withdraw(300)) #OOPS! Unable to withdraw amount, Low balance print(atm_acc_1.getBalance()) #100
true
d12f4c3636de41e75e9a4bf5e435166f00866b4e
minal444/PythonCheatSheet
/ArithmaticOperations.py
770
4.125
4
# Arithmetic Operations print(10+20) # Addition print(20 - 5) # Subtraction print(10 * 2) # Multiplication print(10 / 2) # Division print(10 % 3) # Modulo print(10 ** 2) # Exponential # augmented assignment operator x = 10 x = x + 3 x += 3 # augmented assignment operator x -= 3 # augmented assignment operator # Operator Precedence = Order of Operator # Exponential --> multiplication or division --> addition or subtraction # parenthesis take priority # Math Functions x = 2.9 print(round(x)) print(abs(-2.9)) # always gives positive number # Math Module has more math functions import math print(math.ceil(2.9)) print(math.floor(2.9)) # For more information regarding Math - google it for Math module for python 3
true
c7237ded5227b686fe4d6a005db6b52a7c5bf435
chandthash/nppy
/Project Number System/quinary_to_octal.py
1,525
4.71875
5
def quinary_to_octal(quinary_number): '''Convert quinary number to octal number You can convert quinary number to octal, first by converting quinary number to decimal and obtained decimal number to quinary number For an instance, lets take binary number be 123 Step 1: Convert to deicmal 123 = 1 * 5^2 + 2 * 5^1 + 3 * 5^0 = 38 (Decimal) Step 2: Convert to octal from the obtained decimal 8 | 38 | 6 ----- 4 And our required octal number is 46 (taken in a reverse way) ''' def is_octal(): count = 0 for quinary in str(quinary_number): if int(quinary) >= 5: count += 1 if count == 0: return True else: return False if is_octal(): decimal = 0 octal_number = '' reversed_quinary = str(quinary_number)[::-1] for index, value in enumerate(reversed_quinary): decimal += int(value) * 5 ** index while decimal > 0: octal_number += str(decimal % 8) decimal = decimal // 8 print(octal_number[::-1]) else: print('Invalid quinary Number') if __name__ == '__main__': try: quinary_to_octal(123) except (ValueError, NameError): print('Integers was expected')
true
e0da7a3dd1e796cf7349392dc1681663e36616ad
chandthash/nppy
/Minor Projects/multiples.py
317
4.25
4
def multiples(number): '''Get multiplication of a given number''' try: for x in range(1, 11): print('{} * {} = {}'.format(number, x, number * x)) except (ValueError, NameError): print('Integer value was expected') if __name__ == '__main__': multiples(10)
true
dddc399fa7fc2190e838591ae38c24b3065afadd
purwar2804/python
/smallest_number.py
660
4.15625
4
"""Write a python function find_smallest_number() which accepts a number n and returns the smallest number having n divisors. Handle the possible errors in the code written inside the function.""" def factor(temp): count=0 for i in range(1,temp+1): if(temp%i==0): count=count+1 return count def find_smallest_number(num): temp=1 while(1): x=factor(temp) if(x==num): return temp else: temp=temp+1 num=16 print("The number of divisors :",num) result=find_smallest_number(num) print("The smallest number having",num," divisors:",result)
true
37e7b3c7ea73bc62be4d046ce93db984b269e2aa
brawler129/Data-Structures-and-Algorithms
/Python/Data Structures/Arrays/reverse_string.py
805
4.40625
4
import sys def reverse_string(string): """ Reverse provided string """ # Check for invalid input if string is None or type(string) is not str: return 'Invalid Input' length = len(string) # Check for single character strings if length < 2: return string # Return string itself # Create empty string to store reversed string reversed_string = "" for i in range(length-1, -1, -1): reversed_string += string[i] return reversed_string # Command line argument # input_string = sys.argv[1] """ A Few test cases """ # input_string = None # NULL # input_string = 1 #Integer # input_string = ['Hello!' , 'my' , 'name', 'is', 'Devesh.'] # Array input_string = 'Hello! My name is Devesh.' print(reverse_string(input_string))
true
3425852ccba1415b95e0feaf62916082d4a3f8b6
itu-qsp/2019-summer
/session-8/homework_solutions/sort_algos.py
2,501
4.125
4
"""A collection of sorting algorithms, based on: * http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html * http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html Use the resources above for illustrations and visualizations. """ def bubble_sort(data_list): for passnum in range(len(data_list) - 1, 0, -1): for idx in range(passnum): if data_list[idx] > data_list[idx + 1]: temp = data_list[idx] data_list[idx] = data_list[idx + 1] data_list[idx + 1] = temp #Growth rate is O(n*n) #Bubble sort in 2 minutes: https://www.youtube.com/watch?v=xli_FI7CuzA def selection_sort(data_list): for fill_slot in range(len(data_list) - 1, 0, -1): position_of_max = 0 for location in range(1, fill_slot + 1): if data_list[location] > data_list[position_of_max]: position_of_max = location temp = data_list[fill_slot] data_list[fill_slot] = data_list[position_of_max] data_list[position_of_max] = temp #O(n*n) #Selection sort in 3 minutes: https://www.youtube.com/watch?v=g-PGLbMth_g def merge_sort(data_list): # print("Splitting ", data_list) if len(data_list) > 1: mid = len(data_list) // 2 left_half = data_list[:mid] right_half = data_list[mid:] merge_sort(left_half) merge_sort(right_half) i = 0 j = 0 k = 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: data_list[k] = left_half[i] i = i + 1 else: data_list[k] = right_half[j] j = j + 1 k = k + 1 while i < len(left_half): data_list[k] = left_half[i] i = i + 1 k = k + 1 while j < len(right_half): data_list[k] = right_half[j] j = j + 1 k = k + 1 # print("Merging ", data_list) #O(n*logn) (linearithmic time) #Merge sort in 3 minutes: https://www.youtube.com/watch?v=4VqmGXwpLqc def sort_algo_b(data_list): selection_sort(data_list) def sort_algo_a(data_list): merge_sort(data_list) if __name__ == '__main__': data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] selection_sort(data_list) print(data_list) data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] merge_sort(data_list) print(data_list)
true
3f859b0275a136b8b8078b7d0798c3496d57af06
itu-qsp/2019-summer
/session-6/homework_solutions/A.py
2,864
4.6875
5
""" Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this, see file mad_libs.txt: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. The program would find these occurrences and prompt the user to replace them. Enter an adjective: silly Enter a noun: chandelier Enter a verb: screamed Enter a noun: pickup truck The following text file would then be created: The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events. The results should be printed to the screen and saved to a new text file. """ # 1. Read in the mad_libs and save it as a list where the words are the items, initialize an empty list for the result # 2. loop through all of the words. # 3. check if the words are either ADJECTIVE, NOUN, ADVERB, or VERB # 4. if they are, then replace them by a input. # 5. Append all words to the result list # 6. save result in a new file. # Opens the mad_libs.txt and saves it as a list where the items are all of the words with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs.txt", "r") as f: words = f.read().split() # Initializing a new list to store the result in new_words = [] # Looping through all of the words in the list words for word in words: if "ADJECTIVE" in word: # If the string "ADJECTIVE" is in the current word, then replace that part of the word word = word.replace("ADJECTIVE", input("Enter an adjective:\n")) elif "NOUN" in word: # If the string "NOUN" is in the current word, then replace that part of the word word = word.replace("NOUN", input("Enter a noun:\n")) elif "ADVERB" in word: # If the string "ADVERB" is in the current word, then replace that part of the word word = word.replace("ADVERB", input("Enter an adverb:\n")) elif "VERB" in word: # If the string "VERB" is in the current word, then replace that part of the word word = word.replace("VERB", input("Enter an verb:\n")) # Append the word to the list, whether is was changes or not. new_words.append(word) # Prints the new_words list as a string, where all of the items (the words in the list) are seperated by " " (a white space) print(" ".join(new_words)) # Write the new file with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs_result.txt", "w") as f: # Write the same string we printed in line 59 in the new file f.write(" ".join(new_words)) # Open the new file to check that it was saved as we wanted with open("/Users/viktortorpthomsen/Desktop/qsp2019/session6_homework/mad_libs_result.txt", "r") as f: new_text = f.read() print(new_text)
true
7cf44380af29bb10e89ef1ec62ba1b2ee96c0066
fortiz303/python_code_for_devops
/join.py
290
4.34375
4
#Storing our input into a variable named input_join input_join = input("Type a word, separate them by spaces: ") #We will add a dash in between each character of our input join_by_dash = "-" #Using the join method to join our input. Printing result print(join_by_dash.join(input_join))
true
81151f0a5de8a7edda840bb24e97288a99d29ab0
MyreMylar/artillery_duel
/game/wind.py
2,110
4.15625
4
import random class Wind: def __init__(self, min_wind, max_wind): self.min = min_wind self.max = max_wind self.min_change = -3 self.max_change = 3 self.time_accumulator = 0.0 # Set the initial value of the wind self.current_value = random.randint(self.min, self.max) self.last_change = 0 if self.current_value > 0: self.last_change = 1 if self.current_value < 0: self.last_change = -1 # Set the amount of time in seconds until the wind changes self.time_until_wind_changes = 5.0 def change_wind(self): # Set the amount of time in seconds until the wind changes self.time_until_wind_changes = random.uniform(3.0, 8.0) # Try to simulate the wind changing. Currently it is more likely to continue # blowing in the same direction it blew in last time (4 times out of 5). if self.last_change > 0: change_value = random.randint(-1, self.max_change) self.last_change = change_value elif self.last_change < 0: change_value = random.randint(self.min_change, 1) self.last_change = change_value else: change_value = random.randint(-1, 1) self.last_change = change_value self.current_value += change_value # Make sure the current wind value does not exceed the maximum or minimum values if self.current_value > self.max: self.current_value = self.max if self.current_value < self.min: self.current_value = self.min def update(self, time_delta): # The timeDelta value is the amount of time in seconds since # the last loop of the game. We add it to the 'accumulator' # to track when an amount of time has passed, in this case # 3 seconds self.time_accumulator += time_delta if self.time_accumulator >= self.time_until_wind_changes: self.time_accumulator = 0.0 # reset the time accumulator self.change_wind()
true
ea2e97ed068f7dc534f6d1dd6318927d2ed01a4a
svfarande/Python-Bootcamp
/PyBootCamp/errors and exception.py
957
4.125
4
while True: try: # any code which is likely to give error is inserted in try number1 = float(input("Enter Dividend (number1) for division : ")) number2 = float(input("Enter Divisor (number2) for division : ")) result = number1 / number2 except ValueError: # it will run when ValueError occurs in try block print("Looks like you didn't enter number. Try again.") continue except ZeroDivisionError: # it will run ZeroDivisionError occurs in try block print("Looks like your divisor is 0. Try again.") continue except: # it will run when error occur but doesn't belong to above expected errors print("Something is wrong. Try again.") continue else: # It will only run when either of the expect don't run print("Division is = " + str(result)) break finally: # Whatever may be the case this will run for sure print("Great Learning !!")
true
9b6c4e8219809f7e2235bdedad400d80f6d0be98
nage2285/day-3-2-exercise
/main.py
1,027
4.34375
4
# ๐Ÿšจ Don't change the code below ๐Ÿ‘‡ height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) # ๐Ÿšจ Don't change the code above ๐Ÿ‘† #Write your code below this line ๐Ÿ‘‡ #print(type(height)) #print(type(weight)) #BMI Calculator BMI = round(weight/ (height * height)) if BMI < 18.5 : print (f"Your BMI is {BMI}, you are underweight.") elif BMI < 25 : print (f"Your BMI is {BMI}, you are normal weight.") elif BMI < 30 : print (f"Your BMI is {BMI}, you are slightly overweight.") elif BMI < 35 : print (f"Your BMI is {BMI}, you are obese.") else : print (f"Your BMI is {BMI}, you are clinically obese.") # How to convert string into lower #sentence = ("Mary Had a Little lamb") #sentence_l = sentence.lower() #print(sentence_l) #How to count number of certain alphabets #sentence = "Mary had a little lamb" #sentence1 = sentence.count("a") #sentence2 = sentence.count("t") #count = sentence1 + sentence2 #print(sentence1) #print(sentence2) #print (type(count)) #print(count)
true
61d5f409e19effec42600395ec8e9ce06f88b956
UjjwalDhakal7/basicpython
/typecasting.py
1,793
4.46875
4
#Type Casting or Type Cohersion # The process of converting one type of vaue to other type. #Five types of data can be used in type casting # int, float, bool, str, complex #converting float to int type : a = int(10.3243) print(a) #converting complex to int type cannot be done. #converting bool to int : b = int(True) c = int(False) print(b,c) #converting string to int type : #string should contain int or float values which should be specified in base 10. d = int('50') print(d) #converting int to float : print(float(12)) print(float(0b101)) #converting complex to float is also not possible. #converting bool to float : print(float(True)) print(float(False)) #converting str to float : print(float('200')) #converting int, float into complex : #Form 1 : #entering only one argument, pvm will assume it as real value. print(complex(1)) print(complex(10.4)) print(complex(True)) print(complex(False)) print(complex('50')) #Form 2 : #entering two arguments, pvm will assume first argument as real and the other as imaginery value. print(complex(10,3)) print(complex(10.4, 10.2)) #str to complex has various restrictions. #converting to bool types: #For int and float types, #if the argument is 0, the bool value will be False, else true. print(bool(10)) print(bool(0)) #For complex types, #if real and imaginary part is 0, bool value is False, else True. print(bool(10+10j)) print(bool(0j)) #For str types, #if the argument is empty then only bool value is False, else any value is True. print(bool('True')) print(bool("False")) print(bool('')) #converting to str types : a = str(10) b = str(0b1010) c = str(10.67) d = str(10+2j) print(type(a), type(b), type(c))
true
48741d9ccf235ca379a3b7ead7082637b33c450d
UjjwalDhakal7/basicpython
/booleantypes.py
248
4.21875
4
#boolean datatypes #we use boolean datatypes to work with boolean values(True/False, yes/no) and logical expressions. a = True print(type(a)) a = 10 b=20 c = a<b print(c) print(type(c)) print(True + True) print(False * True)
true
50ed06f5df2f648636a8237cca5ca3cd36732b2c
UjjwalDhakal7/basicpython
/intdatatypes.py
1,181
4.40625
4
#we learn about integer datatypes here: #'int' can be used to represent short and long integer values in python 3 # python 2 has a concpet of 'long' vs 'int' for long and short int values. #There are four ways to define a int value : #decimal, binary, octal, hexadecimal forms #decimal number system is the default number system #To define a binary number it should have a prefix '0b' or '0B': a = 0b1111 A = 0B11001 print(a) print(A) #To define a octal number it should have a prefix '0o' or '0O': b = 0o1341 B = 0O12301 print(b) print(B) #To define a hexa number it should have a prefix '0x' or '0X': c = 0x2342AB C = 0X43667F print(c) print(C) #in case of Hexa form python does not follow case sensitiveness. print(0xBeef) print(0XAbcD) #Base Conversion Functions : #1. bin() #can be used to convert other forms of number to binary number system. bin(0o127) bin(15) bin(0X12A) #2. oct() >> #can be used to convert other forms of number to octal number system. oct(0b100110) oct(15) oct(0X12A) #3. hex() >> #can be used to convert other forms of number to binary number system. hex(0o127) hex(15) print(hex(0b100110))
true
8709a8799021fed49bb620d7088c22bc086492dd
ewrwrnjwqr/python-coding-problems
/python-coding-problems/unival tree challenge easy.py
1,921
4.25
4
#coding problem #8 #A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. #Given the r to a binary tree, count the number of unival subtrees. # the given tree looks like.. # 0 # / \ # 1 0 # / \ # 1 0 # / \ # 1 1 class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right node_right_left1 = Node(1, Node(1), Node(1)) node_right1 = Node(0, node_right_left1, Node(0)) t = Node(0, Node(1), node_right1) def in_order(r): if r.left: in_order(r.left) print(str(r.value) + ', ', end='') if r.right: in_order(r.right) in_order(t) print('') def is_unival(r): if r is None: return True if r.left is not None and r.left.value != r.value: return False if r.right is not None and r.right.value != r.value: return False if is_unival(r.left) and is_unival(r.right): return True return False def count_univals(r): if r is None: return 0 total_count = count_univals(r.left) + count_univals(r.right) if is_unival(r): total_count += 1 return total_count def count_univals2(r): total_count, is_unival = helper(r) return total_count def helper(r): if r is None: return 0, True left_count, is_left_unival = helper(r.left) right_count, is_right_unival = helper(r.right) is_unival = True if not is_left_unival or not is_right_unival: is_unival = False if r.left is not None and r.left.value != r.value: is_unival = False if r.right is not None and r.right.value != r.value: is_unival = False if is_unival: return left_count + right_count + 1, True else: return left_count + right_count, False print(count_univals(t), 'should be 5')
true
1f3b48d098480dd34dee90aaabe24822b6682e71
ColeCrase/Week-5Assignment
/Page82 pt1.py
228
4.125
4
number = int(input("Enter the numeric grade: ")) if number > 100: print("Error: grade must be between 100 and 0") elif number < 0: print("Error: grade must be between 100 and 0") else: print("The grade is", number)
true
8de67b2e8d4fb914a3b9f3e29a5a85d9cba30c0c
subho781/MCA-Python-Assignment
/Assignment 2 Q7.py
337
4.1875
4
#WAP to input 3 numbers and find the second smallest. num1=int(input("Enter the first number: ")) num2=int(input("Enter the second number: ")) num3=int(input("Enter the third number: ")) if(num1<=num2 and num1<=num3): s2=num1 elif(num2<=num1 and num2<=num3): s2=num2 else: s2=num3 print('second smallest number is :',s2)
true
bd2ef2d43a62650f68d140b1097e98b73a27f293
Athenstan/Leetcode
/Easy/Edu.BFSzigzag.py
888
4.15625
4
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None #first try at the problem def traverse(root): result = [] if root is None: return result # TODO: Write your code here queue = deque() queue.append(root) toggle = True while queue: levelsize = len(queue) currentlevel = [] for _ in range(levelsize): currentnode = queue.popleft() if toggle: currentlevel.append(currentnode.val) else: currentlevel.insert(0,currentnode.val) if currentnode.left: queue.append(currentnode.left) if currentnode.right: queue.append(currentnode.right) toggle = not toggle result.append(currentlevel) return result #Generally correct, logic was done properly and the method executed as promised. Need to research more into appendleft function
true
d407f3540a1a4d7240fb572a3e1fa12e430cdced
rjimeno/PracticePython
/e6.py
273
4.125
4
#!/usr/bin/env python3 print("Give me a string and I will check if it is a palindrome: ") s = input("Type here: ") for i in range(0, int(len(s)/2)): l = len(s) if s[i] != s[l-1-i]: print("Not a palindrome.") exit(1) print("A palindrome!") exit(0)
true
f72b45ba5408c8ab5afbe1d88e96c10bb157b920
rjimeno/PracticePython
/e3.py
1,479
4.15625
4
#!/usr/bin/env python3 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] default_limit = 5 for x in a: if x < default_limit: print(x) # Extras: # 1.Instead of printing the elements one by one, make a new list that has all # the elements less than 5 from this list in it and print out this new list. def list_less_than( input_array, limit=default_limit): """ >>> list_less_than([]) [] >>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> list_less_than(a) [1, 1, 2, 3] >>> list_less_than(a, 8) [1, 1, 2, 3, 5] """ l = [] for n in input_array: if n < limit: l.append(n) return l # 2. Write this in one line of Python. def list_less_than_oneliner(i_a, l=default_limit): """ >>> list_less_than([]) [] >>> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> list_less_than_oneliner(a) [1, 1, 2, 3] >>> list_less_than_oneliner(a, 8) [1, 1, 2, 3, 5] """ return [n for n in i_a if n < l] try: limit = int(input("What's the smallest number you don't care about (i.e. " "What's the limit? Default is {}.)" .format( default_limit))) except Exception as e: print("That did not look like a number: '{}'".format(e)) print("Will default of {} instead.".format(default_limit), file=sys.stderr) limit = default_limit print(list_less_than_oneliner(a, limit)) if '__main__' == __name__: import doctest doctest.testmod()
true
c6e36b6fb21454dbfb35fcf4862afeb97c3abbc5
souzartn/Python2Share
/other/completed/Rock_Paper_Scissors.py
1,296
4.34375
4
################################################################ # Challenge 02 # Game "Rock, Paper, Scissors" # Uses: Basic Python - e.g. If, elif,input, print ################################################################ import os clearScreen = lambda: os.system('cls') def computeGame(u1, u2): if u1 == u2: return("It's a tie!") elif u1 == 'rock': if u2 == 'scissors': return("Rock wins!") else: return("Paper wins!") elif u1 == 'scissors': if u2 == 'paper': return("Scissors win!") else: return("Rock wins!") elif u1 == 'paper': if u2 == 'rock': return("Paper wins!") else: return("Scissors win!") else: return("Invalid input! One of the player did not enter rock, paper or scissors, try again.") sys.exit() clearScreen() print("---------------------------------------------------------") print("Game: Rock, Paper, Scissors!") user1_answer = input("Player01, do yo want to choose rock, paper or scissors? ") user2_answer = input("Player02, do you want to choose rock, paper or scissors? ") result = computeGame(user1_answer, user2_answer) print(result) print("---------------------------------------------------------")
true
80e6a92937db9f5a34465ec78fff113e99b1e4a9
neerajmaurya250/100-Days-of-Code
/Day-12/power.py
417
4.125
4
terms = int(input("How many terms? ")) result = list(map(lambda x: 2 ** x, range(terms))) # display the result print("The total terms is:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) # output: # How many terms? 5 # The total terms is: 5 # 2 raised to power 0 is 1 # 2 raised to power 1 is 2 # 2 raised to power 2 is 4 # 2 raised to power 3 is 8 # 2 raised to power 4 is 16
true
a805c9af0f10ca75770fc88d7b33967e5af71cfc
everydaytimmy/code-war
/7kyu.py
716
4.1875
4
# In this kata, you are asked to square every digit of a number and concatenate them. # For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): return int(''.join(str(int(i)**2) for i in str(num))) ###------ Over The Road ------### # You've just moved into a perfectly straight street with exactly n identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this: def over_the_road(address, n): distance = (2*n) + 1 return distance - address
true
c944e5314444364dfcffe437c49a16cd70062888
rjrishav5/Codes
/Linkedlist/insert_doubly_linkedlist.py
2,193
4.28125
4
class Node: def __init__(self,data): self.data = data self.next = None self.prev = None class doubly_linkedlist: def __init__(self): self.head = None # insert node at the end of a doubly linkedlist def at_end(self,data): new_node = Node(data) if self.head is None: self.head = new_node return else: temp = self.head while(temp.next is not None): temp = temp.next temp.next = new_node new_node.prev = temp # insert node at the begining of a doubly linkedlist def at_begining(self,data): new_node = Node(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node # insert node at a given position in doubly linkedlist def at_position(self,position,data): new_node = Node(data) if (position == 1): new_node.next = self.head self.head.prev = new_node self.head = new_node else: temp = self.head i = 2 while(i <=position-1): if(temp.next is not None): temp = temp.next i+=1 if (temp.next is not None): new_node.next = temp.next new_node.prev = temp temp.next = new_node if(new_node.next is not None): new_node.next.prev = new_node # print the doubly linkedlist def print_llist(self): temp = self.head if (temp is not None): print("\nThe list contains:",end=" ") while(temp is not None): print(temp.data,end=" ") temp = temp.next else: print("The list is empty") dllist = doubly_linkedlist() dllist.at_end(2) dllist.at_end(3) dllist.at_end(4) dllist.at_end(5) dllist.at_end(6) dllist.at_end(7) dllist.print_llist() dllist.at_position(3,15) dllist.print_llist() dllist.at_position(1,20) dllist.print_llist()
true
596d01a48433701abcdf0b13d338b6d176d3de90
YOON81/PY4E-classes
/09_dictionaries/exercise_04.py
973
4.25
4
# Exercise 4: Add code to the above program to figure out who has the most messages # in the file. After all the data has been read and the dictionary has been created, # look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum # loops) to find who has the most messages and print how many messages the person has. fname = input('Enter a file name: ') # mbox-short.txt if len(fname) < 1: fname = 'mbox-short.txt' try: fhand = open(fname) except: print('Check the name again.') exit() emailist = dict() for line in fhand: line = line.rstrip() word = line.split() if line.startswith('From '): emailist[word[1]] = emailist.get(word[1], 0) + 1 #print(emailist) largest = 0 themail = None for key, value in emailist.items(): if largest == 0 or value > largest: largest = value themail = key print('The most message is', themail, largest) # The most message is cwen@iupui.edu 5 # good job Yoon!
true
92514ac1daed990f7d22f402f23760511642d1c1
YOON81/PY4E-classes
/04_functions/exercise_06.py
759
4.15625
4
# Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and # create a function called computepay which takes two parameters (hours and rate). # ** ์ฒซ๋ฒˆ์งธ ์งˆ๋ฌธ์— ๋ฌธ์ž ์ž…๋ ฅํ–ˆ์„ ๋•Œ ์—๋Ÿฌ ๋ฉ”์„ธ์ง€ ๋œจ๋Š” ๊ฑด ์•„์ง ํ•ด๊ฒฐ ์•ˆ๋จ ** # ** ๋งˆ์ง€๋ง‰ ํ”„๋ฆฐํŠธ๋ฌธ์— ์—๋Ÿฌ ๋œธ ! ** hours = input('Enter Hours: ') rate = input('Enter Rate: ') try: hours = float(hours) rate = float(rate) def computepay(hours, rate): if hours <= 40: hours_pay = (hours * rate) return hours_pay else: hours_pay = (40 * rate) + (hours - 40) * rate * 1.5 return hours_pay except ValueError: print('Error, Please enter numeric input') print(computepay(hours, rate))
true
7f9d7da99a451c6e90b34331a02076cdbe4b2d3b
brad93hunt/Python
/github-python-exercises/programs/q12-l2-program.py
482
4.125
4
#!/usr/bin/env python # # Question 12 - Level 2 # # Question: # Write a program, which will find all such numbers between 1000 and 3000 (both included) # such that each digit of the number is an even number. # The numbers obtained should be printed in a comma-separated sequence on a single line. def main(): # Print number for each number in the range of 1000 - 3000 if num % 2 == 0 print [i for i in range(1000,3001) if i % 2 == 0] if __name__ == '__name__': main()
true
9bd97f882ac5185dd2f78b4f4ed83e3e7c930de6
brad93hunt/Python
/github-python-exercises/programs/q13-l2-program.py
595
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # Question 13 - Level 2 # # Question: #ย Write a program that accepts a sentence and calculate the number of letters and digits. # Suppose the following input is supplied to the program: # hello world! 123 # Then, the output should be: # LETTERS 10 # DIGITS 3 def main(): user_input = raw_input('Please enter a string of letters and numbers: ') letters = sum(c.isaplha() for c in user_input) numbers = sum(c.isdigit() for c in user_input) print 'Letters: ', letters print 'Numbers: ', numbers if __name__ == '__main__': main()
true
2af9387667d6254a491cef429c85c32e75a3c2d8
Artem123Q/Python-Base
/Shimanskiy_Artem/homework_5/homework5_2.py
788
4.25
4
''' Task 5.2 Edit your previous task: put the results into a file. Then create a new python script and import your previous program to the new script. Write a program that reads the file and prints it three times. Print the contents once by reading in the entire file, once by looping over the file object, and once by storing the lines in a list and then working with them outside the 'with' block. ''' '''from homework_5_1 import summ print(summ()) with open('file_test', 'a') as in_file: for i in range(3): read_3_times = in_file.write(f'{summ()}\n') print(read_3_times)''' with open('file_test') as read_all: file_value = read_all.read() print(file_value) for i in file_value: print(i)# loop list_1 = [] for i in file_value: list_1.append(i)
true
9ecf2afb58c4c9a938b4d8a96f75a4858d5138bc
xinmu01/python-code-base
/Advanced_Topic/Iterator_example.py
1,113
4.28125
4
class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) # After define the __iter__, the iter() and for in loop can be used. def __iter__(self): return self #As long as define __next__, the next() can be used. def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] def reset(self): self.index = len(self.data) a = Reverse("I am Xin") print (next(a)) for i in a: print (i) print() a.reset() for i in a: print(i) print() a.reset() b = iter(a) print (next(b)) for i in b: print(i) print() ##Convert List to Iterator test_list = [1,2,3] test_list_iter = iter(test_list) print(next(test_list_iter)) print(next(test_list_iter)) print(next(test_list_iter)) ##Generator Example def generator_example(a): for i in a: yield i generator_example = generator_example([1,2,3]) print(next(generator_example)) for i in generator_example: print (i)
true
e5ea2965be23486032a8d31ee2bfc01cd8d59126
cryptoaimdy/Python-strings
/src/string_indexing_and_slicing_and_length.py
1,180
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[35]: # string indexing and slicing s = "crypto aimdy" # printing a character in string using positive index number print(s[5]) # printing a character in string using negative index number print(s[-5]) # In[28]: ##String Slicing #printing string upto 5 characters print(s[:5]) # In[29]: #prints string after first leaving first 5 char print(s[5:]) # In[30]: #prints char at position 4 all the way upto char at position 5 but leaving the character 5. print(s[4:5]) # In[31]: #prints all the char from opposite side after leaving first eight char from backwards. print(s[:-8]) # In[32]: #pritns cahr from backward at index 2. print(s[-2]) # In[33]: #prints the every character at the gap of 5 characters after priting each character. print(s[::5]) # In[34]: #prints the every character from backwards at the gap of 3 characters after priting each character. print(s[::-3]) # In[37]: # string length #printing string length print(len(s)) # In[43]: #Instead of using a variable, we can also pass a string right into the len() method: print(len("Let's print the length of this string.")) # In[ ]:
true
310c2e0bbde417cbf69ee2768a833c6c3cbdb51a
thonathan/Ch.04_Conditionals
/4.2_Grading_2.0.py
787
4.25
4
''' GRADING 2.0 ------------------- Copy your Grading 1.0 program and modify it to also print out the letter grade depending on the numerical grade. If they fail, tell them to "Transfer to Johnston!" ''' grade= int(input("Please enter your grade: ")) exam= int(input("Please enter your exam score: ")) worth= int(input("Please enter your exam worth: ")) examworth=worth/100 gradeworth=(100-worth)/100 ave=grade*(gradeworth)+exam*examworth print() print("Here is your final grade: ",ave,) if ave>90: print("Here is your letter grade: A!") elif ave>80: print("Here is your letter grade: B!") elif ave>70: print("Here is your letter grade C") elif ave>60: print("Here is your letter grade D") else: print("Here is your letter grade F") print("Transfer to Johnston!")
true
370cfa9c4c18e0345cd14d49f6bc5762886d3b84
SHajjat/python
/binFunctionAndComplex.py
359
4.1875
4
# there is another data type called complex complex =10 # its usually used in complicated equations its like imaginary number # bin() changes to binary numbers print(bin(10000)) # this will print 0b10011100010000 print(int("0b10011100010000",2)) # im telling it i have number to the base of 2 i wanna change to int # this will return it to integer 10000
true
ce2e9a4fce24333c40aab5c06c2b83d16c5ae9c0
booherbg/ken
/ppt/magic/functions_examples.py
2,601
4.125
4
''' Working with functions ''' # one parameter, required def person1(name): print "My name is %s" % name #one parameter, optional w/ default argument def person2(name='ken'): print "My name is %s" % name #three parameters, two optional def person3(name, city='cincinnati', work='library'): print "My name is %s from %s, I work at %s" % (name, city, work) #one required parameter, the rest are variable def person4(name, *params): print "My name is %s, my parameter list is:" % name for i in params: print i #one required param, variable keywords def person5(name, **keywords): print "My name is %s" % name if keywords.has_key('city'): print "I am from %s" % keywords['city'] for kw,val in keywords.items(): print "%s: %s" % (str(kw), str(val)) # one required param, then variable params, then variable keywords def person6(*params, **keywords): if keywords.has_key('name'): name = keywords['name'] else: name = 'anonymous' print "My name is %s" % name print "My params are:" for i, p in enumerate(params): print "%d. %s" % (i, str(p)) print "My keywords are:" # Note the use of a tuple unpacking from enumerate... for i, (key, val) in enumerate(keywords.items()): print "%d. %s:%s" % (i, str(key), str(val)) print "Now I'm going to call the function contained in the keyword 'func':" if keywords.has_key('func'): print "==== result from calling: %s =====" % keywords['func'] keywords['func'](**keywords) else: print "no function found" # simple usage print 'person1' person1('blaine') print '' print 'person2' person2() person2('ken') print '' print 'person3' person3('blaine') person3('blaine', 'dayton', 'airport') person3('blaine', work='coffee shop') person3('blaine', work='donut shop', city='san francisco') print '' print 'person4' person4('blaine', 'random', 'parameters', 'for', 5, 19, person4) # * means "take everything in range(10) and make them actual arguments. don't pass in a list of numbers, # pass in parameters of integers person4('blaine', *range(10)) # but you could do this too! person4('blaine', range(10)) print '' print 'person5' person5('blaine', keyword='mykeyword', city='columbus, ohio') person5(city='cleveland', name='blaine') print '' print 'person6' person6(1,2,3,4,5, name='blaine', city='cincinnati', work='clifton labs') # pay attention now, this gets interesting! person6(1,2,3,4, name='blaine', city='cincinnati', work='cliftonlabs', func=person5)
true
9c73b01299eeb325f8035f6c3307aab051fd804d
ShehrozeEhsan086/ICT
/Python_Basics/replace_find.py
689
4.28125
4
# replace() method string = "she is beautiful and she is a good dancer" print(string.replace(" ","_")) # replaces space with underscore print(string.replace("is","was")) # replaces is with was print(string.replace("is","was",1)) #replaces the first is with was print(string.replace("is","was",2)) #replaces both is in the sentence to was # find() method # find the location for a value print(string.find("is")) print(string.find("is", 5)) # will look for "is" after position 4 # if the location of the first "is" is unknown we can do;. is_pos1 = string.find("is") print(is_pos1) is_pos2 = string.find("is",is_pos1 +1) # +1 so that it wont count the first "is" print(is_pos2)
true
508877d679b9c33911f6c9823045770931d7c0f0
CallumRai/Radium-Tech
/radium/helpers/_truncate.py
855
4.375
4
import math def _truncate(number, decimals=0): """ Truncates a number to a certain number of decimal places Parameters ---------- number : numeric Number to truncate decimals : int Decimal places to truncate to, must be non-negative Returns ------- ret : numeric Number truncated to specified decimal places Raises ------ TypeError Decimals is not an integer ValueError Decimals is negative """ if not isinstance(decimals, int): raise TypeError('Decimals must be an integer.') elif decimals < 0: raise ValueError('Decimals must be >= 0.') elif decimals == 0: # If decimals is zero can truncate as normal return math.trunc(number) factor = 10.0 ** decimals return math.trunc(number * factor) / factor
true
6bbaf096406780be38dceedcf04602b1d48210d0
AliSalman86/Learning-The-Complete-Python-Course
/10Oct2019/list_comprehension.py
1,678
4.75
5
# list comprehension is a python feature that allows us to create lists very # succinctly but being very powerful. # doubling a list of numbers without list comprehension: numbers = [0, 1, 2, 3, 4, 5] doubled_numbers = list() # use for loop to iterate the numbers in the list and multiply it by 2 for number in numbers: doubled_numbers.append(number * 2) print(doubled_numbers) print("=========================================") # same above with list comprehension numbers_2 = [1, 2, 3, 4, 5] doubled_numbers_2 = [number * 2 for number in numbers_2] print(doubled_numbers_2) print("=========================================") # practice for comprehension names = ["Alex", "Alice", "Jaafar", "Jenna"] last_name = "Jordan" full_names = [f"{name} full name is {name} {last_name}." for name in names] print(full_names) print("=========================================") # multi lists comprehension a_numbers = [3, 4, 5, 6] b_numbers = [8, 5, 3, 1] multiplied = [a * b for a in a_numbers for b in b_numbers] print(multiplied) print(f"multiply a_numbers list by b_numbers list give us {len(multiplied)} possibility") print("=========================================") # validating names to true is first letter is capital or small # lower(), will make all letters in a string in a list lower case. # title(), make every string in a list start with capital letter. friend = input("Enter your name: ") friends = ["Alex", "Alice", "Jaafar", "Jenna"] friends_lower = [name.lower() for name in friends] print(friend) print(friends_lower) if friend.lower() in friends_lower: print(f"Hello {friend.title()}") else: print(f"Hi, nice to meet you {friend.title()}")
true
a6ff0a523770dff757aecf156646ae5ad1ef9687
AliSalman86/Learning-The-Complete-Python-Course
/07Oct2019/basic_while_exercise.py
738
4.40625
4
# you can input any letter but it will actually do something only if p entered to # print hello or entered q to quit the program user_input = input("Please input your choice p to start the prgram or q to terminate: ") # Then, begin a while loop that runs for as long as the user doesn't type 'q', if q # entered then program terminate. while user_input != "q": # if user input p then hello printed if user_input == "p": print("Hello!") # ask user again what to input p to print again or q to quit # entering any other letters would led the program to input a letter again without # printing or quiting user_input = input("Please input your choice p to start the prgram or q to terminate: ") print("program terminated")
true