blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4bea2aa9f65dc46094022529b2666bd0ebd4a252
chinatsui/DimondDog
/algorithm/exercise/hash_table/find_two_squares_sum.py
943
4.3125
4
""" Given a number 'num', find another two numbers 'a' and 'b' to make pow(a,2) + pow(b,2) = num, then return [a,b] If there doesn't exist such a pair of numbers, return an empty array. Example 1: Input: 58. Output: [3, 7] Explanation: 3^2 + 7^2 = 58 Example 2: Input: 12. Output: [] Explanation: There doesn't exist a pair of numbers to make pow(a,2) + pow(b,2) == 12 """ class Solution: def find_two_square_nums(self, num): if num < 0: return [] max_sqrt = self._max_sqrt(num) i, j = 0, max_sqrt while i <= j: sum = pow(i, 2) + pow(j, 2) if sum == num: return [i, j] elif sum < num: i += 1 else: j -= 1 return [] @staticmethod def _max_sqrt(n): i = 0 while pow(i, 2) <= n: i += 1 return i - 1 print(Solution().find_two_square_nums(12))
true
079df767f942e053cc7c3da2ac52b214e2f76dd9
chinatsui/DimondDog
/algorithm/exercise/dfs/flatten_binary_tree_to_linked_list.py
1,324
4.21875
4
""" LeetCode-114 Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ from algorithm.core.binary_tree import BinaryTree class Solution: """ My initial implementation is to flatten the tree to below format: 1 / 2 / 3 / 4 / 5 / 6 Although it is a linked list, but not expected as requirement. Think the answer over and over. Besides, this problem is a very good example to recurse and change a tree in-place. """ def flatten(self, root): if not root: return self.flatten(root.left) self.flatten(root.right) if root.left: cur = root.left while cur.right: cur = cur.right cur.right = root.right root.right = root.left root.left = None t_root = BinaryTree.deserialize([1, 2, 5, 3, 4, None, 6]) Solution().flatten(t_root) print(BinaryTree.serialize(t_root))
true
7fba688e38fd71770a82e5fd1b679b3310b07eb0
JeremyJMoss/NumberGuessingGame
/main.py
837
4.125
4
import random print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100") randomNum = random.randint(1, 101); difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") if difficulty == "easy": attempts = 10 else: attempts = 5 game_over = False while game_over == False: print(f"You have {attempts} attempts to guess the number") guess = int(input("Make a guess: ")) attempts -= 1 if guess < 1 or guess > 100: print("Invalid guess.") elif guess == randomNum: print(f"You got it! The number was {randomNum}!") game_over = True elif guess > randomNum: print("Too high.") else: print("Too low.") if game_over == False: if attempts == 0: game_over = True print("You've run out of guesses, You lose.") else: print("Guess again.")
true
c907b392e1ee740c0f8d88935014170850865099
award96/teach_python
/B-variables.py
1,489
4.53125
5
""" Variables are necessary to keep track of data, objects, whatever. Each variable in Python has a name and a pointer. The name is how you call the variable ('a' in the lines below) and the pointer 'points' to the object in memory. The pointer can change as you reassign the variable (as I do below) This is important: A variable has a pointer, not an object. If the object the pointer references changes, the next time you use the variable it will have changed as well. Some objects are called Primitives, and are immutable. This means that when you set x = 5, you cannot do anything to '5' to change it. You can only reassign the variable, ie x = 6 """ a = 5 print(a) a = "applesauce" # 5 has not changed, the pointer associated with a has changed print(a) def variable_test(): # a variable defined inside of a function is 'local scoped' # this means that a = True only inside of this function. Outside a # continues to equal whatever it did equal. a = True # a = applesauce print(a) variable_test() # a still equals applesauce because the function cannot change variables outside of its scope print(a) # this is how to print things in a more organized way print('\n') # \n creates a new line regardless of where you put it print(f"{a}") # f before a string makes it possible to put variables inside brackets within the string # here's how you might use that print(f"\nThis string has much better formatting\na = {a}") print(""" \n A multiline string for printing! """)
true
be8450d8e7bd73004d0e181703dc1175e1309139
nebkor/lpthw
/ex32.py
870
4.59375
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'appricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is the count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # creating a list of integers 0 - 5, held by elements elements = range(0, 6) # now we can print them out too for i in elements: print "Element was: %d" % i # reverse a list and print def reverse_list_print(l): # try: didn't work here, unindent error. Maybe we need a else:? print "Now, backwards!" l.reverse() for i in l: print i print reverse_list_print(elements)
true
9ceec7eae46ff248dbcdcfa1146738bea6b517cc
nebkor/lpthw
/ex20.py
2,230
4.25
4
# import sys.argv into the global namespace as argv from sys import argv # assign script to the 0th entry in the argv array and input_file # to the 1th entry in the argv array script, input_file = argv # Define the function "print_all()" which takes an argument as f def print_all(f): print f.read() # prints the contents of f using the .read() method # f can only be a file object, else the .read() method will fail # Define the function "rewind()" which takes an argument as f def rewind(f): f.seek(0) # using the .seek() method on a file object to # return the offset of the file back to the 0th byte # define the function "print_a_line()" which takes two arguments as # line_count and f. def print_a_line(line_count, f): print line_count, f.readline(), # prints the raw value of line_count followed by a space # then uses the .readline() method on the file object f # to print a string from the the file object starting at the current # offset until the next new line # assigning the variable current_file to the output of the "open()" function # using the input_file variable as it's argument current_file = open(input_file) print "First let's print the whole file:\n" # calls the "print_all()" function on the file object held by the # current_file variable, which performs the .read() method from the # file object's current offset to the end of the file. print_all(current_file) print "Now let's rewind, kind of like a tape." # calls the "rewind()" function on the file object held by the # current_file variable which performs the .seek() method on the file object # setting offset of the file object back to the 0th byte rewind(current_file) print "Now let's print three lines:" current_line = 1 # current_line value is 1 print_a_line(current_line, current_file) current_line = current_line + 1 # current_line value is now 2 print_a_line(current_line, current_file) current_line = current_line + 1 # current_line value is now 3 print_a_line(current_line, current_file) print_a_line(current_line, f = open(input_file)) print_a_line(current_line + 1, current_file) print_a_line(current_line + 2, current_file)
true
ad25f8423417bd2f9de0ea80ae9c97bc53635969
nebkor/lpthw
/joe/ex15.py
1,594
4.625
5
# import sys.argv into the global namespace as argv from sys import argv # assign to the 'script' variable the value of argv[0], # assign to the 'filename' variable the value of argv[1] script, filename = argv # assign to the 'txt' variable the value returned by the # function "open()", which was called with the variable # 'filename' as its argument. The "open()" function returns # a File object, so the variable 'txt' has a value of type # "File". txt = open(filename) # print the raw representation of the string value # of the variable 'filename', prepended with the string, # "Here's your file " and appended by the string ":". print "Here's your file %r:" % filename # print the contents of the file named by the value # of the variable 'filename', by invoking the "read()" # method of object referenced by the variable 'txt'. print txt.read() # close the file handle referenced by the variable 'txt' # by calling the "close()" method. calling "read()" on # txt after it's been closed would be an error. txt.close() # prints the string "Type the filename again:" print "Type the filename again:" # assign to the variable 'file_again' the output from # the function "raw_input()", which was called with a string # argument "> ", used as the prompt for the user # to enter a string to be passed as input to the "raw_input()" # function file_again = raw_input("> ") # assgin to the 'txt' variable the value returned by the # function "open()", which was called with the variable # 'file_again' as its argument. txt_again = open(file_again) print txt_again.read() txt_again.close()
true
4272bcf4fdcdee3dfeada312f6e5325d6bc70760
Dylan-Lebedin/Computer-Science-1
/Homework/test_debug2.py
2,868
4.1875
4
""" This program includes a function to find and return the length of a longest common consecutive substring shared by two strings. If the strings have nothing in common, the longest common consecutive substring has length 0. For example, if string1 = "established", and string2 = "ballistic", the function returns the integer 3, as the string "lis" is the longest common consecutive substring shared by the two strings. The function tests all possible pairs of starting points (starting point for string 1, and starting point for string 2), and measures the match from each. It keeps track of the length of the best match seen, and returns that when finished checking all starting points. The function has bug(s). There are no tests (yet). Your job is to 1) include in this program a sufficient suite of pass/fail tests to thoroughly test the function and expose all error(s). 2) Generate a screenshot that demonstrates your use of a debugger to step through the function. Specifically it should illustrate the execution point of a test at which the function makes (or is about to make) a mistake. 3) fix the code and document your fix(es). Include additional tests if you feel it necessary to thoroughly test the function. You will submit your updated version of this file (along with a separate document containing the screenshot and answered questions). File: test_debug2.py Author: CS @ RIT Author: Dylan Lebedin """ def match(string1, string2): """ Identifies and returns the length of a longest common consecutive substring shared by the two input strings. :param string1: The first string. :param string2: The second string. :return: length of a longest shared consecutive string. """ best_length = 0 # for all possible string1 start points for idx1 in range(0,len(string1)): # for all possible string2 start points for idx2 in range(0,len(string2)): # check if these characters match if string1[idx1] == string2[idx2]: this_match_count = 1 # see how long the match continues while idx1 + this_match_count < len(string1) and idx2 + this_match_count < len(string2)\ and string1[idx1 + this_match_count] == string2[idx2 + this_match_count]: this_match_count += 1 # compare to best so far if this_match_count > best_length: best_length = this_match_count # now return the result return best_length def test_match(): print(match("established", "ballistic")) print(match("care", "care")) print(match("education", "national")) print(match("caesar", "kings")) print(match("xyz", "abc")) test_match()
true
9956f0ea9beb16499bd04955fef4a03c471577e9
BassP97/CTCI
/Hard/surroundedRegions.py
1,912
4.15625
4
""" Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. Example: X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X """ #searches for an edge and, if one is found, returns a list of all Os to skip in the future #if an edge isnt found, it flips all the Os in the current "block" to Xs def searchForEdge(startLoc, board): currLoc = startLoc foundEdge = False stack = [startLoc] locationRecorder = [] while True: if len(stack)!=0: nextLoc = stack.pop() locationRecorder.append(nextLoc) if nextLoc[0]+1>=len(board[0]) or nextLoc[0]-1<=len(board[0]) or nextLoc[1]+1>=len(board) or nextLoc[1]-2<=len(board): foundEdge = True return locationRecorder if board[nextLoc[0]+1][nextLoc[1]] == "0": stack.append((nextLoc[0]+1,nextLoc[1])) if board[nextLoc[0]][nextLoc[1]+1] == "0": stack.append((nextLoc[0],nextLoc[1]+1)) if board[nextLoc[0]-1][nextLoc[1]] == "0": stack.append((nextLoc[0]-1,nextLoc[1])) if board[nextLoc[0]][nextLoc[1]-1] == "0": stack.append((nextLoc[0],nextLoc[1]-1)) else: break for locs in locationRecorder: board[locs[0]][locs[1]] = "X" return [] def surroundedRegions(board): coordinateList = [] toSkip = Set() for x in range(0,len(board)): for y in range(0,len(board[x])): if board[x][y] == "O" and (x,y) not in toSkip: skipLater = searchForEdge((x,y), board) if skipLater!=[]: for i in skipLater: toSkip.add(i) return board print(surroundedRegions[])
true
87a7fea85665c6937299d627e8f48b742e35e359
BassP97/CTCI
/Med/mergeTimes.py
1,123
4.21875
4
""" Write a function merge_ranges() that takes a list of multiple meeting time ranges and returns a list of condensed ranges. For example, given: [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] your function would return: [(0, 1), (3, 8), (9, 12)] Do not assume the meetings are in order. The meeting times are coming from multiple teams. Write a solution that's efficient even when we can't put a nice upper bound on the numbers representing our time ranges. Here we've simplified our times down to the number of 30-minute slots past 9:00 am. But we want the function to work even for very large numbers, like Unix timestamps. In any case, the spirit of the challenge is to merge meetings where start_time and end_time don't have an upper bound. """ def mergeTimes(times): times.sort(key=lambda tup:tup[0]) i = 0 while True: if i >= len(times)-1: break if times[i][1]>=times[i+1][0]: times[i][1] = times[i+1][1] del times[i+1] else: i = i+1 return times print(mergeTimes([[0, 1], [3, 5], [4, 8], [10, 12], [9, 10]]))
true
d6181901165881a52d73d399e7939c1300118b1f
BassP97/CTCI
/Med/reverseLLInplace.py
456
4.25
4
""" Write a function for reversing a linked list. Do it in place. Your function will have one input: the head of the list. Your function should return the new head of the list. Here's a sample linked list node class: """ def revLL(head): if head.next is None: return head curr = head.next prev = head while curr: temp = curr.next curr.next = prev prev = curr curr = temp head = prev
true
838b2e05a36c9c8df569a7c01e631711e6dba849
BassP97/CTCI
/Med/shortEncoding.py
716
4.40625
4
""" Given a list of words, we may encode it by writing a reference string S and a list of indexes A. For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5]. Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character. What is the length of the shortest reference string S possible that encodes the given words? Example: Input: words = ["time", "me", "bell"] Output: 10 Explanation: S = "time#bell#" and indexes = [0, 2, 5]. Note: 1 <= words.length <= 2000. 1 <= words[i].length <= 7. Each word has only lowercase letters. """ def shortEncoding(words):
true
f42be0825f831246d8fb0dae883522ca8281bbba
BassP97/CTCI
/2021 prep/zigZagOrder.py
1,165
4.125
4
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] """ from collections import deque def zigZag(root): if not root: return [[]] currLevel = deque(root) nextLevel = deque() zig = True levels = [] while(currLevel): currLevelContents = [] for node in currLevel: currLevelContents.append(node.value) if zig: if node.left: nextLevel.appendleft(node.left) if node.right: nextLevel.appendleft(node.right) else: if node.right: nextLevel.appendleft(node.right) if node.left: nextLevel.appendleft(node.left) zig = not zig currLevel = nextLevel nextLevel = deque() levels.append(currLevelContents) return levels
true
26c13d5967797a8dbd118c174099395213d62b03
BassP97/CTCI
/Easy/diameterOfBinaryTree.py
636
4.15625
4
""" Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Note - too lazy to implement a real tree so logic will have to do """ class Solution(object): def diameterOfBinaryTree(root): self.ans = 1 def depth(node): if not node: return 0 L = depth(node.left) R = depth(node.right) self.ans = max(self.ans, L+R+1) return max(L, R) + 1 depth(root) return self.ans - 1
true
721a58fcb536b1692f35c9337676f6855200c61e
BassP97/CTCI
/Med/validateBST.py
1,034
4.15625
4
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. The binary tree is stored in an array as follows: """ def main(bst):s for i in range(0, len(bst)): if ((2*i)+1 <= len(bst)-1): if((bst[(2*i)+1] is not None) and (bst[(2*i)+1]>bst[i])): print("The left child of ", bst[i], " ", bst[(2*i)+1], " is greater than its parent") return False if ((2*i)+2 <= len(bst)-1): if(bst[(2*i)+2] is not None and bst[(2*i)+2]<bst[i]): print("The right child of ", bst[i], "-", bst[(2*i)+1], " is greater than its parent") return False return True assert(main([2,1,3]) == True) assert(main([5,1,4,None,None,3,6]) == False)
true
fa876691a18d78065d3af8a9aff74eb8a14ccede
anishLearnsToCode/python-training-1
/solution-bank/loop/solution_8.py
368
4.1875
4
""" WAP that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. """ number = int(input()) is_prime = True for i in range(2, number): if number % i == 0: print('composite number') is_prime = False break if is_prime and number is not 1: print('prime number')
true
909a76f6f26af2922d5de1e25247bf11ed1e805f
anishLearnsToCode/python-training-1
/solution-bank/loop/solution_6.py
210
4.21875
4
""" WAP that prompts the user to input an integer and then outputs the number with the digits reversed. For example, if the input is 12345, the output should be 54321. """ number = input() print(number[::-1])
true
400e46df1e58b1a6914e2e72e63ba6323e9e04f8
josephwalker504/python-set
/cars.py
1,470
4.125
4
# Create an empty set named showroom. showroom = set() # Add four of your favorite car model names to the set. showroom = {"model s", "camaro", "DB11", "B7"} print(showroom) # Print the length of your set. print("length of set",len(showroom)) # Pick one of the items in your show room and add it to the set again. showroom.add("B7") # Print your showroom. Notice how there's still only one instance of that model in there. print(showroom) # Using update(), add two more car models to your showroom with another set. showroom_two = {"Q7", "QX70"} showroom.update(showroom_two) print(showroom) # You've sold one of your cars. Remove it from the set with the discard() method. showroom.discard("camaro") print(showroom) # Acquiring more cars # Now create another set of cars in a variable junkyard. Someone who owns a junkyard full # of old cars has approached you about buying the entire inventory. In the new set, add # some different cars, but also add a few that are the same as in the showroom set junkyard = {"S550", "745Li", "LS460", "B7", "model s", "DB11"} print("intersection", junkyard.intersection(showroom)) # Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom. print("union",showroom.union(junkyard)) # Use the discard() method to remove any cars that you acquired from the junkyard that you do not want in your showroom. showroom.discard("Q7") print("discard", showroom)
true
91edad8c1a7978d660c77fcc7606c71e96773fe8
shereenElSayed/python-github-actions-demo
/src/main.py
885
4.15625
4
#!/usr/bin/python3 import click from src import calculations as calc @click.command() @click.option('--name', prompt='Enter your name', help='The person to greet.') def welcome(name): """Simple program that greets NAME for a total of COUNT times.""" click.echo(f'Hello {name}') @click.command() @click.argument('vals', type=int, nargs=-1, required=True) @click.option('--operation', '-o', required=True, type=click.Choice(['sum', 'multiply'])) def calculate(vals, operation): "Calculate the sum or the multiplication of numbers" if operation == "sum": result = calc.summation(vals) elif operation == "multiply": result = calc.multiply(vals) calc.print_result(operation, result) @click.group() def main(): pass main.add_command(calculate) main.add_command(welcome) if __name__ == '__main__': main()
true
cb14a75694c303c8ced888a2dbb06d95cf424a82
niranjanvl/test
/py/misc/word_or_not.py
611
4.40625
4
#-------------------------- # for each of the given argument # find out if it is a word or not # # Note : Anything not a number is a Word # # word_or_not.py 12 1 -1 abc 123b # 12 : Not a Word # 1 : Not a Word # -1 : Not a Word # abc : Word # 123b : Word #-------------------------- import sys values = sys.argv[1:] def is_number(x): result = False if( len(x) > 1): if x[0] in "-+": x = x[1:] result = x.isdigit() return result for v in values: if not is_number(v): print("{0} : Word".format(v)) else: print("{0} : Not a Word".format(v))
true
737013cf2ef608e5a672dbcbb129137ade18f9e9
niranjanvl/test
/py/misc/gen_odd_even.py
2,505
4.34375
4
''' Generate odd/even numbers between the given numbers (inclusive). The choice and the range is given as command line arguments. e.g., gen_odd_even.py <odd/even> <int> <int> odd/even : can be case insensitive range can be ascending or descending gen_odd_even.py odd 2 10 3, 5, 7, 9 gen_odd_even.py odd 10 2 9, 7, 5, 3 gen_odd_even.py odd 7 15 7, 9, 11, 13, 15 gen_odd_even.py even 2 10 2, 4, 6, 8, 10 gen_odd_even.py even 10 2 10, 8, 6, 4, 2 ''' # Import necessary modules # Read the commmand line argumets # Validate the arguments. If valid, # proceed, otherwise print usage # Generate the result. # Present the result. import sys def print_usage(): print("Usage :") print("gen_odd_even.py <choice> <begin> <end>") print(" choice : odd | even") print(" begin : integer") print(" end : integer") def process_arguments(args): #Process arguments # gen_odd_even.py <odd/even> <int> <int> choice = None begin = None end = None valid_args = True if(len(sys.argv) != 4): print("Invalid number of arguments : {0}". format(len(sys.argv))) valid_args = False if(valid_args): arg = sys.argv[1] if(arg.lower() not in ["odd", "even"]): print("Invalid choice : {0}".format(arg)) valid_args = False else: choice = arg.lower() if(valid_args): arg = sys.argv[2] if(not arg.isdigit()): print("Invalid begin : {0}".format(arg)) valid_args = False else: begin = int(arg) if(valid_args): arg = sys.argv[3] if(not arg.isdigit()): print("Invalid end : {0}".format(arg)) valid_args = False else: end = int(arg) if(valid_args): return choice, begin, end else: print_usage() exit() #return None, None, None def print_result(choice, begin, end, result): #Print the result print("The {0} numbers in the range {1},{2} :". format(choice, begin, end)) print(", ".join([str(x) for x in result])) return None def generate_result(choice, begin, end): result = None #Compute the result # TODO result = [1, 2, 3, 4] return result def main(): choice, begin, end = process_arguments(sys.argv) result = generate_result(choice, begin, end) print_result(choice, begin, end, result) if __name__ == "__main__": main()
true
82ef0d627b03c478a1988b33cc7f81cb04493380
niranjanvl/test
/py/misc/power.py
438
4.28125
4
import sys def pow(x,y): #x to the power of y result = 1 if y > 0: #repetitive multiplication i = 0 while i < y: result *= x i += 1 elif y < 0: #repetitive division i = y while i < 0: result /= x i += 1 else: result = 1 return result x = float(sys.argv[1]) y = float(sys.argv[2]) print(pow(x,y))
true
41099a375c5cbe212a9d4dafe8d98f6fd3c341db
abhishekboy/MyPythonPractice
/src/main/python/04Expressions.py
934
4.125
4
a =12 b =3 print (a+b) # 15 print(a-b) # 9 print(a*b) # 36 print(a/b) # 4.0 print(a//b) #interger division,rounder down to minus infinity print(a % b) #modulo : remainder after interger division print(a**b) #a power b print() #print empty line # in below code a/b can't be used as it will give the float value and range has to have "int" for i in range (1, a//b ): print (i) #operator precedence #PEMDAS (Parenthisis, exponents , multiplication/division, addition/substraction #BEDMAS (brackets, exponents , division/mulitplication, addition/substraction #BODMAS (brackets, order , division/mulitplication, addition/substraction #BIDMAS (brackets, index , division/mulitplication, addition/substraction print (a + b / 3 - 4 * 12) #-35.0 print (a + (b / 3) - (4 * 12)) #-35.0 print ((((a + b) / 3) - 4) * 12) #12.0 print (((a + b) / 3 - 4) * 12) #12.0 print (a / (b * a )/ a)
true
b05d92cbbb972902b5fb5b6ca213408d6d8b77a9
Mjayendr/My-Python-Learnings
/discon.py
1,409
4.375
4
# This program converts distance from feet to either inches, yards or meters. # By: Jay Monpara def main(): print invalid = True while invalid: while True: try: # using try --- except statements for numeric validation distance = raw_input("Enter the distance in feet: ") # prompt user to enter the number to convert from feet to other units. distance = float(distance) # converts string into a float number. print print "Distance= ", distance, "feet." break except: print print "Please enter a numeric number" print print convert_to = raw_input("Enter [i] for inches, [y] for yards or [m] for meters: ") # asking user for the specific requirement. print if convert_to == 'i': inches = distance * 12.0 print " The distance in inches is %0.3f inches = " % inches # string formatting to get the precise answer with 3 decimals. if convert_to =='y': yards = distance/1.50 print "The distance in yards is %0.3f yards. " % yards if convert_to =='m': meters = distance/3.2 print "The distance in meters is %0.3f meters." % meters print more = raw_input("Enter [Y] to convert another distance or [done] to finish: ") # asking user wheather he wants to continue print if more == 'done': invalid = False # breaking the while loop else: continue main()
true
66ce742e5725c7d94a6e119ae5fbe050d6ec5d0e
Mjayendr/My-Python-Learnings
/Temperatur C to F.py
644
4.375
4
#A program to convert temperature from degree celcius to Degree farenheit. # By Jay Monpara def Main(): print Celcius = input("What is the temperature in celcius?") # provoke user to input celcius temperature. Fahrenheit = (9.0/5.0) * Celcius + 32 # process to convert celcius into fahrenheit print print "The temperature is", Fahrenheit,"degrees fahrenheit." # dispalys the output print if Fahrenheit >= 90: # conditonal statement print "It's really hot out there, be careful!" if Fahrenheit <= 30: print "It's too cold out there. Be sure to dress warmly" Main()
true
fc62d6f18d7bd1e3ff07e8640c79e1216999b294
markser/InClassGit3
/wordCount.py
643
4.28125
4
# to run the program # python3 wordCount.py # then input string that we want to retrieve the number of words in the given string def wordCount(userInputString): return (len(userInputString.split())) def retrieve_input(): userInputString = (input('Input a string to determine amount of words: ')) if len(userInputString) < 0: print("Please input a string with characters") else: return userInputString print("Please enter a character ") def main(): userInputString = retrieve_input() print(wordCount(userInputString)) return wordCount(userInputString) if __name__ == "__main__": main()
true
43e89a01a12c0e2d0ccf2731e8edefa283daff37
mageoffat/Python_Lists_Strings
/Rotating_List.py
1,291
4.4375
4
# Write a function that rotates a list by k elements. # For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2]. # Try solving this without creating a copy of the list. # How many swap or move operations do you need? num_list = [1,2,3,4,5,6,7,8,9] # my numbered list val = 0 # value def rotation(num_list): #This is my rotation function temp = 0 # temporaty variable temp = num_list[0] #this will set the temporary variable the first element of the list for x in range(1, len(num_list)): #This for goes through the rest of the numbers num_list[x-1] = num_list[x] #this will switch all the numbers by left num_list[len(num_list)-1] = temp # now make the last list element equal to temp print("How much do you want the list to be rotated?") #print the question val = input("Enter a number") #take input try: #see if it can be an int r = int(val) #make the r an int variable except ValueError: # Error checker print("Sorry that is not a number") #print invalid for i in range(0, r): #lets you rotate it as much as you want rotation(num_list) #Will call the rotation(num_list) print(num_list) #will print the final num_list #This one was difficult for me, even though looking at it now it seems fairly simple
true
13ecd656f3fe1fa576935a259ee42f8c180c22b2
akimmi/cpe101
/poly.py
591
4.1875
4
import math # the purpose of this function is add the values inside the list # list, list --> list def poly_add2(p1, p2): a= p1[0] + p2[0] b= p1[1] + p2[1] c= p1[2] + p2[2] return [a, b, c] # the purpose of this function is to multiply the values inside the list (like a polynomial) by using the distributive method # list, list --> list def poly_mult2(p1,p2): a = p1[0] * p2[0] b = (p1[0] * p2[1]) + (p1[1] * p2[0]) c = (p1[0] * p2[2]) + (p1[1] * p2[1]) + (p1[2] * p2[0]) d = (p1[1] * p2[2]) + (p1[2] * p2[1]) e = p1[2] * p2[2] return [a,b,c,d,e]
true
18d665eba87ae845d1184dd5a6a59dbd81a00286
the-last-question/team7_pythonWorkbook
/Imperial Volume.py
1,838
4.59375
5
# Write a function that expresses an imperial volume using the largest units possible. The function will take the # number of units as its first parameter, and the unit of measure (cup, tablespoon or teaspoon) as its second # parameter. Return a string representing the measure using the largest possible units as the function’s only # result. For example, if the function is provided with parameters representing 59 teaspoons then it should # return the string “1 cup, 3 tablespoons, 2 teaspoons”. # Hint: One cup is equivalent to 16 tablespoons. One tablespoon is equivalent to 3 teaspoons. # one cup - 16 tablespoons # one cup - 48 teaspoons # one tablespoon - 3 teaspoons def main(): unitNumber = int(input("unit Number: ")) unitMeasure = input("unitMeasure: ") answer = largestPossible(unitNumber, unitMeasure) print(answer) def largestPossible(unitNumber, unitMeasure): cup = 0 tablespoons = 0 teaspoons = 0 if(unitMeasure == "cup"): cup = unitNumber return "{0} cup, {1} tablespoons, {2} teaspoons".format(cup, tablespoons, teaspoons) elif(unitMeasure == "tablespoons"): if(unitNumber >= 16 ): cup = unitNumber//16 tablespoons = unitNumber%16 else: tablespoons = unitNumber return "{0} cup, {1} tablespoons, {2} teaspoons".format(cup, tablespoons, teaspoons) elif(unitMeasure == "teaspoons"): if(unitNumber >= 48 ): cup = unitNumber//48 unitNumber = unitNumber - cup*48 if(unitNumber >= 3): tablespoons = unitNumber//3 teaspoons = unitNumber%3 else: teaspoons = unitNumber return "{0} cup, {1} tablespoons, {2} teaspoons".format(cup, tablespoons, teaspoons)
true
82cda6b117d2bc918b8d675313db9f7a5b6314ba
sunyumail93/Python3_StepByStep
/Day02_IfElse/Day02_IfElse.py
653
4.15625
4
#!/usr/bin/python3 #Day02_IfElse.py #Aim: Solve the missing/extra input problem using if/else statement. Use internal function len(), print() #This sys package communicate Python with terminal import sys Total_Argument=len(sys.argv)-1 #sys.argv[0] is the script name if Total_Argument == 0: print("Please input two arguments") elif Total_Argument < 2: print("Argument not enough. Please input two arguments") elif Total_Argument > 2: print("Two many arguments. Please input two arguments") else: First_argument=sys.argv[1] Second_argument=sys.argv[2] #print print("First argument:",First_argument) print("Second argument:",Second_argument)
true
484fdb72be152019168cdf842edc31148ce5eb85
RiqueBR/refreshed-python
/Monday/basics.py
1,157
4.53125
5
# You can write comments using a # (hash) or a block with """ (three double quotes) # Module is a different name for a file # Variables are also called identifiers a = 7 print(a) """ Python won't have major issues with differentiate whole interger and floats """ b = 9.3 print(int(b)) # Take the interger of a float (i.e. 9) print(int(a), b, a+b) c = '5' print(int(c)) # Casting a number/interger from a string """ Data always has a 'type': Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview """ print(type(a), type(b)) # <class 'int'> <class 'float'> d = "I'm a variable" c = True # Note booleans need to start with a capital letter (e.g. T for True and F for False) """ Rules for identifiers 1. Identifiers may use underscore, strings and/or digits 2. First character CANNOT be a digit """ # Math operators ('+, -, *, /') print(3**3) # Means 'to the power of' print ('hello ' * 5) # Divide and truncate print(9/5) # Division print(9//5) # Truncation (i.e. divides and prints to the lowest whole value)
true
f45aa98e5010666f1b0b16da119452b43db0de09
chgeo2000/Turtle-Racing
/main.py
2,104
4.28125
4
import turtle import time import random WIDTH, HEIGHT = 500, 500 COLORS = ['red', 'green', 'blue', 'cyan', 'yellow', 'black', 'purple', 'pink'] def get_number_of_racers(): """ This function asks the user for the number of racers :return: int, number of racers """ while True: number_of_racers = int(input("Give the number of racers (2-8): ")) if 2 <= number_of_racers <= 8: return number_of_racers else: print("Number of racers is not in range: 2-8... Try again!") def init_screen(): """ This function initialise the screen (racetrack). """ screen = turtle.Screen() screen.setup(WIDTH, HEIGHT) screen.title("Turtle Racing!") def create_racer(colors): """ Creates racers and add them to a list :param colors: list, a list of colors :return: list, a list containing the racers """ racers = [] spacing_between_racers = WIDTH // (len(colors) + 1) for i, color in enumerate(colors): racer = turtle.Turtle() racer.color(color) racer.shape('turtle') racer.left(90) racer.penup() racer.setpos((-WIDTH // 2) + (i + 1) * spacing_between_racers, -HEIGHT // 2 + 20) racer.pendown() racers.append(racer) return racers def start_race(colors): """ Simulates the actual race. :param colors: list, a list containing the colors of the participants :return: string, the color of the winning racer """ racers = create_racer(colors) while True: for racer in racers: distance = random.randint(1, 15) racer.forward(distance) x, y = racer.pos() if y >= HEIGHT // 2 - 10: return colors[racers.index(racer)] random.shuffle(COLORS) colors = COLORS[:get_number_of_racers()] # number of colors = number of racers init_screen() print(f"The winner is the turtle with color: {start_race(colors)}!") time.sleep(5) # helps the user to see better who won
true
28b4020cbd612ffc2b7f16ac2ba44e39f5ff4ab8
tomatchison/CTI
/P4LAB1_Atchison.py
661
4.40625
4
# Write a program using turtle to draw a triangle and a square with a for loop # 25 Oct 2018 # CTI-110 P4T1a: Shapes # Tom Atchison # Draw a square and a triangle using turtle. # Use a while loop or a for loop. # Start turtle. import turtle # See turtle on screen. wn=turtle.Screen() # Give turtle optional name. sid=turtle.Turtle() # Give turtle turtle shape and wish ("waifu") was option. sid.shape ("turtle") # Use for loop for the square. for a in range (4): sid.forward (125) sid.left (90) # Use for loop for the triangle. for b in range (3): sid.left (120) sid.forward (125) # Exit turtle. turtle.exitonclick()
true
4a4300f301d976b8bb1b7a96e6727f12c501ec83
tomatchison/CTI
/P4LAB3_Atchison.py
737
4.1875
4
# Create my initials using turtle # 25 Oct 2018 # CTI-110 P4T1b: Initials # Tom Atchison # Start turtle. import turtle import random # See turtle on screen. wn=turtle.Screen() wn.bgcolor("green") # Give turtle optional name. sid=turtle.Turtle() sid.speed(20) # Give turtle shape. sid.shape ("turtle") # create a list of colours sfcolor = ["brown", "red", "orange", "yellow", "magenta"] # create a function to create different size leaves def leaf(size): # move the pen into starting position sid.penup() sid.forward(10*size) sid.left(45) sid.pendown() sid.color(random.choice(sfcolor)) # draw a leaf for i in range(8): branch(size) sid.left(45)
true
54290f9350ad833ee6165b2715d5fdcca2e61b8c
mvanorder/forecast-forecast_old
/overalls.py
1,095
4.125
4
''' general use functions and classes ''' def read_list_from_file(filename): """ Read the zip codes list from the csv file. :param filename: the name of the file :type filename: sting """ with open(filename, "r") as z_list: return z_list.read().strip().split(',') def key_list(d=dict): ''' Write the dict keys to a list and return that list :param d: A python dictionary :return: A list fo the keys from the python dictionary ''' keys = d.keys() key_list = [] for k in keys: key_list.append(k) return key_list def all_keys(d): ''' Get all the dicitonary and nested "dot format" nested dictionary keys from a dict, add them to a list, return the list. :param d: A python dictionary :return: A list of every key in the dictionary ''' keys = [] for key, value in d.items(): if isinstance(d[key], dict): for sub_key in all_keys(value): keys.append(f'{key}.{sub_key}') else: keys.append(str(key)) return keys
true
f2d03a02a7e8c0beeb5ebdf2448a95c6d3cbc18a
zzzzzzzlmy/MyLeetCode
/125. Valid Palindrome.py
440
4.125
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. ''' class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ lst = [c for c in s.lower() if c.isalnum()] return lst == lst[::-1]
true
50abfc53edeb131cbd64dcfca42baca644c3b9c5
Joshcosh/AutomateTheBoringStuffWithPython
/Lesson_15.py
1,665
4.40625
4
# %% # 1 | methods and the index method spam = ['hello', 'hi', 'howdy', 'heyas'] spam.index('hello') # the index method spam.index('heyas') spam.index('asdfasdf') # exception # %% # 2 | in the case a value apears more than once - the index() method returns the first item's index spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] spam.index('Pooka') # %% # 3 | methods to add item to a list spam = ['cat', 'dog', 'bat'] spam.append('moose') # append() adds the item to the end of the list print(spam) spam.insert(1, 'chicken') # add anywhere in the list with insert print(spam) spam.insert(-2, 'kruven') print(spam) # the insert() and append() methods only work on lists # %% spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('bat') print(spam) spam.remove('bat') # will return an error for an item that's not on the list # del spam[0] will delete an item given an index and remove will delete the item where it first appears # %% spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat'] print(spam) spam.remove('cat') print(spam) # %% # 4 | the sort() method spam = [2, 5, 3.14, 1, -7] spam.sort() print(spam) spam.sort(reverse=True) print(spam) spam = ['cats', 'ants', 'dogs', 'badgers', 'elephants'] spam.sort() print(spam) spam.sort(reverse=True) print(spam) # %% # 5 | you cannot sort a list that has both strings and numbers spam = [1, 2, 3, 'Alice', 'Bob'] spam.sort() # %% # 6 | sort() works on strings in an "ascii-betical" order # | hense upper case before lower case spam = ['Alice', 'Bob', 'ants', 'badgers', 'Carol', 'cats'] spam.sort() print(spam) # %% # 7 | true alpha-betical sorting spam = ['a', 'z', 'A', 'Z'] spam.sort(key=str.lower) print(spam)
true
39629ce760dc9f089ba7566febb9c1bfb2c60921
Some7hing0riginal/lighthouse-data-notes
/Week_1/Day_2/challenge2.py
1,305
4.3125
4
""" #### Rules: * Rock beats scissors * Scissors beats paper * Paper beats rock #### Concepts Used * Loops( for,while etc.) * if else #### Function Template * def compare(user1_answer='rock',user2_answer='paper') #### Error Handling * If the user_answer input is anything other than 'rock','paper' or 'scissors' return a string stating 'invalid input' #### Libraries needed * sys - to accept user input.""" def compare(u1, u2): inputVerify = {'rock', 'paper', 'scissors'} if u1 not in inputVerify or u2 not in inputVerify: return "Invalid input! You have not entered rock, paper or scissors, try again." if u1 == u2: return "It's a tie" if u1 == "rock": if u2 == "scissors": return "Rock wins!" elif u2 == "paper": return "Paper wins!" elif u1 == "scissors": if u2 == "rock": return "Rock wins!" elif u2 == "paper": return "Scissors wins!" elif u1 == "paper": if u2 == "scissors": return "scissors wins!" elif u2 == "rock": return "Paper wins!" user1_answer = input("do yo want to choose rock, paper or scissors?") user2_answer = input("do you want to choose rock, paper or scissors?") print(compare(user1_answer, user2_answer))
true
1e7499929fdbe5b458524329ec9b45230a0b31ac
zhast/LPTHW
/ex5.py
635
4.46875
4
name = 'Steven Z. Zhang' age = 18 height = 180 # Centimeters weight = 175 # Pounds eyes = 'Dark Brown' teeth = 'White' hair = 'Brown' # The f character in the function lets you plug in a variable with curly brackets print(f"Let's talk about {name}.") # In this case, its name print(f"He's {height} centimeters tall") print(f"He's {height/2.54} inches tall") print(f"He's {weight} pounds heavy") print("Actually that's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair") print(f"His teeth are usually {teeth} depending on the coffee.") total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.")
true
ff13fde0d24c6d8b175496fe127cdee185588557
MaleehaBhuiyan/pythonBasics
/notes_and_examples/o_two_d_lists_and_nested_loops.py
1,053
4.125
4
#2d lists and nested loops number_grid = [ [1,2,3], [4,5,6], [7,8,9], [0] ] #selecting individual elements from the grid, this gets the number 1, goes by row and then column print(number_grid[0][0]) #nested for loop to print out all the elements in this array for row in number_grid: #this will out put the whole grid, the four rows for col in row: #this will print out each individual number because it is going through each row print(col) #Building a translator def translate(phrase): translation = "" for letter in phrase: if letter.lower() in "aeiou": #.lower() => converts the letters in a string to lowercase if letter.isupper(): #.isupper() => returns true if a letter in a string is upper case or false if a letter is lower case translation = translation + "G" else: translation = translation + "g" else: translation = translation + letter return translation print(translate(input("Enter a phrase: ")))
true
e76afe86418c782f16baf1d54a22b66254bb9fd7
kjmjr/Python
/python/prime2.py
513
4.25
4
#Kevin McAdoo #2-1-2018 #Purpose: List of prime numbers #number is the variable for entering input number = int(input('Enter a number and the computer will determine if it is prime: ')) #the for loop that tests if the input is prime for x in range (2, number, x - 1): if (number % x != 0): print (number, end= ",") print ("is prime because it is only able to divide by 1 and itself") #otherwise program skips to say input is not prime else: print (number, "is not prime")
true
cf5de27304a6ae16c9219c902bba602979340412
kjmjr/Python
/python/list_processing.py
807
4.25
4
#Kevin McAdoo #2-21-2018 #Chapter 7 homework print ('List of random numbers: ') #list of random numbers myList = [22, 47, 71, 25, 28, 61, 79, 57, 89, 3, 29, 41, 99, 86, 75, 98, 4, 31, 22, 33] print (myList) def main(): #command for the max function high = max(myList) print ('Highest number: ', high) #command for the low function low = min(myList) print ('lowest number: ', low) #command for the sum function total = sum(myList) print ('Sum: ', total) #the acccumulator of the loop set final = 0.0 #a for loop is run get the values for value in myList: final += value #command for the len function average = final/ len(myList) print ('Average: ', average) #calling the main function main()
true
6b461d8563f05832a796b79b4a84999447d98436
kjmjr/Python
/algorithm_workbench_problems.py
860
4.40625
4
#Kevin McAdoo #Purpose: Class assignment with if/else statements/ the use of and logical operators #1-24-2018 #3. The and operator works as a logical operator for testing true/false statements #where both statements have to be true or both statments have to be false #4 The or operator works as another logical operator for testing true/false statements #but this time one statement can be true and the other can be false #5 The and operator #7 Here you are asking the user to type in a random number between the following random_number = int(input('Enter a number between 9 and 51: ')) #Here is a if command/ and logical operator for deciding if the input is valid if random_number >= 9 and random_number <= 51: print('valid points') #otherwise here is the command else when the input is not valid else: print ('Invalid points')
true
7300bf857322e6298d6f30e4b15affbcb752afe0
kjmjr/Python
/python/Test 1.py
949
4.125
4
#Kevin McAdoo #2-14-2018 #Test 1 #initializing that one kilometer is equal to 0.621 miles one_kilo = 0.621 #the define main function is calling the def get_kilometers (): and def km_to_miles(): functions def main(): #user inputs his number here and float means the number he/she uses does not have to be a whole number user_input = float(input('Enter a number: ')) km_to_miles(user_input) #the def km_to_miles(): function def km_to_miles(user_input): #the if statement for validating input if user_input >= 0: print ('One kilometer is equal to 0.621') print ('Your input was ', user_input) else: print ('Enter a positive number') #math equation for calculating miles miles = user_input * one_kilo print (user_input, 'is equal to', miles, 'miles') #returns miles return miles #calling main function main()
true
595d3f99cbe522aaaf59a724de0d202dd32bbd44
praveenpmin/Python
/tuples.py
1,370
4.46875
4
# Creating non-empty tuples # One way of creation tup='Python','Techy' print(tup) # Another for doing the same tup= ('Python','Techy') print(tup) # Code for concatenating to tuples tuple1=(0,1,2,3) tuple2=('Python','Techy') # Concatenating two tuples print(tuple1+tuple2) # code fore creating nested loops tuple3=(tup,tuple1,tuple2) print(tuple3) # code to create a tuple with repitition tuple3=('python',)*3 print(tuple3) # code to test slicing tuple1=(0,1,2,3) print(tuple1[1:]) print(tuple1[::-1]) print(tuple1[2:4]) # Code for printing length of the tuple print(len(tuple3)) # Code to convert list to tuple list1 = [0,1,2] print(tuple(list1)) print(tuple('Python')) # Code for creating tuples in a loop tup=('Techy') n=5 for i in range(int(n)): tup=(tup,) print(tup) # Code to demonstrate max(), cmp(), min() def cmp(a, b): return (a > b) - (a < b) list1, list2 = [123, 'xyz'], [456, 'abc'] print(cmp(list1, list2)) print(cmp(list2, list1)) list3 = list2 + [786]; print(cmp(list2, list3)) tuple5=('Python' , 'Techy') tuple6=('Coder',1) ## if ( cmp(tuple1,tuple2) !=0): # print('not the same') # else: ## print('same') # print('Maximum elements in tuples 1,2:'+ str(max(tuple5))+',' + str(max(tuple6))) # print('Minimum elements in tuples 1,2:'+ str(min(tuple5))+',' + str(min(tuple6))) # Delete a tuple tuple4=(0,1) del tuple4 print(tuple4)
true
d9aca0f48d29458fde3174259a840b5ccf535355
praveenpmin/Python
/operatoverload1.py
212
4.4375
4
# Python program to show use of # + operator for different purposes. print(1 + 2) # concatenate two strings print("Geeks"+"For") # Product two numbers print(3 * 4) # Repeat the String print("Geeks"*4)
true
c74901d9e80c204115ead86d6377750fd6ca8609
praveenpmin/Python
/listmethod2.py
521
4.71875
5
# Python code to demonstrate the working of # sort() and reverse() # initializing list lis = [2, 1, 3, 5, 3, 8] # using sort() to sort the list lis.sort() # displaying list after sorting print ("List elements after sorting are : ", end="") for i in range(0, len(lis)): print(lis[i], end=" ") print("\r") # using reverse() to reverse the list lis.reverse() # displaying list after reversing print ("List elements after reversing are : ", end="") for i in range(0, len(lis)): print(lis[i], end=" ")
true
6fa1af52a4965d5b74ed3274a2b0f2e7aafe7192
praveenpmin/Python
/inherit1.py
715
4.34375
4
# Python code to demonstrate how parent constructors # are called. # parent class class Person( object ): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) # child class class Employee( Person ): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) # creation of an object variable or an instance a = Person('Rahul', 886012) # calling a function of the class Person using its instance a.display()
true
c2f887c4e61320c71677beab7e8b81ce285cf8e8
praveenpmin/Python
/Array1.py
2,642
4.46875
4
# Python code to demonstrate the working of array import array # Initializing array with array values arr=array.array('i',[1,2,3]) # Printing original array print("The new created array is:",end="") for i in range(0,3): print(arr[i],end="") print("\r") # using append to insert value to end arr.append(4) # printing appended array print("The appended array is:",end="") for i in range(0,4): print(arr[i],end="") # using insert to value at specific location arr.insert(2,5) print("\r") # printing array after insertion print("The after insertion is:",end="") for i in range(0,5): print(arr[i],end="") print("\r") # using pop to remove value print("The popped element is:",end="") print(arr.pop(2)) #printing array after popping print("The array after popping is:",end="") for i in range(0,4): print(arr[i],end="") print("\r") # using remove() to remove 1st occurance value print("The removed element is:",end="") arr.remove(1) # printing array after removing for i in range(0,3): print(arr[i],end="") print("\r") # For index() # Initializing array with array values arr=array.array('i',[1,2,3,0,2,5]) # Using index() to print index of 1st occurence of 2 print("The index of 1st occurence of 2 is:",end="") print(arr.index(2)) # Using reverse to reverse the array arr.reverse() # Printing array after reversing print("The array after reversing is:",end="") for i in range(0,6): print(arr[i],end="") # Using typecode to print datatype of an array print("The datatype of array is:",end="") print(arr.typecode) # using itemsize to print the itemsize of array print("The itemsize of array is:",end="") print(arr.itemsize) # Using buffer_info to print the buffer info of array print("The buffer info of an array is:",end="") print(arr.buffer_info()) # Initializing array2 with values arr2=array.array('i',[7,8,9]) # Using count() to count occurences of 1 in array print("The occurences of 2 in array is:",end="") print(arr.count(2)) # Using extended() to add arr2 elements to arr1 arr.extend(arr2) print("The modified array is:",end="") for i in range(0,9): print(arr[i],end="") print("\r") # Python code to demonstrate the working of # fromlist() and tolist() # initializing list li = [1, 2, 3] # using fromlist() to append list at end of array arr.fromlist(li) # printing the modified array print ("The modified array is : ",end="") for i in range (0,9): print (arr[i],end=" ") # using tolist() to convert array into list li2 = arr.tolist() print ("\r") # printing the new list print ("The new list created is : ",end="") for i in range (0,len(li2)): print (li2[i],end=" ")
true
ccd1785e19f8fbc77c086eee6c3e774ef363d7ef
HosseinSheikhi/navigation2_stack
/ceiling_segmentation/ceiling_segmentation/UNET/VGG16/VGGBlk.py
2,915
4.34375
4
""" Effectively, the Layer class corresponds to what we refer to in the literature as a "layer" (as in "convolution layer" or "recurrent layer") or as a "block" (as in "ResNet block" or "Inception block"). Meanwhile, the Model class corresponds to what is referred to in the literature as a "UNET" (as in "deep learning UNET") or as a "network" (as in "deep neural network"). So if you're wondering, "should I use the Layer class or the Model class?", ask yourself: will I need to call fit() on it? Will I need to call save() on it? If so, go with Model. If not (either because your class is just a block in a bigger system, or because you are writing training & saving code yourself), use Layer. For more info for subclass layer: https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer This Layer subclass is used to create basic VGG blocks as is defined in readme file """ import tensorflow as tf from tensorflow.keras import layers #TODO we do not need to build function cauase weights are not based on input size class VggBlock(layers.Layer): def __init__(self, layers_num, filters, kernel_size, name, stride=1): """ Defines custom layer attributes, and creates layer state variables that do not depend on input shapes, using add_weight() :param layers_num: number of convolution layers in block :param filters: filters for conv layer :param kernel_size: kernel_size for conv layer :param name: name of the VGG block :param stride: stride for conv layers """ super(VggBlock, self).__init__() self.layers = layers_num self.filters = filters self.kernel_size = kernel_size self.layer_name = name self.stride = stride self.conv_layers = None def build(self, input_shape): """ This method can be used to create weights that depend on the shape(s) of the input(s), using add_weight(). __call__() will automatically build the layer (if it has not been built yet) by calling build() :param input_shape: is fed automatically :return: None """ self.conv_layers = [ layers.Conv2D(self.filters, self.kernel_size, strides=self.stride, padding="same", activation='relu', kernel_initializer='he_normal', name=self.layer_name + "_" + str(i)) for i in range(self.layers)] def call(self, inputs, training=None): """ performs the logic of applying the layer to the input tensors (which should be passed in as argument). passes the input tensors to the conv layers :param inputs: are fed in either encoder or decoder :param training: if its in training mode true otherwise false :return: output of vgg layer """ x = inputs for conv in self.conv_layers: x = conv(x) return x
true
179a2434a5f74bc68dc20538808418e7de18da2c
KiteQzioom/Module-4.2
/Module 4.2.py
372
4.1875
4
def isPalindrome(word): length = len(word) inv_word = word[::-1] if word == inv_word: answer = True else: answer = False print(answer) """ The function isPalindrome takes an input of a string and checks if it is a palindrome. It outputs the answer in boolean as True or False. """ isPalindrome("kajak") isPalindrome("stół")
true
914c64272ef4e56be777df07db7ace7768cf30fc
AsemAntar/codewars_problems
/add_binary/add_binary.py
899
4.28125
4
def add_binary(a, b): sum = a + b return bin(sum)[2:] ''' ==================================================================================================== - writing the same function without the builtin bin method. - Here we will follow a brute force approach. - we follow the following method: --> divide the sum by 2 and ignore the remainder and keep doing this for all the resulted numbers until we reach 1 --> for the original sum and its following division numbers : --> add 1 if the number is odd. --> add 0 if the number is even. ==================================================================================================== ''' def addBinary(a, b): sum = a + b bi = '' while sum != 0: if sum % 2 == 0: bi = '0' + bi sum = sum // 2 else: bi = '1' + bi sum = sum // 2 return bi
true
dd41527eebb329e606afa1c55db40f304c5124f1
AsemAntar/codewars_problems
/create_phone_number/phone_number.py
1,033
4.25
4
# Author: Asem Antar Abdesamee # Problem Description: """ Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. Example: create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) --> (123) 456-7890 """ ''' ============================ My Solution ============================ ''' def create_phone_number(n): if len(n) > 10 or len(n) < 10: print('Please: enter 10 digit list only!') return False else: return f'({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}' print(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])) ''' ============================ Better Solutions ============================ ''' def create_phone_numbers(n): print('Constraints: Enter exactly 10 digits array') if len(n) > 10 or len(n) < 10: print('Please: enter 10 digit list only!') return False return '({}{}{}) {}{}{}-{}{}{}{}'.format(*n) print(create_phone_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
true
8dc831b049dd861d1cf468b8a971833b6d1659fa
ege-erdogan/comp125-jam-session-01
/solutions/problem_07.py
761
4.21875
4
''' COMP 125 - Programming Jam Session #1 November 9-10-11, 2020 -- Problem 7 -- Given a positive integer n, assign True to is_prime if n has no factors other than 1 and itself. (Remember, m is a factor of n if m divides n evenly.) ''' import math n = 5 is_prime = True # There is a whole literature of primality tests. See this Wikipedia article if interested: # https://en.wikipedia.org/wiki/Primality_test # We will do it the "dumb" way. # filter out even numbers if n % 2 == 0: is_prime = False # check if any integer less than sqrt(n) divides n. If so, n is composite. for i in range(3, int(math.sqrt(n))): if n % i == 0: is_prime = False break # can exit loop since no need to check for larger numbers print(is_prime)
true
b7f6dfb5b8cff9d58efcdfa21259ff7a35f6231c
OyvindSabo/Ardoq-Coding-Test
/1/HighestProduct.py
2,834
4.40625
4
#Given a list of integers, this method returns the highest product between 3 of those numbers. #If the list has fewer than three integers, the method returns the product of all of the elements in the list. def highestProduct(intList): negativeList = [] positiveList = [] for integer in sorted(intList): if integer < 0: negativeList.append(integer) else: positiveList.append(integer) #We make sure that each part of the split list is sorted in decending order with regards to the absolute value of the elements. positiveList = list(reversed(positiveList)) #We cannot just assume that the three highest factors will give the highest product. if len(positiveList) >= 3: #We consider the posibility that the product of the two lowest negative integers is higher than the product of the second and third highest positive integers. if len(negativeList) >= 2 and negativeList[0]*negativeList[1] > positiveList[1]*positiveList[2]: return positiveList[0]*negativeList[0]*negativeList[1] #The highest product is accomplished only with positive factors. else: return positiveList[0]*positiveList[1]*positiveList[2] #If there are only one or two positive factors, a product of three integers has to include at least one negative factor. if len(positiveList) >= 1: #If at least one factor has to be negative, it's preferable that two factors are negative. if (len(negativeList)>=2): return positiveList[0]*negativeList[0]*negativeList[1] #If there is only one or zero negative factors available, we have no choice but to multiply the available negative factors with our positive factor. else: product = positiveList[0] for integer in list(reversed(negativeList))[0:2]: product*=integer return product #If there are no positive factors available, the product will be negative. #Therefore, we multiply the three negative factors with the lowest absolute value. #If there are not three negative factors available, we still have no choice but to multiply all negative factors available. else: product = 1 for integer in list(reversed(negativeList))[0:3]: product*=integer return product print(highestProduct([1, 10, 2, 6, 5, 3])) #Should return 300 print(highestProduct([-1, -10, -2, -6, -5, -3])) #Should return -6 print(highestProduct([1])) #Should return 1 print(highestProduct([-1])) #Should return -1 print(highestProduct([])) #Should return 1 print(highestProduct([5, -3, -15, -1])) #Should return 225 print(highestProduct([10, 3, 5, 6, 20])) print(highestProduct([-10, -3, -5, -6, -20])) #Should return -90 print(highestProduct([1, -4, 3, -6, 7, 0])) #Should return 168 print(highestProduct([1, 4, 3, -6, -7, 0])) #Should return 168 print(highestProduct([1, 2, -3, -4])) #Should return 24
true
eb85fed448859e906df0baceda09beee9ce16d15
HaNuNa42/pythonDersleri-Izerakademi
/python kamp notları/while.py
344
4.15625
4
# while number = 0 while number < 6: print(number) number += 1 if number == 5: break if number == 3: continue print("hello world") print("************************") for number in range(0,6): if number == 5: break if number == 3: continue print("hello world")
true
903fa4b1f636803dd1f0d5459926a97e53207380
MingjuiLee/ML_PracticeProjects
/02_SimpleLinearRegression/main.py
1,595
4.125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # Import dataset dataset = pd.read_csv('Salary_Data.csv') print(dataset.info()) # check if there is missing value X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values print(X.shape) print(y.shape) # Splitting dataset into Training and Test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Training the Simple Linear Regression Model on the Training set reg = LinearRegression() reg.fit(X_train, y_train) # Predicting the test result y_pred = reg.predict(X_test) # predicted salary print("Training accuracy: ", reg.score(X_train, y_train)) print("Test accuracy: ", reg.score(X_test, y_test)) # Visualization the Training set and Test set results f1 = plt.figure(1) plt.scatter(X_train, y_train, color='red') plt.plot(X_train, reg.predict(X_train), color='blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('Experience') plt.ylabel('Salary') # plt.ion() # plt.pause(4) # plt.close(f1) plt.show() plt.scatter(X_test, y_test, color='red') plt.plot(X_train, reg.predict(X_train), color='blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Experience') plt.ylabel('Salary') plt.show() # Making a single prediction (for example the salary of an employee with 12 years of experience) print(reg.predict([[12]])) # Getting the final linear regression equation with the values of the coefficients print(reg.coef_) print(reg.intercept_)
true
7fc45fdb496f88a3d9737b2d6ff20b7f77d9ca50
4GeeksAcademy/master-python-exercises
/exercises/013-sum_of_digits/solution.hide.py
296
4.375
4
#Complete the function "digits_sum" so that it prints the sum of a three digit number. def digits_sum(num): aux = 0 for x in str(num): aux= aux+int(x) return aux #Invoke the function with any three-digit-number #You can try other three-digit numbers if you want print(digits_sum(123))
true
0627bc29400b783ed5bf32bd83ba5de53b3e152d
bjarki88/Projects
/prof1.py
525
4.15625
4
#secs = int(input("Input seconds: ")) # do not change this line #hours = secs//(60*60) #secs_remain = secs % 3600 #minutes = secs_remain // 60 #secs_remain2 = secs % 60 #seconds = secs_remain2 #print(hours,":",minutes,":",seconds) # do not change this line max_int = 0 num_int = int(input("Input a number: ")) # Do not change this line while num_int >= 0: if num_int > max_int: max_int = num_int num_int = int(input("Input a number: ")) print("The maximum is", max_int) # Do not change this line
true
20198edc2742d160db704a992dd544f1627d5ac4
B-Tech-AI-Python/Class-assignments
/sem-4/Lab1_12_21/sets.py
680
4.28125
4
print("\n--- Create a set ---") set_one = {1, 3, 5, 7} print(set_one) print(type(set_one)) print("\n--- Add member(s) in a set ---") set_two = {2, 3, 5, 7} print(set_two) print("Adding 11 to current set:", end=" ") set_two.add(11) print(set_two) print(type(set_two)) print("\n--- Remove item(s) from a set ---") to_remove = int(input("Enter number to remove from set: ")) set_two.discard(to_remove) print(set_two) print("\n--- Remove item if it is present in the set ---") to_remove = int(input("Enter number to remove from set: ")) try: set_two.remove(to_remove) print(set_two) except: print("Value not present in set!") print("This is your set:", set_two)
true
43d015b115f8b396ef4fc919ff2ccfa4b737ac97
B-Tech-AI-Python/Class-assignments
/sem-3/Lab_File/exp_1.py
892
4.21875
4
# %% # WAP to understand the different basic data types and expressions print("Integer") int_num = 1 print(int_num, "is", type(int_num)) # %% print("Float") float_num = 1.0 print(float_num, "is", type(float_num)) # %% print("Complex Number") complex_num = 1 + 8j print(complex_num, "is", type(complex_num)) # %% print("Strings") string1 = 'This is a string with (\') an escape character' string2 = "First line.\nA newline.\nAnother newline." string3 = "A string with a \tTAB" string4 = """A multiline string""" string5 = f"This is {int_num} formatted string." string6 = r"Raw\\String" print("\nString 1") print(string1) print("\nString 2") print(string2) print("\nString 3") print(string3) print("\nString 4") print(string4) print("\nString 5") print(string5) print("\nString 6") print(string6) # %% print("Booleans") condition = True if condition: print('Condition is True')
true
ff3134c834c903218aafa07dc0961f138b426015
Bhavyasribilluri/python
/nom.py
219
4.46875
4
#to find largest number list= [] num= int(input("Enter number of elements in the list:")) for i in range(1, num + 1): ele = int(input("Enter elements: ")) list.append(ele) print("Largest element is:", max(list))
true
af0ffc4ef074f2facdcdc90a0c5167dde4caea67
Isisr/assignmentOrganizer
/assignmentOrganizer.py
1,597
4.34375
4
''' Created on Feb 10, 2019 @author: ITAUser ALGORTHM: 1) Make a .json text file that will store our assignments 2) IMport our .json file into our code 3) Create user input for finding assignments 4) Find the users assignments in our data -If the users input is in our data -The users input isn't in our data ''' import json answer = "" while(answer != 'no'): with open("assignments_1.json", "r") as f_r: data = json.load(f_r) print("\n\nWe have assignments of the following dueDates:") for i in data: print("\n" + i) ans = input("1. Find dueDate \n2. Add dueDate \n\n") if ans == '1': assignment = input("Enter the assignment:") print("The dueDate for {} is {}".format(assignment,data.get(assignment, "not in our database"))) elif(ans == '2'): n = int(input("How many assignments do you want to add?")) i = 0 while i < n: print("\n Add assignment",i+1) new_name = input("Enter the assignment:") new_dueDate = input("Enter the dueDate (dd/mm/yyyy):") data[new_name] = new_dueDate with open("assignments_1.json", "w")as f_w: json.dump(data, f_w) print ("assignment added!") i+=1 else: print("\nInvalid Choice!") answer = input("\nDo you want to use this again?(yes/no)")
true
8aedac9cc35461ba6258502c0d04b84c98760bc7
Mybro1968/AWS
/Python/02Basics/example/03Number.py
342
4.1875
4
from decimal import * number1 = int(input("What is the number to be divided? ")) number2 = int(input("What is the number to divided by? ")) print(number1, " / ", number2, " = ", int(number1 / number2)) print(number1, " / ", number2, " = ", float(number1 / number2)) print(number1, " / ", number2, " = ", Decimal(number1 / number2))
true
0f2920f5267dcc5b41d469e363af037264c5d342
Mybro1968/AWS
/Python/05Files/Exercise/01WriteTeams.py
392
4.125
4
# Purpose : writes a file with input for up to 5 names file = open("teams.txt","w") count = int(input("how many teams would you like to enter? ")) #team_name = input("Please enter a team name: ") for n in range(count): if count !=0: team_name = input("Please enter a team name: ") + "\n" file.write(team_name) count = count - 1 file.close()
true
6b06b17601db13468cb668d63df1582e33c5de0b
zzwei1/Python-Fuzzy
/Python-Tutorial/Numerology.py
2,629
4.15625
4
#!usr/bin/python # Function to take input from Person def input_name(): """ ()->int Returns sum of all the alphabets of name """ First_name= input("Enter the first Name") Middle_name= input("Enter the middle Name") Last_name= input("Enter the last Name") count1=count_string(First_name) count2=count_string(Middle_name) count3=count_string(Last_name) return count_num(str(count1+count2+count3)) # Function to take input from person def input_dob(): """ ()->int Returns sum of digits of dob """ dob= input("Enter the DOB in format DD-MM-YYYY") sum1=0 for ch in dob: if ch.isdigit(): sum1+=int(ch) return count_num(str(sum1)) # Function to sum up the string def count_string(str1): """ (str1)->int Returns sum of characters in the string >>>count_string('Amita') 9 >>> count_string('') 0 """ count=0 for ch in str1: if ch=='A' or ch=='J' or ch=='S' or ch=='a' or ch=='j' or ch=='s': count+=1 count = count_num(str(count)) elif ch=='B' or ch=='K' or ch=='T' or ch=='b' or ch=='k' or ch=='t': count+=2 ccount = count_num(str(count)) elif ch=='C' or ch=='L' or ch=='U' or ch=='c' or ch=='l' or ch=='u': count+=3 count = count_num(str(count)) elif ch=='D' or ch=='M' or ch=='V' or ch=='d' or ch=='m' or ch=='v': count+=4 count = count_num(str(count)) elif ch=='E' or ch=='N' or ch=='W' or ch=='e' or ch=='n' or ch=='w': count+=5 count = count_num(str(count)) elif ch=='F' or ch=='O' or ch=='X' or ch=='f' or ch=='o' or ch=='x': count+=6 count = count_num(str(count)) elif ch=='G' or ch=='P' or ch=='Y' or ch=='g' or ch=='p' or ch=='y': count+=7 count = count_num(str(count)) elif ch=='H' or ch=='Q' or ch=='Z' or ch=='h' or ch=='q' or ch=='z': count+=8 count = count_num(str(count)) elif ch=='I' or ch=='R' or ch=='i' or ch=='r' : count+=9 count = count_num(str(count)) else: count+=0 count = count_num(str(count)) return count_num(str(count)) #Function to add numbers def count_num(str1): """ (str)->int Returns numeric value of the sum of digits >>> count_num('56') 2 >>>count_num('34') 7 """ sum1=0 for ch2 in str1: sum1+=int(ch2) if sum1>9: sum1=count_num(str(sum1)) return sum1
true
20b5b26e28989a0bd3d98cdcbeaf3583351eeef5
jkatem/Python_Practice
/FindPrimeFactors.py
431
4.15625
4
# 1. Find prime factorization of a given number. # function should take in one parameter, integer # Returns a list containing all of its prime factors def get_prime_factors(int): factors = list() divisor = 2 while(divisor <= int): if (int % divisor) == 0: factors.append(divisor) int = int/divisor else: divisor += 1 return factors get_prime_factors(630)
true
a677d4055dbe59dec016fe09756f57176d7ddc6c
amanmishra98/python-programs
/assign/14-class object/class object10.py
577
4.1875
4
#2.define a class Account with static variable rate_of_interest.instance variable #balance and accountno. Make function to set values in instance object of account #,show balance,show rate_of_interest,withdraw and deposite. class Account: rate_of_interest=eval(input("enter rate of interest\n")) def info(self,balance,ac): print("balance is %d"%balance,",","account no is %d"%ac) bal=int(input("enter account balance\n")) acc=int(input("enter account no\n")) c1=Account() Account.rate_of_interest=2 print(Account.rate_of_interest) c1.info(bal,acc)
true
8265c18a5344c85d76ca67601d613501cd660841
alessandraburckhalter/Exercises
/ex-07-land-control.py
498
4.1875
4
# Task: Make a program that has a function that takes the dimensions of a rectangular land (width and length) and shows the land area. print("--" * 20) print(" LAND CONTROL ") print("--" * 20) # Create a function to calculate the land area def landArea(width, length): times = width * length print(f"The land area of {w} x {l} is {times}m.") # Ask user to input width and length w = float(input("WIDTH (m): ")) l = float(input("LENGTH (m): ")) # Call function landArea(w, l)
true
5b8fe72fd81b5ebb09d48774e3259dc5b69c05d7
bazerk/katas
/tree_to_list/tree_to_list.py
939
4.25
4
def print_tree(node): if not node: return print node.value print_tree(node.left) print_tree(node.right) def print_list(node, forwards=True): while node is not None: print node.value node = node.right if forwards else node.left def transform_to_list(node, prev=None): if not node: return prev left = node.left right = node.right node.left = prev if prev: prev.right = node prev = transform_to_list(left, node) return transform_to_list(right, prev) class Node(object): def __init__(self, value=None, left=None, right=None): self.left = left self.right = right self.value = value root = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7)) ) print "As tree" print_tree(root) print "transforming" tail = transform_to_list(root) print "As list" print_list(root) print "Backwards" print_list(tail, False)
true
2928aac960286ff38dae1ca85e50c0d0ba653111
cvhs-cs-2017/practice-exam-IMissHarambe
/Loops.py
282
4.34375
4
"""Use a loop to make a turtle draw a shape that is has at least 100 sides and that shows symmetry. The entire shape must fit inside the screen""" import turtle meme = turtle.Turtle() for i in range (100): meme.forward(1) meme.right(3.3) input()
true
fbcc409e7bdf235598c1db86b34f4a5ad4b146b5
furtiveJack/Outils_logiciels
/projet/src/utils.py
1,768
4.21875
4
from enum import Enum from typing import Optional """ Utility methods and variables for the game. """ # Height of the window (in px) HEIGHT = 1000 # Width of the window (in px) WIDTH = 1000 # Shift from the side of the window ORIGIN = 20 NONE = 0 H_WALL = 1 V_WALL = 2 C_WALL = 3 MINO = 4 class CharacterType(Enum): """ Enumeration class to define the possibles types of character """ ARIANE = 0 THESEE = 1 DOOR = 2 MINO_H = 3 MINO_V = 4 class Direction(Enum): """ Enumeration class to define the possible move directions """ UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 def get_dir_from_string(direction: str) -> Optional[Direction]: """ Convert a string representing a direction to its value in the enum Direction class. Valid directions are UP, DOWN, RIGHT, LEFT. Case does not matter. :param direction: a string representing a direction :return: a direction from the Direction class, or None if the parameter is incorrect. """ direction = direction.lower() if direction == "left": return Direction.LEFT if direction == "right": return Direction.RIGHT if direction == "up": return Direction.UP if direction == "down": return Direction.DOWN return None def dir_to_string(direction: Direction) -> str: """ Convert a direction from the Direction class to its string representation. :param direction: the direction to convert :return: a string representing the direction. """ if direction == Direction.LEFT: return "Left" if direction == Direction.RIGHT: return "Right" if direction == Direction.DOWN: return "Down" if direction == Direction.UP: return "Up"
true
69422e8bcf009b6bff2355220506721adc178cad
JasmineEllaine/fit1008-cpp-labs
/3-lab/task1_a.py
1,180
4.25
4
# Task 1a # Read input from user (int greater than 1582) # If leap year print - is a leap year # Else print - is not a leap year def main(): """ Asks for year input and prints response accordingly Args: None Returns: None Raises: No Exceptions Preconditions: None Complexity: O(1) """ year = int(input("Please enter a year: ")) if is_leap_year(year): print("Is a leap year") else: print("Is not a leap year") def is_leap_year(year): """ Checks if a given year is a leap year Args: year (int): year to be checked Returns: True (bool): if leap year False (bool): if not a leap year Raises: No exceptions Precondition: year > 1582 Complexity: O(1) """ if (year % 100 == 0): if (year % 400 == 0): return True else: return False elif (year % 4 == 0): return True else: return False if __name__ == "__main__": main() # if (year%400 == 0) or ((year%4 == 0) and not (year%100 == 0)): # return True # return False
true
bec90b0361b19f66e15bfef6d5abacd2bddc9970
msm17b019/Project
/DSA/Bubble_Sort.py
677
4.1875
4
def bubble_sort(elements): size=len(elements) swapped=False # if no swapping take place in iteration,it means elements are sorted. for i in range(size-1): for j in range(size-1-i): # (size-i-1) as last element in every iteration is getting sorted. if elements[j]>elements[j+1]: elements[j],elements[j+1]=elements[j+1],elements[j] swapped=True if not swapped: break return elements if __name__=='__main__': test=[ [23,5,4,6,34,64,7,84,24], [45,3,4,5,23,54,7,4,6], [9,7,45,3,65,5,4,6,43] ] for element in test: print(bubble_sort(element))
true
bb05a9044f8fdaca1ca78ec9d7f63f2840cc9866
hampusrosvall/leetcode
/merge_linked_lists.py
2,340
4.28125
4
""" P C l1: 1 -> 6 -> 7 -> 8 N l2: 2 -> 3 -> 4 -> 5 -> 9 -> 10 The idea is to insert the nodes of the second linked list into the first one. In order to perform this we keep track of three pointers: 1) prevNode (points to the previous node in the insertion list) 2) currentNode (points to the current node in the insertion list) 3) nodeToInsert (points to the current node in the list to insert from) At each iteration, we compare the value of the currentNode to the nodeToInsert. If currentNode.value < nodeToInsert.value we increment the currentNode and prevNode pointers, as the currentNode is in correct position If currentNode.value > nodeToInsert.value we insert the nodeToInsert behind currentNode and update pointers. When we are done, we can check if we have any more nodes to insert in the insertion list. We simply validate this by checking the content of nodeToInsert and point currentNode.next to whatsever left in nodeToInsert. """ class ListNode: def __init__(self, value): self.value = value self.next = None def print_values(head): while head: print(head.value) head = head.next def mergeLinkedLists(headOne, headTwo): prevNode, currentNode, nodeToInsert = None, headOne, headTwo while currentNode and nodeToInsert: if currentNode.value < nodeToInsert.value: # increment the pointers prevNode = currentNode currentNode = currentNode.next else: if prevNode: prevNode.next = nodeToInsert prevNode = nodeToInsert nodeToInsert = nodeToInsert.next prevNode.next = currentNode if not currentNode: prevNode.next = nodeToInsert return headOne if headOne.value < headTwo.value else headTwo first = ListNode(1) first.next = ListNode(3) second = ListNode(2) second.next = ListNode(4) headOne = ListNode(2) headOne.next = ListNode(6) headOne.next.next = ListNode(7) headOne.next.next.next = ListNode(8) headTwo = ListNode(1) headTwo.next = ListNode(3) headTwo.next.next = ListNode(4) headTwo.next.next.next = ListNode(5) headTwo.next.next.next.next = ListNode(9) headTwo.next.next.next.next.next = ListNode(10) head = mergeLinkedLists(headOne, headTwo) print_values(head)
true
b9a617f0880e2997d7319464c1c7c5aa7ff3395e
blueclowd/leetCode
/python/1042-Flower_planting_with_no_adjacent.py
1,257
4.1875
4
''' Description: You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers. paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y. Also, there is no garden that has more than 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. ''' from collections import defaultdict class Solution: def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: graph = defaultdict(list) for node_1, node_2 in paths: graph[node_1 - 1].append(node_2 - 1) graph[node_2 - 1].append(node_1 - 1) colors = [0] * N for node in range(N): adj_nodes = graph[node] used_colors = [colors[adj_node] for adj_node in adj_nodes] for i in range(1, 5): if i not in used_colors: colors[node] = i break return colors
true
0b23ebf4c19a7d6dc6fbea5e184b61d1d6116854
blueclowd/leetCode
/python/0101-Symmetric_tree.py
1,458
4.15625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # Iterative class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True queue = [root.left, root.right] while queue: node_1 = queue.pop(0) node_2 = queue.pop(0) if not node_1 and not node_2: continue if not node_1 or not node_2: return False if node_1.val == node_2.val: queue.append(node_1.left) queue.append(node_2.right) queue.append(node_1.right) queue.append(node_2.left) else: return False return True # Recursive class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True return self.is_mirror(root.left, root.right) def is_mirror(self, node_1, node_2): if not node_1 and not node_2: return True if not node_1 or not node_2: return False return node_1.val == node_2.val and self.is_mirror(node_1.left, node_2.right) and self.is_mirror(node_1.right, node_2.left)
true
c77a6dd6090ddd15e50741841a66cb05e8db771a
shashbhat/Internship_Data_Analytics
/Assignment/Day 1/6.py
387
4.375
4
''' 6. Write a program to accept a number from the user; then display the reverse of the entered number. ''' def reverse_num(num): ''' Reverses a number and returns it. ''' rev = 0 while num != 0: rev = rev * 10 + num % 10 num = num // 10 return rev num = int(input("Enter a number: ")) rev = reverse_num(num) print(f"Reverse of {num} is {rev}")
true
4ac7158db07e3d5ce9de5125b646eee70fec24b3
milind1992/CheckIO-python
/Boolean Algebra.py
1,713
4.5
4
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence") ​ def boolean(x, y, operation): ​ if operation=="conjunction": #"conjunction" denoted x ∧ y, satisfies x ∧ y = 1 if x = y = 1 and x ∧ y = 0 otherwise. return x*y ​ elif operation=="disjunction": #"disjunction" denoted x ∨ y, satisfies x ∨ y = 0 if x = y = 0 and x ∨ y = 1 otherwise. return x or y ​ elif operation=="implication": #"implication" (material implication) denoted x→y and can be described as ¬ x ∨ y. If x is true then the value of x → y is taken to be that of y. But if x is false then the value of y can be ignored; however the operation must return some truth value and there are only two choices, so the return value is the one that entails less, namely true. return not_(x)or y ​ elif operation=="exclusive": #"exclusive" (exclusive or) denoted x ⊕ y and can be described as (x ∨ y)∧ ¬ (x ∧ y). It excludes the possibility of both x and y. return (x+y)%2 elif operation=="equivalence": #"equivalence" denoted x ≡ y and can be described as ¬ (x ⊕ y). It's true just when x and y have the same value. return not_(boolean(x,y,"exclusive")) ​ ​ def not_(x): if x is 0 : return 1 else: return 0 ​ if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert boolean(1, 0, "conjunction") == 0, "and" assert boolean(1, 0, "disjunction") == 1, "or" assert boolean(1, 1, "implication") == 1, "material" assert boolean(0, 1, "exclusive") == 1, "xor" assert boolean(0, 1, "equivalence") == 0, "same?"
true
47ad2084d09c9be3ffae5d20f34cac14b96f85e3
CodeAltus/Python-tutorials-for-beginners
/Lesson 3 - Comments, input and operations/lesson3.py
269
4.21875
4
# Taking user input dividend = int(input("Enter dividend: ")) divisor = int(input("Enter divisor: ")) # Calculation quotient = dividend // divisor remainder = dividend % divisor # Output results print("The quotient is", quotient) print("The remainder is", remainder)
true
c86b788a0d4bab42f59fde14c1d3a35b034171a1
GedasLuko/Python
/Chapter 5 2/program52.py
673
4.15625
4
#Gediminas Lukosevicius #October 8th, 2016 © #import random function #build numbers function first #create accumulator #create a count in range of five numbers #specify five numbers greater than ten but less than thirty #create a total for five numbers assignment #display five random numbers and total as specified #build main function and call numbers function #call main function import random def main(): numbers() def numbers(): total = 0.0 for count in range(5): number = random.randint(11,29) total = total + number print(number, end = ' ') print() print('The total is', format(total, '.0f')) main()
true
1527cdb327c0d59506154813384d32718ceb1864
GedasLuko/Python
/chapter 2/program24.py
587
4.5
4
#Gediminas Lukosevicius #September 1st, 2016 © #This program will convert an improper fraction to a mixed number #Get Numerator #Get Denominator #Convert improper fraction to mixed number #Dislpay the equivalent mixed number with no space either side of the / symbol numerator = int(input('Please enter the numerator: ')) denominator = int(input('Please enter the denominator: ')) whole_number = int(numerator // denominator) remainder_fraction = int(numerator % denominator) print('The mixed number is: ', format(whole_number), ' and ', format(remainder_fraction), '/', format(denominator),sep='')
true
53c1bd002b7c652df805e6ea2cd1991746508aef
GedasLuko/Python
/write_numbers.py
510
4.375
4
#Gediminas Lukosevicius #October 24th, 2016 © #This program demonstrates how numbers must be converted to strings before they are written to a text file. def main(): outfile = open('numbers.txt', 'w') num1 = int(input('Enter a number: ')) num2 = int(input('Enter another number: ')) num3 = int(input('Enter another number: ')) outfile.write(str(num1) + '\n') outfile.write(str(num2) + '\n') outfile.write(str(num3) + '\n') outfile.close() print('Data written to numbers.txt') main()
true
25e2f64d1c80edac30dfb37bf57035cc2b3d1e1d
zsoltkebel/university-code
/python/CS1028/practicals/p2/seasons.py
868
4.25
4
# Author: Zsolt Kébel # Date: 14/10/2020 # The first day of seasons of the year are as follow: # Spring: March 20 # Summer: June 21 # Fall: September 22 # Winter: December 21 # Display the season associated with the date. month = "Mar" date = 23 if month == "Jan" or month == "Feb": print("Winter") elif month == "Mar": if date < 20: print("Winter") else: print("Spring") elif month == "Apr" or month == "May": print("Spring") elif month == "Jun": if date < 21: print("Spring") else: print("Summer") elif month == "July" or month == "Aug": print("Summer") elif month == "Sep": if date < 22: print("Summer") else: print("Fall") elif month == "Oct" or month == "Nov": print("Fall") elif month == "Dec": if date < 21: print("Fall") else: print("Winter")
true
cacbf029b45a960fa30b175e3f0bafe66ebfaab6
gschen/where2go-python-test
/1200-常用算法/其他/111_二叉树的最小深度.py
1,288
4.15625
4
# https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/ from typing import * import unittest # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: result = [] if root == None: return result queue = [] queue.append(root) while len(queue) != 0: level_len = len(queue) level_all = [] for i in range(level_len): node = queue.pop(0) level_all.append(node.val) if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right) result.insert(0, level_all) return result class Test(unittest.TestCase): def test_01(self): n3, n9, n20, n15, n7 = [TreeNode(i) for i in [3, 9, 20, 15, 7]] n3.left, n3.right = n9, n20 n20.left, n20.right = n15, n7 self.assertEqual(Solution().levelOrderBottom(n3), [ [15, 7], [9, 20], [3] ]) if __name__ == '__main__': unittest.main()
true
5253599aa98ef4900197ef5616ceb94936048fe2
K23Nikhil/PythonBasicToAdvance
/Program13.py
507
4.125
4
#Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. startIndex = 0 endIndex = 10 FabSer = [] i = 1 if startIndex ==1: FabSer.append(startIndex) FabSer.append(startIndex) else: FabSer.append(startIndex) FabSer.append(startIndex + 1) while i < endIndex: sum = FabSer[i] + FabSer[i -1] FabSer.append(sum) i = i+1 print(FabSer)
true
8929a0b3e7d0dcbf04f6bc907de9f9aece86c9d1
spoorthyandhe/project-98
/game.py
885
4.34375
4
import random print(" Number guessing game :") number = random.randint(1,9) chances = 0 print ("Guess a number (between 1 and 9): ") # while loop to count the umbers of changes while chances <5: guess = int(input("Enter your guess: ")) #compare the user enteres number with the number if guess == number: #if number entered by user is same as the generated #number by randint function then break from loop using loop #control statement "break" print(" Congatulation YOU WON!!!") break elif guess < number: print("your guess was too low: guess a number higher than ",guess) else: print("your guess was too high: guess a number lower than ",guess) chances = chances+1 #check whether the user gussed the correct number if not chances <5 : print("YOU LOSE!!! The number is",number)
true
ef05347532b0eab4ddede67797e8a39725fefc07
Mfrakso/Week3
/FiberOptic If_Statements.py
1,895
4.4375
4
''' File: FiberOptic If_Statments.py Name: Mohammed A. Frakso Date: 14/12/2019 Course: DSC_510 - Introduction to Programming Desc: Programe calculates the need of fiber optic cable and evaluate a bulk discount for a user Usage : This program is built to take the 'Company Name' and 'required length(in feet)' of optic cable for installation as input. Then Calculate the total cost that will vary upon the length of optic cable requested for installation and printing receipt for the total cost for installation to user. ''' # Display Welcome Message message = "Welcome to the store" print(message) # Retrieve the company name companyName = input('What is your company name? \n') print('Your company name is', companyName) # Retrieve the number of fiber optic prompt = 'What is the number of feet of fiber optic cable to be installed? \n' numberFeet = float(input(prompt)) int(numberFeet) # Calculate the installation cost of fiber optic # Create a variable cost = 0.87 # Print Number feet print(' The number of feet of fiber optic is', numberFeet) print(numberFeet) # cable cost will change based on length input by user if 100 < numberFeet <= 250: # If Cabal length is between 101 and 250 then price is 0.80 cost = 0.80 elif 250<numberFeet <= 500: # If Cabal length is between 251 and 500 then price is 0.70 cost = 0.70 elif numberFeet > 500: # If Cabal length is more than 500 then price is 0.5 cost = 0.50 else: cost = 0.87 # If Cabal length is less than 100 then price is 0.87 # Calculate the installation cost of fiber optic totalCost = (numberFeet * cost) print("The installation cost is", totalCost) # Printing out the receipt print('Printing Receipt for Company: ', companyName) print('Length of Fiber optic Cable in Feet: ', numberFeet) print('Cable installation Cost Calculation:', numberFeet,'ft x $',cost) print('Total Cost: $', totalCost )
true
ea17d0d98e64c444106d0c018c8ac171a84c3b32
pangyang1/Python-OOP
/Python OOP/bike.py
794
4.15625
4
class Bike(): """docstring for Bike.""" def __init__(self,price,max_speed,miles): self.price = price self.max_speed =max_speed self.miles = 0 def displayinfo(self): print "The price is $" + str(self.price) + ". The max speed is " + str(self.max_speed) + ". The total miles are " + str(self.miles) def ride(self): self.miles +=10 print "Riding" return self def reverse(self): if self.miles >5: self.miles -=5 print "Reversing" return self bike1 = Bike(200, "25mph",0) bike2 = Bike(100, "20mph",0) bike3 = Bike(400, "30mph",0) bike1.ride().ride().ride().reverse().displayinfo() bike2.ride().ride().reverse().reverse().displayinfo() bike3.reverse().reverse().reverse().displayinfo()
true
b38b3a2082f4da3dc269982aab04ac935a5e96bd
IeuanOwen/Exercism
/Python/triangle/triangle.py
1,087
4.25
4
import itertools def valid_sides(sides): """This function validates the input list""" if any(side == 0 for side in sides): return False for x, y, z in itertools.combinations(sides, 3): if (x + y) < z or (y + z) < x or (z + x) < y: return False else: return True def is_equilateral(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x == y and x == z: return True else: return False def is_isosceles(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x == y or y == z or x == z: return True else: return False def is_scalene(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x != y and x != z and y != z: return True else: return False
true
9f865f967c9a164b95c49e5f84b17d5d0204c5f8
IeuanOwen/Exercism
/Python/prime-factors/prime_factors.py
428
4.1875
4
"""Return a list of all the prime factors of a number.""" def factors(startnum): prime_factors = [] factor = 2 # Begin with a Divisor of 2 while startnum > 1: if startnum % factor == 0: prime_factors.append(factor) startnum /= factor # divide the startnum by the factor else: # If the divisor is not a factor increase it by 1 factor += 1 return prime_factors
true
375e0bf125558618bb74238ec40264ce59ca9344
Jeevan-Palo/oops-python
/Polymorphism.py
1,050
4.5
4
# Polymorphism achieved through Overloading and Overriding # Overriding - Two methods with the same name but doing different tasks, one method overrides the other # It is achieved via Inheritance class Testing: def manual(self): print('Automation Tester with 5 years Experience') class ManualTest(Testing): def manual(self): super().manual() print('Manual Tester with 5 years Experience') test = ManualTest() test.manual() # Method Overloading # Python does not support method overloading by default # Method overloading in Python is that we may overload the methods but can only use the latest defined method. # The below example object will call same method with and without parameter class Testing_MOL: def Hello(self, testing=None): if testing is not None: print('Hello ' + testing) else: print('Hello Manual Tester') # Create an instance obj = Testing_MOL() # Call the method obj.Hello() # Call the method with a parameter obj.Hello('Automnation Tester')
true
cc50929915eae260da1160b515b30cbea4268108
MicheSi/Data-Structures
/binary_search_tree/sll_queue.py
2,213
4.1875
4
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList2: def __init__(self): # first node in the list self.head = None self.tail = None def add_to_head(self, value): new_node = Node(value) if not self.head and not self.tail: self.head = new_node self.add_to_tail = new_node else: new_node.set_next(self.head) self.head = new_node def add_to_tail(self, value): # regardless of if the list is empty or not, we need to wrap the value in a Node new_node = Node(value) # what if the list is empty? if not self.head and not self.tail: self.head = new_node self.tail = new_node # what if the list isn't empty? else: self.tail.set_next(new_node) self.tail = new_node def contains(self, value): current = self.head if current is None: return while current is not None: if current.get_value() == value: return True current = current.get_next() return False def remove_head(self): # what if the list is empty? if not self.head and not self.tail: return # what if it isn't empty? else: # we want to return the value at the current head value = self.head.get_value() if self.head == self.tail: self.head = None self.tail = None return value else: self.head = self.head.get_next() return value def get_max(self): current = self.head value = current.value if not self.head and not self.tail: return if self.head == self.tail: return current.value while current.get_next() is not None: if current.value > value: value = current.value current = current.get_next() else: current = current.get_next return value
true
572e08a21a64a898d60e2bd26bec4f350da44d65
his1devil/lintcode-note
/flattenlist.py
449
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): """ Given a list, each element in the list can be a list or integer. Flatten it into a simply list with integers. 递归 """ def flatten(self, nestedList): result = [] if isinstance(nestedList, int): return [nestedList] for i in nestedList: result.extend(self.flatten(nestedList)) return result
true
cd54caff7a61f615fd855cc9a012871652fb4c2a
his1devil/lintcode-note
/rotatestring.py
1,055
4.25
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): """ Given a string and an offset, rotate string by offset. (rotate from left to right) offset=2 => "fgabcde" """ def rotateString(self, s, offset): # 防止offset越界,offset 对len(s)取模 if s is None or len(s) == 0: return -1 offset = offset % len(s) first = s[:len(s) - offset] end = s[len(s) - offset:] s = first[::-1] + end[::-1] s = s[::-1] return s # 借助mutable structure 原地变换字符串 因为字符串不可变 def rotateString2(self, s, offset): if s is None or len(s) == 0: return -1 offset = offset % len(s) self.reverse(s, 0, len(s) - offset - 1) self.reverse(s, len(s) - offset, len(s) - 1) self.reverse(s, 0, len(s) - 1) def reverse(self, _str, start, end): while start < end: _str[start], _str[end] = _str[end], _str[start] start += 1 end -= 1
true
6c78661c73b2892e248eff64a7395e6b1e84359b
paulmagnus/CSPy
/mjenkins-programs/windchill.py
447
4.3125
4
def windChill(): print 'Welcome to the windchill calculator!' temperature = input("Enter the temperature: ") windspeed = input("Enter the wind speed: ") windchill = 35.74 + (0.6215 * temperature) - (35.75 * (windspeed ** 0.16)) + (0.4275 * temperature * (windspeed ** 0.16)) print 'At ' + str(temperature) + ' degrees, with a wind speed of ' + str(windspeed) + ' miles per hour, the windchill is: ' + str(windchill) + ' degrees' windChill()
true
fd8809831149570c0750c8d612f2bd99c0d31479
katyduncan/pythonintro
/lesson2/8IntegersFloats.py
409
4.1875
4
# Check data type print(type(3)) print(type(4.3)) # whole number float print(type(4.)) # operation involving int and float always results in float print(3 + 2.5) # cut decimal off float to convert to int print(int(49.7)) # 49 no rounding occurs # add .0 to convert int to float print( float(3520 + 3239)) # 6759.0 # NOTE floats are approx, 0.1 is actually slightly more print(.1 + .1 + .1 == .3) # False
true
a57f59a87013bed7f79d9524af8858e8c48c024d
Bumskee/-Part-2-Week-2-assignment-21-09-2020
/Problem 2.py
483
4.15625
4
"""Problem 2 finding the average score tests of 3 students""" #Assigning the value for the student scores student1 = 80 student2 = 90 student3 = 66.5 #Function for finding the average out of those student scores def findAverage(student1, student2, student3): scoreAverage = (student1 + student2 + student3) / 3 return scoreAverage #Assigning the value to the average variable average = findAverage(student1, student2, student3) #prints the value of average print(average)
true
63d1c825ba44f094558ed37759d9f9d018a7a484
samanthaalcantara/codingbat2
/Logic-1/caught_speeding.py
758
4.28125
4
""" Date: 06 12 2020 Author: Samantha Alcantara Question: You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. """ #Answer def caught_speeding(speed, is_birthday): speed_adj = 0 if (is_birthday == True): speed_adj = 5 if speed < 61 + speed_adj: return 0 if speed < 81 + speed_adj: return 1 return 2 # no ticket small ticket big ticket # 0 <= Speed < 61 61<= Speed < 81 Speed >= 81
true
19a6de32c4a6c72a5dbd89ad23600d9de5893ce6
peterhchen/runBookAuto
/code/example/01_Intro/05_Age.py
539
4.4375
4
#!/usr/bin/python3 # Display different format based on age. # Age 1 to 18: Important # Age 21, 50, or >= 65: Important # All othera Ages: Not important # Get age and store in age age = eval (input('Enter age: ')) # if age >= 1 and <= 18: important if (age >= 1) and (age <= 18): print ("Important") # if age == 21 or 50: important elif (age == 21) or (age == 50): print ("Important") # if age < 65, convert the true to false. elif not(age < 65): print ("Important") # else not import. else: print ("Not Important")
true