blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
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
8cc0098cb8f8632608a151d3b7767d43fd5bd03b
pacheco-andres/nuevos-archivos-
/venta_libros.py
912
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- books = {"matematicas": 100, "espaniol": 90, "biologia": 70, "historia": 80, "fisica":110} def show_books(): counter = 1 print("VENTA DE LIBROS") for book in books.keys(): print ('%s.- %s') %(counter, book) counter += 1 def get_input(): try: book_id = int(input("ingresa el numero del libro: ")) return book_id except: return 0 def find_book(): book_id = get_input() book_names_array = books.keys() if book_id > 0 and book_id <= len(book_names_array): book_key = book_names_array[book_id-1] print('Libro: %s Costo: $%s') %(book_key, books[book_key]) #en cada %s se guarda un argumento en este caso en el 1 es book_key elif book_id == 0: print("Porfavor ingresa un numero") else: print("No se encontro ningun libro") show_books() find_book()
false
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
86555752f784eec78689d6fd691753ed4a9f8cb9
yoavbargad/self.py-course-python
/Unit 4/unit 4 - 4.2.4.py
219
4.21875
4
# Python Course - unit 4 # 4.2.4 import calendar day_list = list(calendar.day_name) date = input('Enter a date (dd/mm/yyyy):\t') day = calendar.weekday(int(date[6:]), int(date[3:5]), int(date[:2])) print(day_list[day])
false
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
a298b6e9d0490deeef0a2688b072d88f686a2ddc
anishLearnsToCode/python-training-1
/day_1/print_funtion.py
273
4.25
4
""" Time Complexity: O(1) Space Complexity: O(1) """ print('hello world', end=' ** ') print('this is amazing!!!') print('i am on top of the world') print('\ni am on a new line\n\n', end='***') print('\tsomething\ni am once again on a new line\t\t', end='this is the end')
false
8d2b67127264b57599932c5c94d8cd81b3df0e3c
apisourse/netology_python
/1-06/1-6__init__.py
943
4.1875
4
class Car: # pass #просто заглушка, если класс пустой, если не пустой, то писать не нужно # Создаем атрибуты класса color = 'black' engine_volume = 1500 year = 2018 fuel = 0 #l position = 0 speed = 0 #km/h status = 'stopped' coords = [0, 0, 0] def __init__(self, fuel, position): self.coords = [0, 0, 0] self.fuel = fuel self.position = position Car_01 = Car(101, 102) print(Car_01.__dict__) print(Car_01.fuel) print(Car_01.position) print(Car_01.coords) print(Car_01.__dict__) Car_02 = Car(201, 202) Car_02.coords[2] = 1 print(Car_02.fuel) print(Car_02.position) print(Car_02.coords) print(Car_02.__dict__) # ИТОГ: Если мы помещаем изменяемые функции в атрибуты, то с ними можно работать индивидуально в рамках объектах
false
5a5773da9a58a0f0688fbd7730ee89ff1907a226
virensachdev786/my_python_codes
/pyDS.py
992
4.25
4
def main(): #LIST # print("Enter the size of list") # n = int(input()) # a = list() # # for i in range(n): # print("enter elements of list: ") # c = int(input()) # a.append(c) # # print("the entered list is: {0} ".format(a)) #Tuple # print("Enter size of tuple: ") # t = int(input()) # v = tuple() # # for i in range(t): # print("Enter elements of tuple: ") # v = list(v) # m = int(input()) # v.append(m) # # v = tuple(v) # # print("the entered tuple is: {0}".format(v)) #Dictionary mydict = dict() for i in range(2): print("Enter first name : ") firstname = input() print("Enter Last name : ") lastname = input() mydict[firstname] = lastname print("my dict is {0}".format(mydict)) for key,value in mydict.items(): print("{0} {1}".format(key,value)) if __name__=="__main__": main()
false
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
19d5309eeeb5429350a3e3dae8368c265c4d3034
zhangwhitemouse/pythonDataStructure
/datastructure/python-data-structure-linkedlist/reverselinkedlist.py
2,242
4.4375
4
""" 反转链表 问题分析:反转链表就是将单链表的每个节点的指针域指向前一个节点,头节点特殊一点,它需要指向None 算法分析:第一反应就是暴力解法呀,就是将单链表的每个元素拿出来放入列表,然后再构建一遍链表(被自己蠢到了哈哈哈)。 然后想了想发现我用两个变量,一个存储当前节点,一个存放当前节点的前一个节点不就行了 """ # class Solution: # def reverseList(self, head): # prev = None # curr = head # while curr != None: # temp = curr.next #存储当前节点的下一个节点 # curr.next = prev #将当前节点的指针域指向前一个节点 # prev = curr #移动新链表的头节点 # curr = temp #当前节点往下移动 # return prev """ 还有一种递归的方法,但是由于我递归理解的比较差,暂时脑袋还转不过来 等我转好了,我再写哦 时间一分一秒的过去,就这样一直过了一下午,灵光乍现,懂了 """ class Solution: def reverseList(self, head): if head == None or head.next == None: return head new_linkedlist = self.reverseList(head.next) head.next.next = head head.next = None return new_linkedlist """ 反转链表指定位置到另外位置的元素,之前都是无脑翻,现在要从m到n。 算法分析:首先我得找到开始的节点,然后从开始的节点进行链表反转,一直反转到结束的位置,然后将整个链表连接起来 """ class Solution: def reverseBetween(self, head, m, n): prev = None cur = head if not head: return head while m > 1: prev = cur cur = cur.next m -= 1 n -= 1 con = prev tail = cur while n: temp = cur.next cur.next = prev prev = cur cur = temp n -= 1 if con: con.next = prev else: head = prev tail.next = cur return head
false
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
a092b1273accd648d829f7b7f8321e3469d75f66
romanPashnitskyi/PythonProjects
/task3_3.py
281
4.125
4
#! /usr/bin/env python3 import sys weight = input("Введіть Вашу вагу в кг: ") height = input("Введіть Ваш зріст в метрах : ") weight = float(weight) height = float(height) print('Індекс Маси Тіла - ', + weight / height** 2)
false
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
20d57d8eab474dac7e2c0b4e79713cfea581dadc
MaleehaBhuiyan/pythonBasics
/notes_and_examples/c_strings.py
791
4.28125
4
#Working with strings print("Giraffe Academy") print("Giraffe\nAcademy") print("Giraffe\"Academy") print("Giraffe\Academy") phrase = "Giraffe Academy" print(phrase + " is cool") phrase = "Giraffe Academy" print(phrase.lower()) phrase = "Giraffe Academy" print(phrase.upper()) phrase = "Giraffe Academy" print(phrase.isupper()) phrase = "Giraffe Academy" print(phrase.upper().isupper()) phrase = "Giraffe Academy" print(len(phrase)) phrase = "Giraffe Academy" print(phrase[0]) phrase = "Giraffe Academy" print(phrase.index("G")) phrase = "Giraffe Academy" print(phrase.index("a")) phrase = "Giraffe Academy" print(phrase.index("Acad")) #will give an error phrase = "Giraffe Academy" print(phrase.index("z")) phrase = "Giraffe Academy" print(phrase.replace("Giraffe", "Panda"))
false
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
85f2ba90389fb93c15f832f74166552bbbf44061
praveenpmin/Python
/list1.py
693
4.1875
4
# Let us first create a list to demonstrate slicing # lst contains all number from 1 to 10 lst = range(1, 11) print (lst) # below list has numbers from 2 to 5 lst1_5 = lst[1 : 5] print (lst1_5) # below list has numbers from 6 to 8 lst5_8 = lst[5 : 8] print (lst5_8) # below list has numbers from 2 to 10 lst1_ = lst[1 : ] print (lst1_) # below list has numbers from 1 to 5 lst_5 = lst[: 5] print (lst_5) # below list has numbers from 2 to 8 in step 2 lst1_8_2 = lst[1 : 8 : 2] print (lst1_8_2) # below list has numbers from 10 to 1 lst_rev = lst[ : : -1] print (lst_rev) # below list has numbers from 10 to 6 in step 2 lst_rev_9_5_2 = lst[9 : 4 : -2] print (lst_rev_9_5_2)
false
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
1acd357b716e8b304581d59179941a769737576a
praveenpmin/Python
/conversion3.py
570
4.3125
4
# Python code to demonstrate Type conversion # using dict(), complex(), str() # initializing integers a = 1 b = 2 # initializing tuple tup = (('a', 1) ,('f', 2), ('g', 3)) # printing integer converting to complex number c = complex(1,2) print ("After converting integer to complex number : ",end="") print (c) # printing integer converting to string c = str(a) print ("After converting integer to string : ",end="") print (c) # printing tuple converting to expression dictionary c = dict(tup) print ("After converting tuple to dictionary : ",end="") print (c)
false
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
c4b0602b03fedeef579efbb0a9694df624cf3b7c
praveenpmin/Python
/var4.py
413
4.375
4
a = 1 # Uses global because there is no local 'a' def f(): print ('Inside f() : ', a) # Variable 'a' is redefined as a local def g(): a = 2 print ('Inside g() : ',a) # Uses global keyword to modify global 'a' def h(): global a a = 3 print ('Inside h() : ',a) # Global scope print ('global : ',a) f() print ('global : ',a) g() print ('global : ',a) h() print ('global : ',a)
false
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
6b00144868f5c61dcbc1dc8ca8b5263c7ef887ba
LanYehou/shared_by_Lan
/python/test.py
1,730
4.21875
4
def theReturn(): def funx(x): #function funx, def funy(y): #function funy is in function funx. return(x*y) #return x*y means now the function funy(y)=x*y . if you use print(funy(y)) you will get the answer of x*y . return(funy(2)) #now in funy(y) , y=2 . So funx(x) = funy(2) = x*2 . a=funx(3) #now in function funx(x), x=3 . So funx(3) = funy(2) = 3*2 = 6 . print(a) #a=funx(3),so if you use print(a) , you will get 6. #if x=3,y=2,the output is 6-. ########################################################### def algorithm1(): a=int(input('input a interge between 100~999:\n')) m=0 n=a while(n!=0): m=m*10+int(n)%10 n//=10 print(a,' ==> ',m ,' .\n') ########################################################### def algo(): a=1 b=2 c= a+b and b-2*a print(c) def algo2(): a=input('') b=1 c=a+b print(c) def algo3(): dict={'country':'china','city':'zhangjiang','school':'gdou'} print("dict['city']:",dict['city']) def algo4(): def ifais0(a): if a==0: return(0) else: return(1) def output(): a=1 if ifais0(a): print(a+1) else: print(a+3) output() def algo5(): a=1 b=0 while a<10: b=b+2 a=a+1 print(b) def algo6(): a=[1,2] b=[3,4] c=0 for x in a: for y in b: c=c+x+y print(c) def algo7(): a=1 b=2 c=0 def changeab(): a=3 b=4 def addab(a,b): c=a+b print(c) changeab() addab(a,b) print(a,'\n',b,'\n',c) if __name__=='__main__': algo4()
false
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
da3a66bfcd0abf09460b271250091c659e82f619
prasantakumarsethi/python
/Python Probs/List_Mutability.py
436
4.125
4
#to show list and Dictionary are mutable or not # list Fruits = ["Apple","Banana","Mango","Strawberry","Watermelon"] print(id(Fruits)) print(Fruits) Vegetables = Fruits Vegetables[1]='Orange' print(id(Vegetables)) print(Vegetables) #dictonary Fruits = {1:"Apple",2:"Banana",3:"Mango",4:"Strawberry",5:"Watermelon"} print(id(Fruits)) print(Fruits) Vegetables = Fruits Vegetables[1]='Orange' print(id(Vegetables)) print(Vegetables)
false
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
e199f17d58cb5333de0ee06c197899d94fdafa47
Kailashw/HackerRank_Python
/Day 25.py
339
4.1875
4
import math def is_prime(n): if n == 2: return 'Prime' if n % 2 == 0 or n < 2: return 'Not prime' for j in range(3, int(math.sqrt(n)) + 1): if n % j == 0: return 'Not prime' return 'Prime' n = int(input()) for i in range(n): number = int(input()) print(is_prime(number))
false
b556ded22fa9b378b0352bde27a02cf8ba3d5187
ege-erdogan/comp125-jam-session-01
/11_10/problem_07.py
495
4.15625
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 = 6 is_prime = True if n != 2 and n % 2 == 0: is_prime = False elif n % 3 == 0: is_prime = False else: for i in range(3, int(math.sqrt(n)), 2): if n % i == 0: is_prime = False break print(is_prime)
false
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
1cb1efd306622329b3895df8777b7f5feffb8d61
amanbhal/ImportantQuestions
/InsertionSort.py
319
4.1875
4
""" Implement Insertion Sort on an array. """ def insertionSort(arr): for i in range(1,len(arr)): j = i while(j>0 and arr[j]<arr[j-1]): print i,j, arr[j], arr[j-1] = arr[j-1], arr[j] j -= 1 print arr return arr print insertionSort([6,5,4,3,2,1])
false
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
a01d518ebf69b684987a43d8c0cd24991d864ad9
PzcMist/python-exercise
/ex3.py
1,167
4.65625
5
print("I will now count my chickens:") #在屏幕上打印出I will now count my chickens: print("Hens", 25 + 30 / 6) #在屏幕上打印Hens,同时计算(先除在家,/表示全部除尽)打印 print("Roosters", 100 - 25 * 3 % 4) #打印Roosters,同时计算(先*在 % 最后计算-) print("Now I will count the eggs:") #在屏幕上打印Now I will count the eggs: print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #先(% / 后+ -)%与/平级所以从左到右,在计算+ -从左到右 print("Is it true that 3 + 2 < 5 - 7?") #在屏幕上打印Is it true that 3 + 2 < 5 - 7? print(3 + 2 < 5 - 7) #比较运算符,输出False or True print("What is 3 + 2?",3 + 2) #在屏幕上打印What is 3 + 2?,同时计算(5) print("What is 5 - 7?",5 - 7) #在屏幕上打印What is 5 - 7?,同时计算(-2) print("Oh,that's why it's False.") #在屏幕上打印出Oh,that's why it's False. print("How about some more.") #在屏幕上打印出How about some more. print("Is it greater?", 5> -2) #在屏幕上打印出Is it greater?,同时比较 print("Is it greater or equal?",5 >= -2) print("Is it less or equal?", 5 <= -2)
false
b97dd0be85ef222c68510a16797d4c76e6f43a9d
Biwoco-Playground/Learn-Docker_VNL
/Cookbook/Chapter1/1-12.py
386
4.28125
4
from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] print(Counter(words)) print('In 3 cai xuat hien nhieu nhat') print(Counter(words).most_common(3))
false
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
9b647e7adeb4698353ab3169bdba4af0ad23a426
alextodireanu/algorithms
/bubble_sort.py
410
4.375
4
# bubble sort algorithm def bubble_sort(bs_list): """Method to bubble sort a given list""" n = len(bs_list) # reading all the elements in our list for i in range(n-1): for j in range(n-i-1): if bs_list[j] > bs_list[j+1]: bs_list[j], bs_list[j+1] = bs_list[j+1], bs_list[j] return bs_list unsorted_list = [1, 4, 6, 2] print(bubble_sort(unsorted_list))
false
8ac0ff3826a01324a3e7501a460c037c750ef9bd
diegord13/programas
/Retos/sesiones/sesion10/sesion10.py
2,669
4.40625
4
""" Funciones La verdad es que hemos venido trabajando con funciones desde que empezamos con archivos .py En Python, definimos una función con la siguiente estructura def funcion(parametros) Recuerda que los parametros son opcionales! """ def suma(a,b): print(a+b) #suma(3,4) #Actividad 1 def caja(): total = 0 continuar = 'S' while continuar == 'S': nombre = input('Ingrese el nombre del producto ') precio = float(input('Ingrese el precio del producto ')) total = precio + total imprimaproducto(nombre,precio) continuar = input('tiene mas articulos para ingresar, marque S para si y N para no ') print('El total de la compra es ', total) def imprimaproducto(nombre,precio): print('El nombre del producto es {} y el precio es {}'.format (nombre,precio)) #Usted es cajero en un supermercado de su ciudad. Su trabajo es imprimir cada uno de los productos de su cliente, su precio y calcular el total a pagar. # #Diseña un programa con las siguiente características: # # 1. Que tenga una función caja que solicite al usuario nombre y precio de cada producto. # 2. Una variable total que vaya sumando el precio de los artículos # 3. Una función adicional llamada imprimaProducto(nombre, precio) que reciba el nombre y # el precio de cada producto y los imprima. # 4. Que después de llamar a imprimaProducto le pregunte al usuario si tiene o no más artículos a ingresar. Si no tiene, el programa debe detenerse. # 5. Si no hay más artículos, que imprima el total de la compra # Al final de tus funciones, puedes simplement llamar a la función caja para probar #caja() #Actividad 2 # import random def numALEATORIO(): num = random.randint(100,130) while num == 110 or num == 115 or num == 120: num = random.randint(100,130) return num def numeros(): num = 0 contador =1 while contador < 10: num = numALEATORIO() if contador % 2 != 0: if num % 2 == 0: print('El numero {} es par'.format(num)) contador += 1 if contador % 2 == 0: if num % 2 != 0: print('El numero {} es impar '.format(num)) contador += 1 # print(num) #Escribamos una función numAleatorio() que retorne un número aleatorio entre 100 y 130, #excepto los números 110, 115 y 120 . # #Adicionalmente, una función numeros que imprima diez números aleatorios #(retornados por la función numAleatorio()) alternando par, impar, comenzando por par. #numALEATORIO() numeros()
false
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
bd3a39f97ab581ce0a090408c6d63039e0df80a6
JorgeAntonioZunigaRojas/python
/practica_generadores_vs_funciones.py
1,573
4.21875
4
''' def funcion_generar_numeros_pares(limite): numero=1 numeros_pares=[] while numero<limite: numeros_pares.append(numero*2) numero=numero+1 return numeros_pares resultado=funcion_generar_numeros_pares(10) print(resultado) ''' # La diferencia entre un generador y una funcion es # --> funcion: devuelve todo el resultado de su algorimo con un "return" # --> Generador: devuelve parte del resultado de su algorimo con un "yield" # -----> para acceder a todos su resultados deberas usar un bucle repetitivo y usar "next" ''' def generador_numeros_pares(limite): numero=1 while numero<limite: yield numero*2 numero=numero+1 resultado=generador_numeros_pares(10) primer_numero_par=next(resultado) segundo_numero_par=next(resultado) tercer_numero_par=next(resultado) print("Primer numero par: {}".format(primer_numero_par)) print("Segundo numero par: {}".format(segundo_numero_par)) print("Tercer numero par: {}".format(tercer_numero_par)) ''' # -->yield from: ayuda e recorrer elementros en una sola linea def devuelve_ciudades(*ciudades): #Cuando se coloca un "*" (asterisco) delante de un argumento de una funcion estamos indicando que va a recivir un numero indetermindado de argumentos y los va a recibir en forma de tupla for elemento in ciudades: yield from elemento #Es equivalente a un buble for ciudades=devuelve_ciudades("Lima", "Trujillo", "Arequipa", "cusco", "VES") print(next(ciudades)) print(next(ciudades)) print(next(ciudades)) print(next(ciudades)) print(next(ciudades))
false
5191bf3ef7658a74fb8ad5a4d8f42b3f7c4052d7
rudresh-poojari/my-captain-assingments
/circle_area.py
323
4.125
4
r = float(input("enter the radius of the circle : ")) area = 3.14159265359*r**2 print("the area of thr circlr with radius ",r,"is : ",area) # output : # C:\Users\rudre\OneDrive\Desktop\pythonmc>circle_area.py # enter the radius of the circle : 1.1 # the area of thr circlr with radius 1.1 is : 3.801327110843901
false
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
dc657b9020a4d2635cf85d2a00f8b4cb928c6a37
arayariquelmes/curso_python_abierto
/18_ejemplo_while.py
484
4.15625
4
#import os #Ejemplos de uso del ciclo while #1. Ciclo que se repite una cantidad indeterminada de veces res="si" while res == "si": print("Bienvenido al programa!") res = input("Desea continuar?") #Esto limpia la pantalla #os.system('clear') print("Gracias por utilizar el super programa más util del mundo") #2. Ciclo que se repite un número finito de veces cont = 1 while cont <= 100: print(cont, end=" ") cont+=1 # cont = cont + 1 print("Se acabó!!")
false
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
d80c6860c1560d77f5375136529dc5dfbfdfd709
OusmaneCisse/tableMulti_anneeBiss
/tableMulti_anneeBiss/table_de_multiplication.py
579
4.15625
4
""" Cette fonction permet d'afficher la table de multiplication en fonction d'un nombre enter au clavier. Auteur: Ousmane CISSE Date: 05/12/2020 """ __version__ = "0.0.1" #Creation de la fonction def table_de_multiplication(): #Recupération de la valeur n = int(input("Veuillez entrer un nombre: ")) #Affichage de la table print("La table de multiplication de : ", n," est :") #Boucle pour parcourir de 1 à 10 for i in range(1,11): print(n , " x ", i, " = ",i*n) if __name__ == "__main__": table_de_multiplication()
false
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