blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
230e1d2846f4b608c3f541d5d089655ca97f9efe
kmrsimkhada/Python_Basics
/loop/while_with_endingCriteria.py
968
4.25
4
#While-structure with ending criteria ''' The second exercise tries to elaborates on the first task. The idea is to create an iteration where the user is able to define when the loop ends by testing the input which the user gave. Create a program which, for every loop, prompts the user for input, and then prints it on the screen. If the user inputs the string "quit", the program prints "Bye bye!" and shuts down. When the program is working correctly it should print out something like this: >>> Write something: What? What? Write something: Fight the power. Fight the power. Write something: quit Bye bye! >>> It is probably a good idea to implement the entire program within one "while True" code block, and define the ending criteria so that the program uses a selection criteria and break command. ''' while True: write = str(input("Write something: ")) if write == "quit": print("Bye bye!") break; else: print(write) continue;
true
e1dca0956dc0547a3090e508787df989034b0eaf
kmrsimkhada/Python_Basics
/type_conversion.py
702
4.5
4
#Type Conversions ''' In this exercise the aim is to try out different datatypes. Start by defining two variables, and assign the first variable the float value 10.6411. The second variable gets a string "Stringline!" as a value. Convert the first variable to an integer, and multiply the variable with the string by 2. After this, finalize the program to print out the results in the following way: Integer conversion cannot do roundings: 10 Multiplying strings also causes trouble: Stringline!Stringline! ''' number1 = 10.6411 st1 = "Stringline!" st2 = st1*2 num1 = int(number1) print("Integer conversion cannot do roundings: "+str(num1)) print("Multiplying strings also causes trouble: "+st2)
true
26a5ce912495c032939b4b912868374a6d8f83c7
kmrsimkhada/Python_Basics
/lists/using_the_list.py
2,397
4.84375
5
#Using the list ''' n the second exercise the idea is to create a small grocery shopping list with the list datastructure. In short, create a program that allows the user to (1) add products to the list, (2) remove items and (3) print the list and quit. If the user adds something to the list, the program asks "What will be added?: " and saves it as the last item in the list. If the user decides to remove something, the program informs the user about how many items there are on the list (There are [number] items in the list.") and prompts the user for the removed item ("Which item is deleted?: "). If the user selects 0, the first item is removed. When the user quits, the final list is printed for the user "The following items remain in the list:" followed by the remaining items one per line. If the user selects anything outside the options, including when deleting items, the program responds "Incorrect selection.". When the program works correctly it prints out the following: >>> Would you like to (1)Add or (2)Remove items or (3)Quit?: 1 What will be added?: Apples Would you like to (1)Add or (2)Remove items or (3)Quit?: 1 What will be added?: Beer Would you like to (1)Add or (2)Remove items or (3)Quit?: 1 What will be added?: Carrots Would you like to (1)Add or (2)Remove items or (3)Quit?: 2 There are 3 items in the list. Which item is deleted?: 3 Incorrect selection. Would you like to (1)Add or (2)Remove items or (3)Quit?: 2 There are 3 items in the list. Which item is deleted?: 2 Would you like to (1)Add or (2)Remove items or (3)Quit?: 2 There are 2 items in the list. Which item is deleted?: 0 Would you like to (1)Add or (2)Remove items or (3)Quit?: 4 Incorrect selection. Would you like to (1)Add or (2)Remove items or (3)Quit?: 3 The following items remain in the list: Beer >>> ''' mylist = [] while True : user_input = int(input("""Would you like to (1)Add or (2)Remove items or (3)Quit?:""")) if user_input == 1: add_input = input("What will be added?: ") mylist.append(add_input) elif user_input == 2: print("There are ",len(mylist), " items in the list.") try: mylist.pop(int(input("Which item is deleted?: "))) except Exception: print("Incorrect selection.") elif user_input == 3: print("The following items remain in the list: ") for i in mylist: print(i) break else: print("Incorrect selection. ")
true
8a49bad35b7b1877abf081adc13ed6b9b63d0de8
suhanapradhan/IW-Python
/functions/6.py
319
4.28125
4
string = input("enter anything consisting of uppercase and lowercase") def count_case(string): x = 0 y = 0 for i in string: if i.isupper(): x += 1 else: y += 1 print('Upper case count: %s' % str(x)) print('Lower case count: %s' % str(y)) count_case(string)
true
35a98e4bf5b1abcd7d6dd9c6ff64d53d07f8788e
BinyaminCohen/MoreCodeQuestions
/ex2.py
2,795
4.1875
4
def sum_list(items): """returns the sum of items in a list. Assumes the list contains numeric values. An empty list returns 0""" sum = 0 if not items: # this is one way to check if list is empty we have more like if items is None or if items is [] return 0 else: for x in items: sum += x return sum def remove_duplicates(items): """remove all the duplicates from a list, and return the list in the original order a copy of the list (with the modifications) is returned :type items: object listNoDup = [] if len(items) < 2: return items else: for x in items: for y in listNoDup: if x is not y: listNoDup.append(x) return listNoDup""" exsist = set() listNoDup = [] for x in items: if x not in exsist: exsist.add(x) listNoDup.append(x) return listNoDup def remove_longer_than(words, n): """remove all the words from the words list whose length is greater than N""" return [x for x in words if len(x) <= n] def have_one_in_common(list1, list2): """return True if the lists have at least one element in common for x in list1: for y in list2: if x is y: return True return False""" return len(set(list1).intersection(set(list2))) > 0 def word_count(words): """takes a list of words and returns a dictionary that maps to each word how many times it appears in the list""" d = {} for x in words: if x in d: d[x] += 1 else: d[x] = 1 return d # start tests def test_sum_list(): assert (sum_list([]) == 0) assert (sum_list([1]) == 1) assert (sum_list([1, 2, 3]) == 6) def test_remove_duplicates(): assert (remove_duplicates([1, 3, 2, 1, 3, 1, 2]) == [1, 3, 2]) assert (remove_duplicates(["a", "b", "a"]) == ["a", "b"]) assert (remove_duplicates([]) == []) def test_remove_longer_than(): l = ["", "a", "aa", "aaa", "aaaa"] assert (remove_longer_than(l, -1) == []) assert (remove_longer_than(l, 0) == [""]) assert (remove_longer_than(l, 2) == ["", "a", "aa"]) def test_have_one_in_common(): assert (have_one_in_common([1, 2, 3], [4, 5, 6]) == False) assert (have_one_in_common([], []) == False) assert (have_one_in_common([1, 2, 3], [1]) == True) assert (have_one_in_common(["a", "b", "c"], ["a", "x", "c"]) == True) def test_word_count(): assert (word_count([]) == {}) assert (word_count(["a", "b", "a"]) == {"a": 2, "b": 1}) if __name__ == "__main__": test_sum_list() test_remove_duplicates() test_remove_longer_than() test_have_one_in_common() test_word_count() print("Done")
true
a9cb243ebc4a52d46e6d214a17e011c293cde3ff
s16323/MyPythonTutorial1
/EnumerateFormatBreak.py
1,464
4.34375
4
fruits = ["apple", "orange", "pear", "banana", "apple"] for i, fruit in enumerate(fruits): print(i, fruit) print("--------------Enumerate---------------") # Enumerate - adds counter to an iterable and returns it # reach 3 fruit and omit the rest using 'enumerate' (iterator) for i, fruit in enumerate(fruits): # 'For' loop receives 2 args now. For every index 'i' and a given 'fruit' element reported by 'enumerate()' function do: if i == 3: break print(i, fruit) print("---------------Format-----------------") # Format # C = "someOtherString".capitalize() # Check out other functions # print(C.lower()) # itd... print("someString {} {}".format("123", "ABC")) # format replaces whatever is in {} x ="Hello {}" y = x.format("World", "xxx", 777) print(y) print("--------------------------------------") for i, fruit in enumerate(fruits): print("I'm checking: {}".format(i)) if i == 3: print("{} is the third fruit!!! No more checking.".format(fruit)) break print(i,"is", fruit) print("------Skipping some iterations--------") # Skipping some iterations fruits = ["apple", "orange", "pear", "banana", "apple"] print("Start") for fruit in fruits: if fruit == "orange": print("wracam do poczatku petli") continue # after 'continue' the next if is skipped ! Code goes back to 'for' loop if fruit == "banana": break print(fruit) print("End")
true
4cb726601b5dda4443b8fe3b388cbd6f598013a8
varnagysz/Automate-the-Boring-Stuff-with-Python
/Chapter_05-Dictionaries_and_Structuring_Data/list_to_dictionary_function_for_fantasy_game_inventory.py
1,640
4.21875
4
'''Imagine that a vanquished dragon’s loot is represented as a list of strings like this: dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this: def addToInventory(inventory, addedItems): # your code goes here inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv) The previous program (with your displayInventory() function from the previous project) would output the following: Inventory: 45 gold coin 1 rope 1 ruby 1 dagger Total number of items: 48''' def display_inventory(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print('Total number of items: ' + str(item_total)) def add_to_inventory(inventory, added_items): for i in added_items: inventory.setdefault(i, 0) inventory[i] += 1 return inventory inv = {'gold coin': 42, 'rope': 1} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = add_to_inventory(inv, dragon_loot) display_inventory(inv)
true
71db3ebdbd3bbcac09c385947f6b327f9d7c3d73
harshit-sh/python_games
/matq.py
743
4.25
4
# matq.py # Multiplication Quiz program # Created by : Harshit Sharma from random import randint print "Welcome to Maths Multiplication Quiz!" print "--------------------------------" ques = int(raw_input("How many questions do you wish to answer? ")) print "--------------------------------" limit = int(raw_input("Till what positive range can you answer? (Enter a Positive number) ")) c1 = 0 for i in range(ques): n1 = randint(1,limit) n2 = randint(1,limit) right_ans = n1*n2 ans = int(raw_input("What's %d times %d? : "%(n1,n2))) if right_ans == ans: print "Well done!" c1 = c1 + 1 else: print "Sorry, answer is ",right_ans print print "---------Summary------------" print print "You scored", c1, "points out of a possible", ques
true
cdaa647a527a20cf851f65ce4df554a3185b920a
annkon22/ex_book-chapter3
/linked_list_queue(ex20).py
1,835
4.1875
4
# Implement a stack using a linked list class Node: def __init__(self, init_data): self.data = init_data self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_data(self, new_data): self.data = new_data def set_next(self, new_next): self.next = new_next class UnorderedList: def __init__(self): self.head = None self.num = 0 def is_empty(self): return self.head == None def add(self, item): temp = Node(item) temp.set_next(self.head) self.head = temp self.num += 1 def size(self): return self.num def list_print(self): print_value = self.head while print_value: print(print_value.data, end = ' ') print_value = print_value.next def queue(self, newdata): new_node = Node(newdata) if self.head is None: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node def stack(self, newdata): new_node = Node(newdata) if self.head is None: self.head = new_node return def __str__(self): current = self.head string = '' while current is not None: string += str(current) + ", " current = current.get_next() return string my_lst = UnorderedList() my_lst.stack(1) my_lst.stack(10) my_lst.stack(100) my_lst.stack(1000) my_lst.stack(10000) my_lst.stack(100000) my_lst.stack(1000000) my_lst.stack(10000000) my_lst.list_print() print()
true
32662139be2cd03f427faaa5a1255fb8fd24b1cd
annkon22/ex_book-chapter3
/queue_reverse(ex5).py
457
4.25
4
#Implement the Queue ADT, using a list such that the rear of the queue #is at he end of the list class Queue(): def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) my_q = Queue() my_q.enqueue('hi') my_q.enqueue('ok') my_q.enqueue('bye') print(my_q.dequeue()) print(my_q.dequeue()) print(my_q.dequeue())
true
061acf150e2bea1ec8acbc7ce8d2a4550c408e0e
ChristianDzul/ChristianDzul
/Exam_Evaluation/Question_06.py
506
4.15625
4
##Start## print ("Welcome to the area calculator") ##Variables## length = 0 width = 0 area_square = 0 area_rectangle = 0 ##Getting the values## length = int( input("Insert a value for the lenght \n")) width = int( input("Insert a value for the width \n")) ##Process## if (length == width): area_square = length * width print ("The figure is a square with an area of:", area_square) else: area_rectangle = length * width print ("The figure is a rectangle with an area of:", area_rectangle)
true
8bf756db6183232e427214af5df6d0d67b19b98c
meraj-kashi/Acit4420
/lab-1/task-1.py
286
4.125
4
# This script ask user to enter a name and number of cookies # script will print the name with cookies name=input("Please enter your name: ") number=int(input("Please enetr number of your cookies: ")) print(f'Hi {name}! welcome to my script. Here are your cookies:', number*'cookies ')
true
9b80a85e7d931de6d78aeddeeccc2c154897a88b
vikrampruthvi5/pycharm-projects
/code_practice/04_json_experimenter_requestsLib.py
1,217
4.125
4
""" Target of this program is to experiment with urllib.request library and understand GET and POST methods Tasks: 1. Create json server locally 2. retrieve json file using url 3. process json data and perform some actions 4. Try POST method """ """ 1. Create json server locally a. From terminal install json-server : sudo npm install -g json-server create a folder or file with json data ex: people.json b. Start observing the json file json-server --watch people.json c. Make sure you are getting Resources http://localhost:3000/people Home http://localhost:3000 """ """ 2. retrieve json file using url """ import urllib.request as req import json def get_json_data(url): # Method to retrieve json data data = req.urlopen(url) data_json = json.loads(data.read()) return data_json def post_json_data(url): # Method posts json data to the json file under server print("Post method") def print_json_data(json): for i in range(len(json)): print(json[i]['name'],"is",json[i]['age'],"years old.") json = get_json_data("http://localhost:3000/people") print_json_data(json)
true
aa322e4df062956a185267130057767ad450dc6e
JRose31/Binary-Lib
/binary.py
937
4.34375
4
''' converting a number into binary: -Divide intial number by 2 -If no remainder results from previous operation, binary = 0, else if remainder exists, round quotient down and binary = 1 -Repeat operation on remaining rounded-down quotient -Operations complete when quotient(rounded down or not) == 0 ''' import math def intToBinary(x): convert = x binary_holder = [] while convert > 0: #dividing any number by 2 results in a remainder of 0 or 1 binary_holder.append(convert % 2) #reassign rounded down quotient to our variable (convert) convert = math.floor(convert//2) #convert complete binary_holder list into string holder_string = "".join([str(num) for num in binary_holder]) #our binary is backwards in the list (now a str) so we reverse it binary_complete = holder_string[::-1] return(binary_complete) binary = intToBinary(13) print(binary)
true
5b17c79d9830601e3ca3f21b2d1aa8f334e93f13
piumallick/Python-Codes
/LeetCode/Problems/0104_maxDepthBinaryTree.py
1,405
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 14 20:12:03 2020 @author: piumallick """ # Problem 104: Maximum Depth of a Binary Tree ''' Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. ''' class Node: def __init__(self , val): self.value = val self.left = None self.right = None ''' def maxDepth(root): if root == None: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 ''' def maxDepth2(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 leftDepth = self.maxDepth2(root.left) rightDepth = self.maxDepth2(root.right) if leftDepth > rightDepth: return leftDepth + 1 else: return rightDepth + 1 # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.right.right.left = Node(8) root.right.left.right = Node(7) print(root.maxDepth2(8))
true
c5f5581f816bd354b3ee78d660c58aab13bb3906
piumallick/Python-Codes
/LeetCode/Leetcode 30 day Challenge/April 2020 - 30 Day LeetCode Challenge/02_isHappyNumber.py
1,406
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 25 22:49:19 2020 @author: piumallick """ # Day 2 Challenge """ Write an algorithm to determine if a number n is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Return True if n is a happy number, and False if not. Example: Input: 19 Output: true """ ''' let num = 123 let sum = 0 do while sum is not 1 { do while num is greater than one digit number { get number at index 1 of num num = num // 10 calculate sum } calculate sum for the last digit in num } ''' def isHappyNumber(num): sum = 0 numset = set() while (sum != 1 and (num not in numset)): numset.add(num) sum = 0 while (num > 9): rem = num % 10 rem_square = (rem ** 2) sum += rem_square num = num // 10 sum += (num ** 2) num = sum #print(numset) return sum == 1 # Testing if (isHappyNumber(2)): print('Happy Number') else: print('Not a Happy Number')
true
48a6871dba994b1244835a8fcc2a5edf9b206ca1
piumallick/Python-Codes
/LeetCode/Problems/0977_sortedSquares.py
909
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 7 15:01:17 2020 @author: piumallick """ # Problem 977: Squares of a Sorted Array ''' Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order. ''' def sortedSquares(A): """ :type A: List[int] :rtype: List[int] """ res = [] for i in range(0, len(A)): res.append(A[i] ** 2) i += 1 return sorted(res) def sortedSquares2(A): return ([i*i for i in A]) # Testing A = [1,2,3,4,5] print(sortedSquares(A)) B = [-1, -2, 0, 7, 10] print(sortedSquares2(B))
true
3da3dfcf8bdba08539c1a0ecb23f7a908a8718f6
piumallick/Python-Codes
/LeetCode/Problems/0009_isPalindrome.py
973
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 29 15:46:03 2020 @author: piumallick """ # Problem 9: Palindrome Number """ Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? """ def isPalindrome(n): r = 0 x = n if (n < 0): return False while (n > 0): a = n % 10 r = (r * 10) + a n = n // 10 print('x=',x) print('r=',r) if (x == r): return True else: return False n = 121 print(isPalindrome(n))
true
a4b659635bbc3dbafabce7f53ea2f2387281daa3
piumallick/Python-Codes
/Misc/largestNumber.py
613
4.5625
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 27 10:59:35 2019 @author: piumallick """ # Python Program to find out the largest number in the array # Function to find out the maximum number in the array def largestNumber(arr, n): # Initialize the maximum element max = arr[0] #Traverse the array to find out the max element for i in range(1, n): if arr[i] > max: max = arr[i] return max # Driver Code arr = [10, 20, 30, 50, 40, 90, 5] n = len(arr) print('The largest number in the array is',largestNumber(arr,n),'.')
true
78784eb5050732e41908bbb136a0bac6881bc29b
phenom11218/python_concordia_course
/Class 2/escape_characters.py
399
4.25
4
my_text = "this is a quote symbol" my_text2 = 'this is a quote " symbol' #Bad Way my_text3 = "this is a quote \" symbol" my_text4 = "this is a \' \n quote \n symbol" #extra line print(my_text) print(my_text2) print(my_text3) print(my_text4) print("*" * 10) line_length = input("What length is the line?" >) character = input("What character should I use?") print(character*int(line_length))
true
5ce0153e690d86edc4b835656d290cda02caa2c7
plee-lmco/python-algorithm-and-data-structure
/leetcode/23_Merge_k_Sorted_Lists.py
1,584
4.15625
4
# 23. Merge k Sorted Lists hard Hard # # Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. # # Example: # # Input: # [ # 1->4->5, # 1->3->4, # 2->6 # ] # Output: 1->1->2->3->4->4->5->6 def __init__(self): self.counter = itertools.count() def mergeKLists(self, lists: List[ListNode]) -> ListNode: return self.use_priority_queue(lists) def use_priority_queue(self, lists: List[ListNode]) -> ListNode: ''' Runtime: 164 ms, faster than 26.43% of Python3 online submissions for Merge k Sorted Lists. Memory Usage: 16.9 MB, less than 32.59% of Python3 online submissions for Merge k Sorted Lists. ''' # Create priority queue q = PriorityQueue() # Create head of link list head = ListNode(0) curr_node = head # Loop through all the list # Put the first linked list in Priority Queue for link in lists: # ensure link list defined if link: # Add to queue # In python 3 to avoid duplicate elements in tuple caused comparison # failure like "TypeError: '<' not supported between instances of # 'ListNode' and 'ListNode'", use a unique id as the second element # in the tuple. q.put((link.val, next(self.counter), link)) # While we go over all linked list while (not q.empty()): _, count, node = q.get() curr_node.next = node if node.next: q.put((node.next.val, next(self.counter), node.next)) curr_node = node return head.next
true
cec13d4024f52f100c8075e5f1b43408790377bb
aquatiger/misc.-exercises
/random word game.py
1,175
4.5625
5
# does not do what I want it to do; not sure why # user chooses random word from a tuple # computer prints out all words in jumbled form # user is told how many letters are in the chosen word # user gets only 5 guesses import random # creates the tuple to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") word = random.choice(WORDS) correct = word jumble = "" count = 0 score = 5 """ Welcom to Random Word Game From the list of scrambled words, Choose the one the computer chose. """ print("The word is ", len(word), "letters long.") # print(word) for word in WORDS: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] * (len(word)) print(jumble) guess = input("\nYour guess is: ") while guess != correct and guess != "": print(guess) if guess == correct: print("That's it! You guessed correcntly!\n") print("Thanks for playing!") input("\nPress the enter key to exit.") """ while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] """
true
30be4f414ed675c15f39ccf62e33924c7eb9db3b
Deepanshudangi/MLH-INIT-2022
/Day 2/Sort list.py
348
4.46875
4
# Python Program to Sort List in Ascending Order NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) NumList.sort() print("Element After Sorting List in Ascending Order is : ", NumList
true
34028b34420e05f24493049df0c8b5b0391eb9b9
sammaurya/python_training
/Assignment6/Ques4.py
879
4.4375
4
''' We have a function named calculate_sum(list) which is calculating the sum of the list. Someone wants to modify the behaviour in a way such that: 1. It should calculate only sum of even numbers from the given list. 2. Obtained sum should always be odd. If the sum is even, make it odd by adding +1 and if the sum is odd do nothing Write two decorators that would serve these two purposes and use them in the above function. ''' def even_sum(func): def wrapper(list): even_list = [value for value in list if value % 2 == 0] return func(even_list) return wrapper def make_odd(func): def wrapper(list): sum = func(list) if sum % 2 == 0: return sum + 1 return sum return wrapper @make_odd @even_sum def calculate_sum(list): return sum(list) list = [1,2,3,4,5,6,7,8,9,10] print(calculate_sum(list))
true
44f4b11f6819b285c3698ab59571f03591ad72b8
sahilsehgal81/python3
/computesquareroot.py
308
4.125
4
#!/usr/bin/python value = eval(input('Enter the number to find square root: ')) root = 1.0; diff = root*root - value while diff > 0.00000001 or diff < -0.00000001: root = (root + value/root) / 2 print(root, 'squared is', root*root) diff = root*root - value print('Square root of', value, "=", root)
true
cfcd0baa03e8b3534f59607103dfec97f760ea28
zoeang/pythoncourse2018
/day03/exercise03.py
699
4.40625
4
## Write a function that counts how many vowels are in a word ## Raise a TypeError with an informative message if 'word' is passed as an integer ## When done, run the test file in the terminal and see your results. def count_vowels(word): if (type(word)==str)==False: raise TypeError, "Enter a string." else: vowels= ['a','e','i','o','u'] #list of vowels word_letters=[i for i in word] #store each letter of the word as an element of a list number_of_vowels=0 for i in word_letters: #for each letter in the word if i in vowels: #check if the letter is in the list of vowels #print i + ' is a vowel.' number_of_vowels+=1 return number_of_vowels # to run, navigate to file
true
bb7941ec61dab5e4798f20fb78222c933efdcfe4
Quantum-Anomaly/codecademy
/intensive-python3/unit3w4d6project.py
757
4.5
4
#!/usr/bin/env python3 toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms'] prices = [2,6,1,3,2,7,2] num_pizzas = len(toppings) #figure out how many pizzas you sell print("we sell " + str(num_pizzas) + " different kinds of pizza!") #combine into one list with the prices attached to the slice pizzas = list(zip(prices,toppings)) print(pizzas) #here is the sorting magic sorted_pizzas = sorted(pizzas) print(sorted_pizzas) #cheapest pizza cheapest_pizza = sorted_pizzas[0] #most expensive pizza priciest_pizza = sorted_pizzas[-1] #three of the cheapest three_cheapest = sorted_pizzas [:3] print(three_cheapest) #how many 2 dollar items are there? num_two_dollar_slices = prices.count(2) print(num_two_dollar_slices)
true
544c379a54a69a59d25a1241727d02f9414d6d1b
Murrkeys/pattern-search
/calculate_similarity.py
1,633
4.25
4
""" Purpose : Define a function that calculates the similarity between one data segment and a given pattern. Created on 15/4/2020 @author: Murray Keogh Program description: Write a function that calculates the similarity between a data segment and a given pattern. If the segment is shorter than the pattern, print out 'Error' message. Data dictionary: calculate_similarity : Function that calculate similarity ds : Numpy array of given data segment patt : Numpy array of given pattern output : Output of function, float or string data_segment : given segment of data pattern : given pattern list """ import numpy as np def calculate_similarity(data_segment, pattern): """ Calculate the similarity between one data segment and the pattern. Parameters ---------- data_segment : [float] A list of float values to compare against the pattern. pattern : [float] A list of float values representing the pattern. Returns ------- float The similarity score/value. "Error" If data segment and pattern are not the same length. """ # Assign given float lists to numpy array variables ds = np.array(data_segment) patt = np.array(pattern) #Check if length of segment is shorter than length of pattern if len(ds) != len(patt): output = 'Error' #Assign 'Error' to output else: output = np.sum(ds*patt) #assign similarity calculation to output return output
true
13593ebd81e6210edd3981895623975c820a72bc
MurrayLisa/pands-problem-set
/Solution-2.py
367
4.4375
4
# Solution-2 - Lisa Murray #Import Library import datetime #Assigning todays date and time from datetime to variable day day = datetime.datetime.today().weekday() # Tuesday is day 1 and thursday is day 3 in the weekday method in the datetime library if day == 1 or day == 3: print ("Yes - today begins with a T") else: print ("No Today does not begin with a T")
true
c0babd8461d2df8c5c3fe535b4fcc9ae15464adf
dcassells/Project-Euler
/project_euler001.py
565
4.46875
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def three_multiple(x): if x%3 == 0: return 1 else: return 0 def five_multiple(x): if x%5 == 0: return 1 else: return 0 def three_five_multiple_sum(a): multi_sum = 0 for i in range(a): if three_multiple(i): multi_sum = multi_sum + i elif five_multiple(i): multi_sum = multi_sum + i return multi_sum print(three_five_multiple_sum(1000))
true
5af9348c7a72d67d0985911be231eb92519c8610
elagina/Codility
/lessons/lesson_1.py
580
4.15625
4
""" Codility Lesson 1 - Iterations BinaryGap - Find longest sequence of zeros in binary representation of an integer. """ def solution(N): bin_N = str("{0:b}".format(N)) max_counter = 0 counter = 0 for ch in bin_N: if ch == '1': if max_counter < counter: max_counter = counter counter = 0 else: counter += 1 return max_counter def main(): N = 9 print 'Binary Gap Problem' print 'Input:\n', 'N =', N print 'Output:\n ', solution(N) if __name__ == '__main__': main()
true
b3bd54dd4116a00744311a671f01040d70799f98
josemigueldev/algoritmos
/07_factorial.py
442
4.21875
4
# Factorial de un número def factorial(num): result = 1 if num < 0: return "Sorry, factorial does not exist for negative numbers" elif num == 0: return "The factorial of 0 is 1" else: for i in range(1, num + 1): result = result * i return f"The factorial of {num} is {result}" if __name__ == "__main__": number = int(input("Enter a number: ")) print(factorial(number))
true
c5cdfbda5e8cb293bb7773ef345ddb5c8157313e
udhay1415/Python
/oop.py
861
4.46875
4
# Example 1 class Dog(): # Class object attribute species = "mammal" def __init__(self, breed): self.breed = breed # Instantation myDog = Dog('pug'); print(myDog.species); # Example 2 class Circle(): pi = 2.14 def __init__(self, radius): self.radius = radius # Object method def calculateArea(self): return self.radius*self.radius*self.pi myCircle = Circle(2); print(myCircle.radius); print(myCircle.calculateArea()); # Example - Inheritance class Animal(): # Base class def __init__(self): print('Animal created') def eating(self): print('Animal eating') class Lion(Animal): # Derived class that can access the methods and properties of base class def __init__(self): print('Lion created') myLion = Lion() myLion.eating()
true
f7ba7fbb5be395558e1d8451e6904279db95952d
Nour833/MultiCalculator
/equation.py
2,637
4.125
4
from termcolor import colored import string def equation(): print(colored("----------------------------------------------------------------", "magenta")) print(colored("1 ", "green"), colored(".", "red"), colored("1 dgree", "yellow")) print(colored("2 ", "green"), colored(".", "red"), colored("2 degree", "yellow")) print(colored("98", "green"), colored(".", "red"), colored("return to home menu", "yellow")) print(colored("99", "green"), colored(".", "red"), colored("exit", "yellow")) try : aq = int(input(colored("""Enter your selected number here ==>""", "blue"))) except : print(colored("please select the right number", "red")) equation() try : if aq == 1: print(colored("Exemple : ax+b ", "red")) b = int(input(colored("Enter b : ", "green"))) a = int(input(colored("Enter a : ", "green"))) x = -b/a if type(x) == float: print(colored("x = " + str(x), "magenta"),colored("or (another form) x = " + str(-b) + "/ "+str(a), "magenta")) else: print(colored("x = "+str(x),"magenta")) elif aq == 2: a = int(input(colored("Enter a : ","green"))) b = int(input(colored("Enter b : ", "green"))) c = int(input(colored("Enter c : ","green"))) Delta = b ** 2 - 4 * a * c rdelta = Delta**(1/2) if type(rdelta)==float: rDelta= "√"+str(Delta) else: rDelta = rdelta if Delta == 0: x = -b / (2 * a) if type(x)==float: print(colored("x = "+str(x),"cyan")," or ",colored("x = "+str(-b)+"/ "+str(2*a),"cyan")) elif Delta < 0: print("X hasn't solution") else: x1 = (-b + rdelta) / (2 * a) x2 = (-b - rdelta) / (2 * a) if type(x1) == float: x1 = str(x1)+" or/or "+"( "+str(-b)+"+"+str(rDelta)+" ) "+"/ "+str(a*2) else: x1 = x1 if type(x2) == float: x2 = str(x2)+" or/or "+"( "+str(-b)+"-"+str(rDelta)+" ) "+"/ "+str(a*2) else: x2=x2 print(colored("x1 = "+x1,"cyan"),"and",colored("x2 = "+x2,"cyan")) elif aq == 98: eq=1 return eq elif aq == 99: exit() except: print(colored("please select the right number", "red")) equation()
true
f9d07c3b4fbdc162b266613270fb975eac8e097d
lidongdongbuaa/leetcode2.0
/位运算/汉明距离/461. Hamming Distance.py
1,551
4.28125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/1/16 20:33 # @Author : LI Dongdong # @FileName: 461. Hamming Distance.py '''''' ''' 题目分析 1.要求:The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different 2.理解:求两个数的相同位置上不同数的发生次数和 3.类型:bit manipulation 4.边界条件:0 ≤ x, y < 2**31. 4.方法及方法分析:bit compare, XOR + count 1 time complexity order: O(1) space complexity order: O(1) ''' ''' A. 思路:brute force - bit compare 方法: 1. compare bit one by one if dif, add numb time complex: O(32) = O(1) space complex: O(1) 易错点: ''' class Solution: def hammingDistance(self, x: int, y: int) -> int: numb = 0 for i in range(32): if (x >> i & 1) != (y >> i & 1): numb += 1 return numb x = Solution() print(x.hammingDistance(1, 4)) ''' B. 优点:不用32位遍历 思路:XOR + count 1 (可用191的各种方法替换) 方法: 1. transfer dif value to 1 2. count 1 time complex: O(i) = O(1), i is numb of 1 space complex: O(1) 易错点: ''' class Solution: def hammingDistance(self, x: int, y: int) -> int: z = x ^ y numb = 0 while z != 0: z = z & z - 1 numb += 1 return numb
true
e88f7472da1d78f89cd3a23e98c97c3bc054fba7
lidongdongbuaa/leetcode2.0
/二叉树/二叉树的遍历/DFS/145. Binary Tree Postorder Traversal.py
1,978
4.15625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/2/19 20:15 # @Author : LI Dongdong # @FileName: 145. Binary Tree Postorder Traversal.py '''''' ''' 题目分析 1.要求: Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: Follow up: Recursive solution is trivial, could you do it iteratively? 2.理解: post order the tree, output the node val in list 3.类型: binary tree 4.确认输入输出及边界条件: input: tree root with API, repeated? Y order? N value range? N output: list[int] corner case: None -> [] only one -> [int] 4.方法及方法分析: time complexity order: space complexity order: ''' ''' dfs from top to down ''' class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: if not root: # corner case return [] res = [] def dfs(root): # scan every node if not root: # base case return dfs(root.left) dfs(root.right) res.append(root.val) return root dfs(root) return res ''' dfs bottom up ''' class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] l = self.postorderTraversal(root.left) r = self.postorderTraversal(root.right) return l + r + [root.val] ''' dfs iteration ''' class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: if not root: # corner case return [] stack = [root] res = [] while stack: root = stack.pop() res.append(root.val) if root.left: stack.append(root.left) if root.right: stack.append(root.right) return res[::-1]
true
8a4ccf34efe6041af0f3d69dae882df49b30d0e8
lidongdongbuaa/leetcode2.0
/二分搜索/有明确的target/33. Search in Rotated Sorted Array.py
2,283
4.21875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/3/12 15:24 # @Author : LI Dongdong # @FileName: 33. Search in Rotated Sorted 数组.py '''''' ''' 题目分析 - 本题重点看 find the target value in the sorted rotated array, return its index, else return -1 O(logN) binary search problem input: nums:list[int], repeated value in it? N; ordered, Y; len(nums) range? [1, 10000]; value range? [-2*32, 2*32] output:int or -1 corner case: nums is None? Y -> -1 nums is only one? Y -> as request target is None? Y -> -1 5.方法及方法分析:brute force; binary search time complexity order: binary search O(logN) < brute force O(N) space complexity order: O(1) 6.如何考 ''' ''' A.brute force - traversal all value Method: traversal all elements in nums, and check the target, if having, return True, else return False time complexity: O(N) space complexity: O(1) ''' class Solution: def search(self, nums: List[int], target: int) -> int: for index, value in enumerate(nums): if target == value: return index return -1 ''' A. Binary search Method: 1. corner case 2. set left and right boundary 3. do while loop a. set mid b. if arr[mid] == target, return mid c. if l part is sorted, move boundary d. if r part is sorted, move boudnary Time complexity: O(logN) Space: O(1) ''' class Solution: def search(self, nums: List[int], target: int) -> int: if not nums: # corner case return -1 l, r = 0, len(nums) - 1 while l <= r: mid = l + (r - l) // 2 if target == nums[mid]: return mid if nums[l] < nums[mid]: # 判断左边有序 if nums[l] <= target < nums[mid]: # 因为此时target != nums[mid] r = mid - 1 else: l = mid + 1 elif nums[l] == nums[mid]: # 左边与mid相等 l = mid + 1 elif nums[l] > nums[mid]: # 右边有序 if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 return -1
true
01aeba94e37e74be60c0b9232b80b18edcdf251e
lidongdongbuaa/leetcode2.0
/二叉树/路径和/257. Binary Tree Paths.py
2,842
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/2/26 16:16 # @Author : LI Dongdong # @FileName: 257. Binary Tree Paths.py '''''' ''' 题目分析 1.要求:Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 2.理解:scan all tree node and return string with -> 3.类型:binary tree path 4.确认输入输出及边界条件: input: tree root node with definition, the node's value range? N, number of node? N, repeated? Y ordered? N output: list[string] corner case: None:[] 5.方法及方法分析:DFS, BFS time complexity order: O(N) space complexity order: O(N) 6.如何考: 没法考oa ''' ''' dfs from top to bottom time complexity: O(n) space:O(n) skewed tree dfs(root, path) ''' class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: # corner case return [] self.res = [] def dfs(root, path): # scan every node and save leaf path to res if not root: # base case return if not root.left and not root.right: self.res.append(path[:]) if root.left: dfs(root.left, path + '->' + str(root.left.val)) if root.right: dfs(root.right, path + '->' + str(root.right.val)) return dfs(root, str(root.val)) return self.res ''' dfs iteration right - left ''' class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: # corner case return [] res = [] stack = [[root, str(root.val)]] while stack: root, path = stack.pop() if not root.left and not root.right: res.append(path[:]) if root.right: stack.append([root.right, path + '->' + str(root.right.val)]) if root.left: stack.append([root.left, path + '->' + str(root.left.val)]) return res ''' bfs ''' class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: # corner case return [] res = [] from collections import deque queue = deque([[root, str(root.val)]]) while queue: root, path = queue.popleft() if not root.left and not root.right: res.append(path[:]) if root.left: queue.append([root.left, path + '->' + str(root.left.val)]) if root.right: queue.append([root.right, path + '->' + str(root.right.val)]) return res
true
7fab504e2bf2fbdf95ba142fb630b38fb34b4ab4
lidongdongbuaa/leetcode2.0
/二分搜索/有明确的target/367. Valid Perfect Square.py
2,926
4.34375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/3/12 11:19 # @Author : LI Dongdong # @FileName: 367. Valid Perfect Square.py '''''' ''' 题目分析 1.要求:Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false 2.理解: find a number which could square as the given num 3.类型: search problem 4.确认输入输出及边界条件: input: int, num range? [1, 100000] output: T/F corner case: num <= 0? N num would be 1? Y -> T num is None? N 5.方法及方法分析:Brute force; binary search; Newton Method time complexity order: binary search O(logN) = Newton Method O(logN) < Brute force O(N) space complexity order: O(1) 6.如何考 ''' ''' A. Brute force Method: 1. traversal number from 1 to half of num to check if the number * number is num if true, return true else return False time complexity: O(n) space : O(1) 易错点: ''' class Num: def isSqare(self, num): # return True of square num, else return Faslse if num == 1: # corner case return 1 for i in range(1, num // 2): if i * i == num: return True return False ''' B. binary search the result from 1 to half of num Method: 1. set left boundary, l, as 1, set right boundary,r, as num//2 2. do while traversal, l <= r a. mid = (l + r)//2 b. check if the mid^2 == num? return True c. mid^2 < num l = mid + 1 d. mid^2 > num r = mid - 1 time O(logN) space O(1) ''' class Num: def isSquare(self, num: int): # return True if num is perfect square, False for no prefect square if num == 1: return True l = 1 r = num // 2 while l <= r: mid = (l + r) // 2 tmp = mid * mid if tmp == num: return True elif tmp < num: l = mid + 1 elif tmp > num: r = mid - 1 return False ''' test code input: 16 l:1, r:8 loop1: mid = 4 tmp = 16 tmp == num -> return True input: 14 = num l:1, r: 7 loop1: mid = 4 tmp = 16 tmp > num r = 3 loop2: mid = 2 tmp = 4 < num l = 2 + 1 = 3 loop3 mid = 3 tmp = 9 < num l = mid + 1 = 4 out of loop return False ''' ''' C.Newton time O(logN) space O(1) ''' class Solution: def isPerfectSquare(self, num: int) -> bool: if num == 1: return True x = num // 2 while x * x > num: x = (x + num // x) // 2 return x * x == num
true
c7c49fdd8806c4b5e06b0502cb892511d82cec67
lidongdongbuaa/leetcode2.0
/数据结构与算法基础/leetcode周赛/200301/How Many Numbers Are Smaller Than the Current Number.py
1,974
4.125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/3/1 11:32 # @Author : LI Dongdong # @FileName: How Many Numbers Are Smaller Than the Current Number.py '''''' ''' 题目分析 1.要求: 2.理解:in a arr, count how many elem in this list < list[i], output 3.类型:array 4.确认输入输出及边界条件: input: list, length? 2<= <= 500; value range? 0<= <= 100, repeated? Y, order? N output: list[int] corner case: None? N, only One? N 5.方法及方法分析: time complexity order: space complexity order: 6.如何考 ''' ''' A. Brute force Method: 1. scan elem in list one by one scan other elem in list count the numb of smaller save count in res 2. return res time complexity O(N**2), space O(N) 易错点: ''' class Solution: def smallerNumbersThanCurrent(self, nums): # return list[int] res = [] for i in range(len(nums)): tmp = 0 for j in range(0, i): if nums[j] < nums[i]: tmp += 1 for k in range(i + 1, len(nums)): if nums[k] < nums[i]: tmp += 1 res.append(tmp) return res ''' test case nums = [6,5,4,8] loop 1: i = 0 tmp = 0 j in (0,0) j in (1, 4) tmp + 1 + 1 = 2 res [2] loop 2: i = 1 tmp = 0 j in(0,1) j in (2,4) tmp + 1 res [2, 1] loop 3 i = 2 tmp = 0 j in (0:2) tmp 0 j in (3,4) tmp 0 res [2,1,0] loop 4 i = 3 tmp = 0 j in (0,3) tmp + 3 j in (4, 4) tmp + 0 res [2,1,0,3] ''' ''' B. optimized code ''' class Solution: def smallerNumbersThanCurrent(self, nums): # return list[int] res = [] for i in range(len(nums)): tmp = 0 for j in range(len(nums)): if j != i and nums[j] < nums[i]: tmp += 1 res.append(tmp) return res
true
51a7a056f3efed50e627e4e07e0b63053e4f499e
masskro0/test_generator_drivebuild
/utils/plotter.py
1,910
4.5625
5
"""This file offers several plotting methods to visualize functions or roads.""" import matplotlib.pyplot as plt import numpy as np def plotter(control_points): """Plots every point and lines between them. Used to visualize a road. :param control_points: List of points as dict type. :return: Void. """ point_list = [] for point in control_points: point_list.append((point.get("x"), point.get("y"))) point_list = np.asarray(point_list) x = point_list[:, 0] y = point_list[:, 1] plt.plot(x, y, '-og', markersize=10, linewidth=control_points[0].get("width")) plt.xlim([min(x) - 0.3, max(x) + 0.3]) plt.ylim([min(y) - 0.3, max(y) + 0.3]) plt.title('Road overview') plt.show() def plot_all(population): """Plots a whole population. Method starts a new figure for every individual. :param population: Population with individuals in dict form containing another dict type called control_points. :return: Void """ iterator = 0 while iterator < len(population): plotter(population[iterator].get("control_points")) iterator += 1 def plot_lines(lines): """Plots LineStrings of the package shapely. Can be also used to plot other geometries. :param lines: List of lines, e.g. LineStrings :return: Void """ iterator = 0 while iterator < len(lines): x, y = lines[iterator].xy plt.plot(x, y, '-og', markersize=3) iterator += 1 # plt.show() def plot_splines_and_width(width_lines, control_point_lines): """Plots connected control points with their width lines. :param width_lines: List of lines (e.g. LineStrings) which represent the width of a road segment. :param control_point_lines: List of connected control points (e.g. LineStrings). :return: Void. """ plot_lines(width_lines) plot_lines(control_point_lines) plt.show()
true
7265ea38cd157f595842c3ef9b309107ce72703a
FalseFelix/pythoncalc
/Mood.py
381
4.1875
4
operation=input("what mood are you in? ") if operation=="happy": print("It is great to see you happy!") elif operation=="nervous": print("Take a deep breath 3 times.") elif operation=="sad": print("kill yourself") elif operation == "excited": print("cool down") elif operation == "relaxed": print("drink red bull") else: print("I don't recognize this mood")
true
20b4b1e4590ec30986cd951656926c9777e9b35b
kingdayx/pythonTreehouse
/hello.py
1,232
4.21875
4
SERVICE_CHARGE = 2 TICKET_PRICE =10 tickets_remaining = 100 # create calculate_price function. It takes tickets and returns TICKET_PRICE * tickets def calculate_price(number_of_tickets): # add the service charge to our result return TICKET_PRICE * number_of_tickets + SERVICE_CHARGE while tickets_remaining: print("There are {} tickets remaining".format(tickets_remaining)) name = input("What is your name? ") tickets = input("Hey {} , How many tickets would you like? ".format(name)) try: tickets = int(tickets) if tickets > tickets_remaining: raise ValueError("There are only {} tickets remaining".format(tickets_remaining)) except ValueError as err: print("oh no! we ran into an issue. {} please try again".format(err)) else: total_cost = calculate_price(tickets) print("Your tickets cost only {}".format(total_cost)) proceed = input("Do you want to proceed? /n (Enter yes/no)") if proceed == "yes": # To do: gather credit card info and process it print("SOLD!!") tickets_remaining -= tickets else: print("Thank you, {}!!".format(name)) print("Tickets are sold out!!")
true
6bb6ae0cb5373c6619deda59adfbf5a33263419e
darshikasingh/tathastu_week_of_code
/day 3/program3.py
271
4.34375
4
def duplicate(string): duplicateString = "" for x in string: if x not in duplicateString: duplicateString += x return duplicateString string = input("ENTER THE STRING") print("STRING AFTER REMOVING DUPLICATION IS", duplicate(string))
true
b15f207ad94ebec1fd8365a66a54563c1589e958
vrashi/python-coding-practice
/upsidedowndigit.py
228
4.25
4
# to print the usside-down triangle of digits row = int(input("Enter number of rows")) a = row for i in range(row+1, 0, -1): for j in range(i+1, 2, -1): print(a, end = " ") a = a - 1 print() a = row
true
394e5870361f046e78b91c28e4a0b9584e2cb158
os-utep-master/python-intro-Jroman5
/wordCount.py
1,513
4.125
4
import sys import string import re import os textInput ="" textOutput ="" def fileFinder(): global textInput global textOutput if len(sys.argv) is not 3: print("Correct usage: wordCount.py <input text file> <output file>") exit() textInput = sys.argv[1] textOutput = sys.argv[2] if not os.path.exists(textInput): print("text file input %s doesn't exist! Exiting" %textInput) exit() #Reads file, removes punctuation and returns a list of words in alphabetical order, and in lowercase def fileReader(file): try: text = open(file,"r") words = text.read() pattern = "[\"\'!?;:,.-]" #table = words.maketrans("!;',.?:\"-"," ") #words = words.translate(table) words = re.sub(pattern," ",words) seperatedWords = words.split() seperatedWords = [element.lower() for element in seperatedWords] seperatedWords.sort() finally: text.close() return seperatedWords #Takes a list of words and places them in a dictionary with the word as a key and the occurrences as its value def wordCounter(words): wordCount = {} for x in words: if(x in wordCount): wordCount[x] = wordCount[x] + 1 else: wordCount[x] = 1 return wordCount #Writes the counted words to a file def fileWriter(countedWords): try: file = open(textOutput,"w+") for x in countedWords: file.write(x + " " + str(countedWords[x]) + "\n") finally: file.close() #main method if __name__=="__main__": fileFinder() organizedWords=fileReader(textInput) fileWriter(wordCounter(organizedWords))
true
0008d5d1d0598ec37b494351fe76f7d0fd49011b
AdityanBaskaran/AdityanInterviewSolutions
/Python scripts/evenumbers.py
371
4.125
4
listlength = int(input('Enter the length of the list ... ')) numlist = [] for x in range(listlength): number = int(input('Please enter a number: ')) numlist.append(number) numlist.sort() def is_even_num(l): enum = [] for n in l: if n % 2 == 0: enum.append(n) return enum print (is_even_num(numlist)) print (is_even_num(numlist))
true
4914e373050abc2fc202a357d4e8a82ee7bd87c7
laurakressin/PythonProjects
/TheHardWay/ex20.py
920
4.1875
4
from sys import argv script, input_file = argv # reads off the lines in a file def print_all(f): print f.read() # sets reference point to the beginning of the file def rewind(f): f.seek(0) # prints the line number before reading out each line in the file def print_a_line(line_count, f): print line_count, f.readline(), # sets var current_file to the second input in the argv current_file = open(input_file) # activating the defs print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" # setting variable current_line(1) current_line = 1 print_a_line(current_line, current_file) # incrementing variable current_line(2) current_line += 1 print_a_line(current_line, current_file) # again incrementing variable current_line(3) current_line += 1 print_a_line(current_line, current_file)
true
c9f68086ab8f97bad4b3b1c1961a0216f655f14c
cscoder99/CS.Martin
/codenow9.py
275
4.125
4
import random lang = ['Konichiwa', 'Hola', 'Bonjour'] user1 = raw_input("Say hello in English so the computer can say it back in a foreign langauge: ") if (user1 == 'Hello') or (user1 == 'hello'): print random.choice(lang) else: print "That is not hello in English"
true
2052521302b0654c70fc5e7065f4a2cd6ff71fb1
martinfoakes/word-counter-python
/wordcount/count__words.py
1,035
4.21875
4
#!/usr/bin/python file = open('word_test.txt', 'r') data = file.read() file.close() words = data.split(" ") # Split the file contents by spaces, to get every word in it, then print print('The words in this file are: ' + str(words)) num_words = len(words) # Use the len() function to return the length of a list (words) to get the word count, then print print('The number of words in this file is: ' + str(num_words)) lines = data.split('\n') # Split the file contents by \n to get each individual line, then print print('The separate lines in this file are: ' + str(lines)) # use the len() function again to get the number of lines there are print('The number of lines, including empty lines, is: ' + str(len(lines))) # To remove the empty lines from the array list, use a for loop # the NOT keyword automatically checks for emptiness, if the current entry is empty then it gets # removed from the array 'lines' for l in lines: if not l: lines.remove(l) print('The number of non-empty lines only is: ' + str(len(lines)))
true
fbc2c2b14924d71905b9ad9097f2e9d7c9e541fc
davidobrien1/Programming-and-Scripting-Exercises
/collatz.py
1,533
4.78125
5
# David O'Brien, 2018-02-09 # Collatz: https://en.wikipedia.org/wiki/Collatz_conjecture # Exercise Description: In the video lectures we discussed the Collatz conjecture. # Complete the exercise discussed in the Collatz conjecture video by writing a # single Python script that starts with an integer and repeatedly applies the # Collatz function (divide by 2 if even, multiply by three and add 1 if odd) using a # while loop and if statement. At each iteration, the current value of the integer # should be printed to the screen. You can specify in your code the starting # value of 17. If you wish to enhance your program, have the program ask the # user for the integer instead of specifying a value at the start of your code. # Add the script to your GitHub repository, as per the instruction in the # Assessments section. n = int(input("Please enter an integer: ")) # this line defines "n" and asks the user to input an integer. The int function converts the input to an integer while n > 1: # the while statement keeps looping through the code while n > 1 if(n % 2 == 0): # this if statement states that if the remainder of n divided by 2 is equal to 0 i.e an even number n = n/2 # n now becomes (n divided by 2) and print(n) # print the value of n elif(n % 2 == 1): # the elif statement says that, or else if the remainder of n divided by 2 is equal to 1 i.e an odd number n = n * 3 + 1 # n now becomes (n multiplied by 3 plus 1) and print(n) # print the value of n
true
d31bfb61f8e01688b186e6ccf860c12f8b1184de
j-kincaid/LC101-practice-files
/LC101Practice/Ch13_Practice/Ch13_fractions.py
543
4.21875
4
class Fraction: """ An example of a class for creating fractions """ def __init__(self, top, bottom): # defining numerator and denominator self.num = top self.den = bottom def __repr__(self): return str(self.num) + "/" + str(self.den) def get_numerator(self): return self.num def get_denominator(self): return self.den def main(): rug = Fraction(5, 7) print(rug) print(rug.get_numerator()) print(rug.get_denominator()) if __name__ == "__main__": main()
true
878934e0c30544f1b8c659ed41f789f20d9ac809
j-kincaid/LC101-practice-files
/LC101Practice/Ch10_Practice/Ch10Assign.py
1,008
4.15625
4
def get_country_codes(prices): # your code here """ Return a string of country codes from a string of prices """ #_________________# 1. Break the string into a list. prices = prices.split('$') # breaks the list into a list of elements. #_________________# 2. Manipulate the individual elements. #_________________# A. Remove integers # nation = prices[0], prices[1] length = len(prices) for nation in (prices): nation == prices[0:] print(nation) #_________________# B. nations = [] for each_char in (0, prices, 2): if each_char in prices[0:2]: nation = each_char nations = list(nations) # lastitem = nations.pop() print(nations) #_________________# 3. Make it back into a string. # set = [] # my_list = ["happy"] # my_str = my_list[0][3:] # my_str == 'py' # True ## Jonathan's example from slack # print(" ".join(prices)) # don't include these tests in Vocareum
true
01c29535868a34895b949fa842ba41393251e622
j-kincaid/LC101-practice-files
/LC101Practice/Ch9_Practice/Ch_9_Str_Methods.py
880
4.28125
4
#___________________STRING METHODS # Strings are objects and they have their own methods. # Some methods are ord and chr. # Two more: ss = "Hello, Kitty" print(ss + " Original string") ss = ss.upper() print(ss + " .upper") tt = ss.lower() print(tt + " .lower") cap = ss.capitalize() # Capitalizes the first character only. print(cap + " .capitalize") strp = ss.strip() # Returns a string with the print(strp + " .strip") ## leading and trailing whitespace removed. lstrp = ss.lstrip() print(lstrp + " .lstrip") # Returns a string with the leading # whitespace removed. rstrp = ss.rstrip() print(rstrp + " .rstrip") # Returns a string with the trailing # whitespace removed. cout = ss.count("T") # Returns number of occurrences of a character print(cout) news = ss.replace("T", "^") # replaces all occurrences of an old substring print(news) # with a new one.
true
c2570e4c6ef6f4d83565952d783fa681eed14981
lunaxtasy/school_work
/primes/prime.py
670
4.34375
4
""" Assignment 3 - Prime Factors prime.py -- Write the application code here """ def generate_prime_factors(unprime): """ This function will generate the prime factors of a provided integer Hopefully """ if isinstance(unprime, int) is False: raise ValueError factors = [] #for calls of 1, which is not prime while unprime < 2: break #for calls of 2, which is prime else: for prime_fac in range(2, unprime + 1): while (unprime % prime_fac) == 0: #checking that the remainder is 0 factors.append(prime_fac) unprime = unprime // prime_fac return factors
true
b241bbd11590407332240b8254c911742e4382cc
TangMartin/CS50x-Introduction-to-Computer-Science
/PythonPractice/oddoreven.py
264
4.28125
4
number = -1 while(number <= 0): number = int(input("Number: ")) if(number % 2 == 0 and number % 4 != 0): print("Number is Even") elif(number % 2 == 0 and number % 4 == 0): print("Number is a multiple of four") else: print("Number is Odd")
true
36020e1b3eaa7ce3cfd732813f6f86b0948245e3
Kartavya-verma/Competitive-Pratice
/Linked List/insert_new_node_between_2_nodes.py
1,888
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def inserthead(self, newnode): tempnode = self.head self.head = newnode self.head.next = tempnode del tempnode def listlength(self): currentnode = self.head len = 0 while currentnode is not None: len += 1 currentnode = currentnode.next return len def insertat(self, newnode, pos): if pos < 10 or pos > self.listlength(): print("Invalid Position") return if pos is 0: self.inserthead(newnode) return currentnode = self.head currentpos = 0 while True: if currentpos == pos: previousnode.next = newnode newnode.next = currentnode break previousnode = currentnode currentnode = currentnode.next currentpos += 1 def insertend(self, newnode): if self.head is None: self.head = newnode else: lastnode = self.head while True: if lastnode.next is None: break lastnode = lastnode.next lastnode.next = newnode def printlist(self): if self.head is None: print("List is empty") return currentnode = self.head while True: if currentnode is None: break print(currentnode.data) currentnode = currentnode.next firstNode = Node(10) linkedlist = LinkedList() linkedlist.insertend(firstNode) secondnode = Node(20) linkedlist.insertend(secondnode) thirdnode = Node(15) linkedlist.insertat(thirdnode, 10) linkedlist.printlist()
true
34e7f7e3d1b5c3688c8091c12c360da3f4563c45
PoojaKushwah1402/Python_Basics
/Sets/join.py
1,642
4.8125
5
# join Two Sets # There are several ways to join two or more sets in Python. # You can use the union() method that returns a new set containing all items from both sets, # or the update() method that inserts all the items from one set into another: # The union() method returns a new set with all items from both sets: set1 = {"a", "b" , "c",1,2} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) # The update() method inserts the items in set2 into set1: set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set1.update(set2) print(set1) #The intersection_update() method will keep only the items that are present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple1"} x.intersection_update(y) print(x) # The intersection() method will return a new set, that only contains the items that are present in both sets. # Return a set that contains the items that exist in both set x, and set y: x = {"apple", "banana", "cherry",'apple'} y = {"google", "microsoft", "apple",'apple'} z = x.intersection(y) print(z) # The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. # Keep the items that are not present in both sets: x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(x) # The symmetric_difference() method will return a new set, that contains only the elements that are NOT # present in both sets. # Return a set that contains all items from both sets, except items that are present in both: x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) print(z)
true
52355dd175d820141ce23ace508c0c73501a74b0
PoojaKushwah1402/Python_Basics
/variable.py
809
4.34375
4
price =10;#this value in the memory is going to convert into binary and then save it price = 30 print(price,'price'); name = input('whats your name ?') print('thats your name '+ name) x, y, z = "Orange", "Banana", "Cherry" # Make sure the number of variables matches the number of values, or else you will get an error. print(x,'x') print(y,'y') print(z,'z') #python needs to externally typecast the values it doesnt typecast internally # int()#converts to integer # str()# converts to string # type()# gives the current data type of variable # Python has no command for declaring a variable. # A variable is created the moment you first assign a value to it. #Python is case sensitive #Multi Words Variable Names #Camel Case - myVariableName #Pascal Case - MyVariableName #snake Case - my_variable_name
true
692f1ef93f6b188a9a3244d45c73239e18ded92c
PoojaKushwah1402/Python_Basics
/Sets/sets.py
999
4.15625
4
# Set is one of 4 built-in data types in Python used to store collections of data. # A set is a collection which is both unordered and unindexed. # Sets are written with curly brackets. # Set items are unordered, unchangeable, and do not allow duplicate values. # Set items can appear in a different order every time you use them, and cannot be referred to by index or key. # Sets cannot have two items with the same value. #**Once a set is created, you cannot change its items, but you can add new items. thisset = {"apple", "banana", "cherry"} thisnewset = set(("apple", "banana", "cherry",'banana')) # note the double round-brackets print(thisset,thisnewset) # You cannot access items in a set by referring to an index or a key. # But you can loop through the set items using a for loop, or ask if a specified value is # present in a set, by using the in keyword. thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) #if set is not changable then how can we add items to it?
true
9df5a51bffcc602bc34b04de97ef2b65e1a7759f
PoojaKushwah1402/Python_Basics
/List/list.py
1,906
4.4375
4
#Unpack a Collection # If you have a collection of values in a list, tuple etc. Python allows you extract the #values into variables. This is called unpacking. fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x,'x') print(y,'y') print(z,'z') # Lists are one of 4 built-in data types in Python used to store collections of data, the other # 3 are Tuple, Set, and Dictionary, all with different qualities and usage. #To determine how many items a list has, use the len() function: #Negative indexing means start from the end #-1 refers to the last item, -2 refers to the second last item etc. thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(len(thislist)) print(type(thislist)) #<class 'list'> print(thislist[2:5]) #To determine if a specified item is present in a list use the in keyword: if "apple" in thislist: print("Yes, 'apple' is in the fruits list") print('here') thislist[1:5] = ['hell','no'] print(thislist) thislist.insert(2, "watermelon") print(thislist)#['apple', 'hell', 'watermelon', 'no', 'melon', 'mango'] #To add an item to the end of the list, use the append() method: # To insert a list item at a specified index, use the insert() method. # The insert() method inserts an item at the specified index: #To append elements from another list to the current list, use the extend() method. tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) #The remove() method removes the specified item. thislist.remove("banana") #The pop() method removes the specified index. #If you do not specify the index, the pop() method removes the last item. thislist.pop(1) #The del keyword also removes the specified index: del thislist[0] #The del keyword can also delete the list completely. del thislist #The clear() method empties the list. thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist)
true
6811f8a6667506b20213934697e0b3207ace1520
tskiranmayee/Python
/5. Set&Tuples&Dictionary/AccessingItems.py
393
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue May 18 15:49:01 2021 @author: tskir """ """ Accessing Items in Dictionary """ dictEx={1:"a",2:"b",3:"c",4:"d"} i=dictEx[1] print("Value of the key 1 is: {}".format(i)) """Another way of Accessing Items in Dictionary""" j=dictEx.get(1) print("Another way to get value for key 1 is:{}".format(j)) """ Access the keys""" k=dictEx.keys() print(k)
true
c2e88d79e03904bc41c849691d12962c9165c683
Marlon-Poddalgoda/ICS3U-Assignment5-B-Python
/times_table.py
1,287
4.1875
4
#!/usr/bin/env python3 # Created by Marlon Poddalgoda # Created on December 2020 # This program calculates the times table of a user input import constants def main(): # this function will calculate the times table of a user input print("This program displays the multiplication table of a user input.") print("") # loop counter variable loop_counter = 0 # sum of positive integers variable answer = 0 # input user_input = input("Enter a positive integer: ") print("") # process try: user_input_int = int(user_input) if user_input_int > 0: # loop statement while loop_counter <= constants.MAX_MULTIPLICATION: # calculations answer = user_input_int * loop_counter print("{0} x {1} = {2}".format(user_input_int, loop_counter, answer)) loop_counter = loop_counter + 1 else: # output print("{} is not a positive integer!" .format(user_input_int)) except Exception: # output print("That's not a number! Try again.") finally: print("") print("Thanks for playing!") if __name__ == "__main__": main()
true
ad841fe2c7b77c9f500e9a1962d9460b3dfc0425
sweetmentor/try-python
/.~c9_invoke_74p4L.py
2,562
4.3125
4
# print('Hello World') # print('Welcome To Python') # response = input("what's your name? ") # print('Hello' + response) # # print('please enter two numbers') # a = int(input('enter number 1:')) # b = int(input('enter number 2:')) # print(a + b) # num1 = int(input("Enter First Number: ")) # num2 = int(input("Enter Second Number: ")) # total = num1 + num2 # print (str(num1)) #print(str(num1) + " plus " + str(num2) + " = " + str(total)) # print("Before the function") # def add(x, y): # print(x) # print(y) # return x + y # print("After the function") # print("Before calling the function") # r = add(5, 4) # print("After calling the function") # print(r) # print("After printing the result") # text = input("what is your name:") # text = text.upper() # print(text) #-------------------challenge47---- # num = int(input("please enter your number")) # if num <= 10: # print ("Small") # else: # print ("Big") #-------------------challenge48---- # num1 = int(input("enter num1:")) # num2 = int(input("enter num2:")) # if num1 == num2: # print ("Same") # else: # print ("Different") #-------------challenge49------- # num = input("enter a number:") # if num == "1": # name = input("please enter your name") # print ("Your name is %s" % name) # if num == "2": # age = input("enter your age: ") # age_int = int(age) # print ("Your age is " + age) # print("done") #---------------------------- # i = 0 # while i < 100: # print(i) # i += 2 # i = 0 # while i < 100: # print(i) # i += 1 # i = 0 # while i < 100: # i += 1 # print(i) #---------------------------------- # people = { # "Joe": 23, # "Ann": 24, # "Barbara": 67, # "Pete": 55, # "Tim": 34, # "Sam": 13, # "Josh": 5 # } # name = input("Enter name: ") # print (people[name]) #----------------------------------- # people = { # "Joe": {"age": 23, "eyes": "blue", "height": 134, "nationality": "Irish"}, # "Ann": {"age": 13, "eyes": "green", "height": 172, "nationality": "Irish"}, # "Bob": {"age": 23, "eyes": "red", "height": 234, "nationality": "Turkmenistan"}, # "Sam": {"age": 45, "eyes": "grey", "height": 134, "nationality": "French"}, # "Tina": {"age": 46, "eyes": "blue", "height": 154, "nationality": "American"}, # } # name = input("Enter name: ") # person = people[name] # what = input("What do you want to know? ") # print (person[what]) #-------------------------------------------- nums = [] for i in range (10) num = int(in)
true
88a00a55774274724298e6641d778fc1ef0e77d7
pavelgolikov/Python-Code
/Data_Structures/Linked_List_Circular.py
1,978
4.15625
4
"""Circular Linked List.""" class _Node(object): def __init__(self, item, next_=None): self.item = item self.next = next_ class CircularLinkedList: """ Circular collection of LinkedListNodes === Attributes == :param: back: the lastly appended node of this CircularLinkedList :type back: LinkedListNode """ def __init__(self, value): """ Create CircularLinkedList self with data value. :param value: data of the front element of this circular linked list :type value: object """ self.back = _Node(value) # back.next_ corresponds to front self.back.next = self.back def __str__(self): """ Return a human-friendly string representation of CircularLinkedList self :rtype: str >>> lnk = CircularLinkedList(12) >>> str(lnk) '12 ->' """ # back.next_ corresponds to front current = self.back.next result = "{} ->".format(current.item) current = current.next while current is not self.back.next: result += " {} ->".format(current.item) current = current.next return result def append(self, value): """ Insert value before LinkedList front, i.e. self.back.next_. :param value: value for new LinkedList.front :type value: object :rtype: None >>> lnk = CircularLinkedList(12) >>> lnk.append(99) >>> lnk.append(37) >>> print(lnk) 12 -> 99 -> 37 -> """ self.back.next = _Node(value, self.back.next) self.back = self.back.next def rev_print(self, current): if current == self.back: print(self.back.item) else: self.rev_print(current.next) print(current.item) # cl = CircularLinkedList(12) # cl.append(13) # cl.append(14) # cl.rev_print(cl.back.next)
true
dbaa1a417e12832ee0865031534e3d04de7e6d04
pavelgolikov/Python-Code
/Old/Guessing game.py
808
4.15625
4
import random number = random.randint (1,20) i=0 print ('I am thinking about a number between 1 and 20. Can you guess what it is?') guess = int(input ()) #input is a string, need to convert it to int while number != guess: if number > guess: i=i+1 print ('Your guess is too low. You used '+ str(i) + ' attempts. Try again') guess = int(input ()) continue #Need to tell computer to return back to while loop elif number < guess: i=i+1 #Up the counter before reporting back print ('Your guess is too high. You used '+ str(i) + ' attempts. Try again') #dont need to up the counter again guess = int(input ()) continue else: break i=i+1 print ('That is correct! You guessed it in ' + str (i) + ' guesses')
true
9d841232854343600926341d118f977d258536be
pavelgolikov/Python-Code
/Old/Dictionary practice.py
1,576
4.1875
4
"""Some functions to practice with lists and dictionaries.""" def count_lists(list_): """Count the number of lists in a possibly nested list list_.""" if not isinstance(list_, list): result = 0 else: result = 1 for i in list_: print(i) result = result + (count_lists(i)) return result def flatten_list(a, result=None): """Flattens a nested list. >>> flatten_list([ [1, 2, [3, 4] ], [5, 6], 7]) [1, 2, 3, 4, 5, 6, 7] """ if result is None: result = [] for x in a: if isinstance(x, list): flatten_list(x, result) else: result.append(x) return result def flatten_dictionary(dic, key = '', result = None): """Flatten dictionary dic.""" if result is None: result = {} for x, y in dic.items(): if isinstance(y, dict): flatten_dictionary(y, str(key)+str(x)+'.', result) else: result[str(key)+str(x)] = y return result def contains_satisfier(list_): """Check if a possibly nested list contains satisfier.""" res = False if not isinstance(list_, list): res = list_ > 5 else: for el in list_: res = res or contains_satisfier(el) return res def tree_reverse(lst): lst.reverse() list_ = [] for el in lst: if isinstance(el, list): list_ += [tree_reverse(el)] else: list_.append(el) return list_
true
3e43132819bc8bae1eb277d76ca981b9827fcde4
enrique95ae/Python
/Project 01/test007.py
391
4.1875
4
monday_temperatures = [9.1, 8.8, 7.5, 6.6, 8.9] ##printing the number of items in the list print(len(monday_temperatures)) ##printing the item with index 3 print(monday_temperatures[3]) ##printing the items between index 1 and 4 print(monday_temperatures[1:4]) ##printing all the items after index 1 print(monday_temperatures[1:]) ##printing the last item print(monday_temperatures[-1])
true
835bbc207ec0ffb49e6a0edcf82dc3aeb3b28504
fbakalar/pythonTheHardWay
/exercises/ex26.py
2,999
4.25
4
#---------------------------------------------------------| # # Exercise 26 # Find and correct mistakes in someone else's # code # # TODO: go back and review ex25 # compare to functions below # make sure this can be run by importing ex25 # #---------------------------------------------------------| def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) def print_first_word(words): #corrected mistake added ':' """Prints the first word after popping it off.""" word = words.pop(0) #corrected mistake poop>pop print word def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) #corrected mistake added ')' print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" five = 10 - 2 + 3 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 #corrected '\' > '/' crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) #corrected ==:= and start-point print "With a starting point of: %d" % start_point print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) # corrected 'jeans' start_point = start_point / 10 print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) #corrected start_pont sentence = "All good\tthings come to those who wait." #corrected god,weight # words = ex25.break_words(sentence) words = break_words(sentence) #sorted_words = ex25.sort_words(words) sorted_words = sort_words(words) print_first_word(words) print_last_word(words) print_first_word(sorted_words) #corrected print_last_word(sorted_words) #sorted_words = ex25.sort_sentence(sentence) sorted_words = sort_sentence(sentence) print sorted_words #corrected print_first_and_last(sentence) #corrected print_first_and_last_sorted(sentence) #corrected
true
1832a289dececef43f9f2e08eaf902bc5ced7016
fbakalar/pythonTheHardWay
/exercises/ex22.py
1,248
4.1875
4
##################################################### # # Exercise 22 from Python The Hard Way # # # C:\Users\berni\Documents\Source\pythonTheHardWay\exercises # # # What do you know so far? # # TODO: # add some write up for each of these # ##################################################### ''' this is a list of all the key words and symbols used in exercises 1 - 21 print: + plus - minus / slash * asterisk % percent < less-than > greater-than <= less-than-equal >= greater-than-equal %s %d %r True False binary \t \n \\ raw_input() from sys import argv sys argv prompt txt = open(filename) print txt.read() FILE OPERATIONS ---------------- close -- Closes the file. Like File->Save.. in your editor. read -- Reads the contents of the file. You can assign the result to a variable. readline -- Reads just one line of a text file. truncate -- Empties the file. Watch out if you care about the file. write('stuff') -- Writes "stuff" to the file. from os.path import exists indata = in_file.read() len(indata) out_file = open(to_file, 'w') out_file.write(indata) def print_two(*args) def rewind(f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() return '''
true
d8feb89430783948201453c395aa1d4a3c1ab9d2
meet-projects/TEAMB1
/test.py
305
4.15625
4
words=["ssd","dsds","aaina","sasasdd"] e_word = raw_input("search for a word in the list 'words': ") check = False for word in words: if e_word in word or word in e_word: if check==False: check=True print "Results: " print " :" + word if check==False: print "Sorry, no results found."
true
63f15390b441813b85bfa8c35efa0a06db9be552
lachlanpepperdene/CP1404_Practicals
/Prac02/asciiTable.py
434
4.3125
4
value = (input("Enter character: ")) print("The ASCII code for",value, "is",ord(value),) number = int(input("Enter number between 33 and 127: ")) while number > 32 and number < 128: print("The character for", number, "is", chr(number)) else: print("Invalid Number") # Enter a character:g # The ASCII code for g is 103 # Enter a number between 33 and 127: 100 # The character for 100 is d
true
ecee3c7834b468cec5f437d173b91fc9665f63d1
Git-Pierce/Week8
/MovieList.py
1,487
4.21875
4
def display_menu(): print("MOVIE LIST MENU") print("list - List all movies") print("add - Add a movie") print("del - Delete a movie") print("exit - Exit program") print() def list(movie_list): i = 1 for movie in movie_list: print(str(i) + "- " + movie) i += 1 print() def add(movie_list): #mutable list movie = input("Name: ") movie_list.append(movie) print(movie + " was added. \n") def delete(movie_list): number = int(input("Enter Movie Number: ")) if number < 1 or number > len(movie_list): print("Invalid movie num. \n") else: movie = movie_list.pop(number-1) print(movie + " was deleted. \n") def main(): movie_list = ["Month Python", "Lord of the Rings", "Titanic"] command_list = ["list", "add", "del", "exit"] display_menu() # code to process each choice made #for i in range (5): m_command = input("Enter a valid movie list menu option: ") while m_command in command_list: if m_command == "list": list(movie_list) elif m_command == "add": add(movie_list) elif m_command == "del": delete(movie_list) elif m_command == "exit": break else: print("Not a valid movie list command. Try again.\n") m_command = input("Enter a valid movie list menu option: ") print("Movie List program ended.") main()
true
1d66b04c774e3346197d17c4ca559a4c5642f3e9
green-fox-academy/Chiflado
/week-03/day-03/horizontal_lines.py
528
4.40625
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() # create a line drawing function that takes 2 parameters: # the x and y coordinates of the line's starting point # and draws a 50 long horizontal line from that point. # draw 3 lines with that function. def drawing_horizontal_lines(x, y): red_line = canvas.create_line(x, y, x + 50, y, fill = 'green') drawing_horizontal_lines(110, 190) drawing_horizontal_lines(240, 30) drawing_horizontal_lines(69, 110) root.mainloop()
true
95908f7ea38b97f342408bbdeac0b56f276d74d5
green-fox-academy/Chiflado
/week-02/day-02/matrix.py
539
4.125
4
# - Create (dynamically) a two dimensional list # with the following matrix. Use a loop! # # 1 0 0 0 # 0 1 0 0 # 0 0 1 0 # 0 0 0 1 # # - Print this two dimensional list to the output def matrix2d(x, y): matrix = [] for i in range(x): row = [] for j in range(y): if i == j: row.append(1) else: row.append(0) matrix.append (row) return matrix for row in matrix2d(4, 4): for elem in row: print(elem, end=' ') print()
true
eccb62bc74d79af4e65142572fdb175ff1ca479d
green-fox-academy/Chiflado
/week-02/day-05/anagram.py
395
4.21875
4
first_string = input('Your first word: ') sorted_first = sorted(first_string) second_string = input('Aaaaand your second word: ') sorted_second = sorted(second_string) def anagram_finder(sorted_first, sorted_second): if sorted_first == sorted_second: return 'There are anagrams!' else: return 'There aren\'t anagrams!' print(anagram_finder(sorted_first, sorted_second))
true
6f52eeb81dedf18d2dc0b356e818818a953fcad5
alessandraburckhalter/python-rpg-game
/rpg-1.py
2,163
4.15625
4
"""In this simple RPG game, the hero fights the goblin. He has the options to: 1. fight goblin 2. do nothing - in which case the goblin will attack him anyway 3. flee""" print("=-=" * 20) print(" GAME TIME") print("=-=" * 20) print("\nRemember: YOU are the hero here.") # create a main class to store info for all characters class Character: def __init__(self, health, power, name): self.health = health self.power = power self.name = name def alive(self): if self.health > 0: return True else: return False def attack(self, enemy): enemy.health -= self.power return enemy.health def print_status(self): print(f"{self.name} has {self.health} health and {self.power} power.") # create a main function def main(): goblin = Character(6, 2, "Globin") hero = Character(10, 5, "Hero") while goblin.alive() and hero.alive(): user_input = int(input("\nWhat do you want to do?\n1. fight goblin\n2. do nothing\n3. flee\n> ")) # Print hero and goblin status after each user input hero.print_status() goblin.print_status() if user_input == 1: # Hero attacks goblin hero.attack(goblin) if not hero.alive(): print("\nYou are dead.") if goblin.health > 0: # Goblin attacks hero goblin.attack(hero) if not goblin.alive(): print("\nGoblin is dead.") if goblin.alive(): print("\nGoblin still in the game. Watch out.") elif user_input == 2: # Hero does nothing, but Goblin still attacking goblin.attack(hero) print("\nOops. Goblin has attacked you! Fight back!") if not goblin.alive(): print("\nGoblin is dead.") if not hero.alive(): print("\nYou are dead. Too late to fight back :(") elif user_input == 3: print("\nGoodbye.") break else: print("\nInvalid input %r" % user_input) main()
true
88561d8cc5a2b0a3778877fbf87a05d0a378d21d
gssasank/UdacityDS
/DataStructures/LinkedLists/maxSumSubArray.py
805
4.25
4
def max_sum_subarray(arr): current_sum = arr[0] # `current_sum` denotes the sum of a subarray max_sum = arr[0] # `max_sum` denotes the maximum value of `current_sum` ever # Loop from VALUE at index position 1 till the end of the array for element in arr[1:]: ''' # Compare (current_sum + element) vs (element) # If (current_sum + element) is higher, it denotes the addition of the element to the current subarray # If (element) alone is higher, it denotes the starting of a new subarray ''' current_sum = max(current_sum + element, element) # Update (overwrite) `max_sum`, if it is lower than the updated `current_sum` max_sum = max(current_sum, max_sum) return max_sum # FLAGGED
true
562547cb28e651432ca6be189ebd212e0ba50d31
gssasank/UdacityDS
/PythonBasics/conditionals/listComprehensions.py
784
4.125
4
squares = [x**2 for x in range(9)] print(squares) #if we wanna use an if statement squares = [x**2 for x in range(9) if x % 2 == 0] print(squares) #if we wanna use an if..else statement, it goes in the middle squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)] print(squares) # QUESTIONS BASED ON THE CONCEPT #Q1 names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"] first_names =[name.split()[0].lower() for name in names] print(first_names) #Q2 multiples_3 = [num for num in range(3,63) if num%3 == 0] print(len(multiples_3)) #Q3 scores = { "Rick Sanchez": 70, "Morty Smith": 35, "Summer Smith": 82, "Jerry Smith": 23, "Beth Smith": 98 } passed = [key for key, value in scores.items() if value>=65] print(passed)
true
e6908a1fede2583910d752dec6b6af8ddf2a0460
gssasank/UdacityDS
/PythonBasics/functions/scope.py
483
4.1875
4
egg_count = 0 def buy_eggs(): egg_count += 12 # purchase a dozen eggs buy_eggs() #In the last video, you saw that within a function, we can print a global variable's value successfully without an error. # This worked because we were simply accessing the value of the variable. # If we try to change or reassign this global variable, however, as we do in this code, we get an error. # Python doesn't allow functions to modify variables that aren't in the function's scope.
true
188bd91cfa5302a8cc99c2f09e4aa376c35895b7
gredenis/-MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/ProblemSet1/Problem3.py
1,187
4.25
4
# Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, # if s = 'azcbobobegghakl', then your program should print # Longest substring in alphabetical order is: beggh # In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print # Longest substring in alphabetical order is: abc # Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, # we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had # a break and cleared your head. temp = '' longest = '' number = 0 while True: if number == len(s): break elif temp == '': temp = s[number] number += 1 elif s[number] >= s[number - 1]: temp = temp + s[number] number += 1 if len(temp) > len(longest): longest = temp else: if len(temp) > len(longest): longest = temp temp = '' else: temp = '' print(longest)
true
ec72975409e3eda6707fcb67778244299c00431e
Rhotimie/ZSSN
/lib/util_sort.py
1,361
4.125
4
import itertools def sort_tuple_list(tuple_list, pos, slice_from=None): """ Return a List of tuples Example usage: sort_tuple_list([('a', 1), ('b', 3), ('c', 2)]) :param status: list of tuples :type status: List :param list: :param int: :return: sorted list of tuples e.g [('a', 1), ('c', 2) ('b', 3)] usig element at pos 1 to sort """ if tuple_list and type(tuple_list) == list: if pos >= len(tuple_list[0]): return None slice_from = len(tuple_list) if not slice_from else slice_from return sorted(tuple_list, key = lambda i: i[pos], reverse = True)[:slice_from] return [] def grouper(n, iterable, is_fill=False, fillvalue=None): """ split a list into n desired groups Example list(grouper(3, range(9))) = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] :return: list of tuples """ args = [iter(iterable)] * n if is_fill: return list(itertools.zip_longest(*args, fillvalue=fillvalue)) else: return list([e for e in t if e != None] for t in itertools.zip_longest(*args)) def un_grouper(list_of_lists): """ combines a list of lists into a single list Example grouper([(0, 1, 2), (3, 4, 5), (6, 7, 8)]) = list(range(9)) :return: list of tuples """ return list(itertools.chain.from_iterable(list_of_lists))
true
b445be9fa502014837bbc795a20d74940eb7d72d
NotBobTheBuilder/conways-game-of-life
/conways.py
2,242
4.125
4
from itertools import product from random import choice def cells_3x3(row, col): """Set of the cells around (and including) the given one""" return set(product(range(row-1, row+2), range(col-1, col+2))) def neighbours(row, col): """Set of cells that directly border the given one""" return cells_3x3(row, col) - {(row, col)} class CGOL(object): """Iterator representing the generations of a game""" def __init__(self, grid): """ Takes a 2d list of bools as a grid which is used to create internal representation of game state (a set of living coordinates) """ self.cells = {(row_i, col_i) for row_i, row in enumerate(grid) for col_i, alive in enumerate(row) if alive} def __iter__(self): """Iterator progressing through each round until all cells are dead""" yield self while self.cells: self.cells = set(filter(self.cell_survives, self.cells_to_check())) yield self def __str__(self): """Represent the round as a 2d grid of + or . for alive or dead""" return '\n'.join(''.join('+' if self.cell_alive((r, c)) else '.' for c in range(20)) for r in range(20)) def cell_alive(self, cell): """Checks if the given cell is alive or dead""" return cell in self.cells def cell_survives(self, cell): """Checks if the given cell makes it to the next generation""" neighbours = self.neighbour_count(*cell) return neighbours == 3 or neighbours == 2 and self.cell_alive(cell) def neighbour_count(self, row, col): """Number of living neighbours surrounding the given cell""" return len(set(filter(self.cell_alive, neighbours(row, col)))) def cells_to_check(self): """Cells which could be alive in the next generation""" return {border for cell in self.cells for border in cells_3x3(*cell)} if __name__ == "__main__": game = CGOL([[choice([True, False]) for r in range(20)] for c in range(20)]) for round, grid in zip(range(40), game): print("===== round {} =====".format(round)) print(grid)
true
2355ee5a02dcbc66d33649b618d1c57e356e9ada
jamj2000/Programming-Classes
/Math You Will Actually Use/Week6_Sympy.py
725
4.3125
4
' "pip install sympy" before you do any of this ' import sympy # import the calculator with variable buttons :) from sympy import Symbol # -------------------------- first, solve the simple equation 2*x=2 x = Symbol('x') # create a "symoblic variable" x equation = 2*x - 2 # define the equation 2*x = 2 solution = sympy.solve(equation, x) # solve for x print(solution) # print the list of all solutions # -------------------------- next, lets do the equation of a circle y = Symbol('y') equation = x**2 + y**2 - 1**2 # x**2 + y**2 = r**2 where r =1 solution = sympy.solve(equation, y) # solve for y print(solution) # notice how one is the TOP half of the circle # and the other in the list is the BOTTOM half
true
0b6dae16fec055ad0eccb3d651b02f5643540e81
jamj2000/Programming-Classes
/Intro To Python/semester1/Week10_Challenge0.py
1,798
4.34375
4
''' This is a deep dive into FUNCTIONS What is a function? A function is a bunch of commands bundled into a group How do you write a function? Look below! CHALLENGES: (in order of HEAT = difficulty) Siberian Winter: Change the link of the Philly function Canada in Spring: Make the link an input to Philly, not a constant Spring in California: Convert Antonia's inputs to named inputs Summer in California: Write a new function which adds two numbers Rocket Engine: Convert these functions into a CLASS ''' import webbrowser def Franko(): print('Hello from Franko, the simple function') def Philly(): print('Hello from Philly, the funky phunction') print('You see, you can do a lot of stuff in one function') print('Like taking the square root of 1,245 to the power of pi!') import math sqrt1245_pi = math.sqrt(1245)**math.pi print('Which is exactly... ', sqrt1245_pi) print('You can even do fun stuff in here... Check this out...') webbrowser.open('http://www.jonnyhyman.com') def Antonia(argument1, argument2, TheyDontAllNeedToSayArgumentThough): print('Hello from Antonia, the fun function with fun inputs') print('These are my arguments:') print(argument1) print(argument2) print(TheyDontAllNeedToSayArgumentThough) webbrowser.open('https://media.giphy.com/media/R8n7YlPHe34dy/giphy.gif') def Kevin(named_argument = 'Wut', other_one = 'Hah', herp = 'derp' ): print('Hello from Kevin the function with NAMED inputs...') print('My inputs were...', named_argument, other_one, herp) #input(" ----> Notice how none of the functions run until you call them" # " //// [ENTER] to continue") print('_______________') # some space to be able to read easier Antonia()
true
ad291e7fa25471945efc95465a4589cd89a44e7a
mihir-liverpool/RockPaperScissor
/rockpaperscissor.py
841
4.125
4
import random while True: moves = ['rock', 'paper', 'scissor'] player_wins = ['paperrock', 'scissorpaper', 'rockscissor'] player_move = input('please choose between rock paper or scissor: ') computer_move = random.choice(moves) if player_move not in moves: print('please choose an option between rock paper and scissor') elif computer_move == player_move: print ('your move was ', player_move) print ('computers move was', computer_move) print('That is a draw, please try again') elif player_move+computer_move in player_wins: print('your move was ', player_move) print('computers move was', computer_move) print('you win') else: print('your move was ', player_move) print('computers move was', computer_move) print('you lose')
true
1dbd6a073c1fbdae4bdc435d7a678e49e8709ab3
sombra721/Python-Exercises
/Regular Expression_ex.py
1,503
4.125
4
''' The script will detect if the regular expression pattern is contained in the files in the directory and it's sub-directory. Suppose the directory structure is shown as below: test |---sub1 | |---1.txt (contains) | |---2.txt (does not contain) | |---3.txt (contains) |---sub2 | |---1.txt (contains) | |---2.txt (contains) | |---3.txt (contains) |---sub3 |---|---sub3-1 The result will be: {"sub1": 2, "sub2": 3,"sub3": 0,"sub3\sub3-1": 0} Running the script with the two arguments: 1. Tha path to be traversal. 2. Ragular Expression pattern. e.g.: python re_traversal.py C:/test ("^[a-zA-Z]+_TESTResult.*") ''' import sys import os import re import pylab def draw_graph(result): names = result.keys() counts = result.values() pylab.xticks(range(len(names)), names) pylab.plot(range(len(names)), counts, "b") pylab.show() def main(argv): result = {} for path, subdirs, files in os.walk(argv[1]): for subdir in subdirs: result[os.path.join(path, subdir)[len(argv[1])+1:]] = 0 for name in files: if re.search(argv[2], open(os.path.join(path, name), 'r').read()): result[os.path.join(path, name)[len(argv[1])+1:-len(name)]] = result.get(os.path.join(path, name)[len(argv[1])+1:-len(name)], 0) + 1 if result: print result else: print "No match detected." draw_graph(result) if __name__ == '__main__': main(sys.argv)
true
8ae7109db20182e8e0367a39c03fa9e4dd04dba5
ryanthemanr0x/Python
/Giraffe/Lists.py
561
4.25
4
# Working with lists # Lists can include integers and boolean # friends = ["Kevin", 2, False] friends = ["Kevin", "Karen", "Jim"] print(friends) # Using index friends = ["Kevin", "Karen", "Jim"] # 0 1/-2 2/-1 print(friends[0]) print(friends[2]) print(friends[-1]) print(friends[-2]) print(friends[1:]) friends1 = ["Kevin", "Karen", "Jim", "Oscar", "Toby"] # 0 1 2 3 4 # Will grab all the elements upto, but not including last element print(friends1[1:4]) friends[1] = "Mike" print(friends[1])
true
6b82f94e0a3149bcb55199f4d3d3d860732aa475
ryanthemanr0x/Python
/Giraffe/if_statements.py
631
4.40625
4
# If Statements is_male = False is_tall = False if is_male or is_tall: print("You are a male or tall or both") else: print("You are neither male nor tall") is_male1 = True is_tall1 = True if is_male1 and is_tall1: print("You are a tall male") else: print("You are either not male or tall or both") is_male2 = True is_tall2 = False if is_male2 and is_tall2: print("You are a tall male") elif is_male2 and not(is_tall2): print("You are a short male") elif not(is_male2) and is_tall2: print("You are not a male and are tall") else: print("You are either not male or tall or both")
true
9e0a944f2100cab01f4e4cad3921c8786998681b
ikramsalim/DataCamp
/02-intermediate-python/4-loops/loop-over-lists-of-lists.py
446
4.25
4
"""Write a for loop that goes through each sublist of house and prints out the x is y sqm, where x is the name of the room and y is the area of the room.""" # house list of lists house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0], ["bedroom", 10.75], ["bathroom", 9.50]] # Build a for loop from scratch for room, area in (house): print("the " + str(room) + " is " + str(area) + " sqm")
true
dcf1b439aa3db2947653f9197e961d4969f92095
ycayir/python-for-everybody
/course2/week5/ex_09_05.py
782
4.25
4
# Exercise 5: This program records the domain name (instead of the # address) where the message was sent from instead of who the mail came # from (i.e., the whole email address). At the end of the program, print # out the contents of your dictionary. # python schoolcount.py # # Enter a file name: mbox-short.txt # {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, # 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8} handle = open('../../files/mbox-short.txt') counts = dict() for line in handle: line = line.strip() if not line.startswith('From'): continue words = line.split() if len(words) < 2: continue email = words[1] emailParts = email.split('@') domain = emailParts[1] counts[domain] = counts.get(domain, 0) + 1 print(counts)
true
c3c1bf04376f728f6470a055e56c878ceec2d3b3
mjdall/leet
/spiral_matrix.py
2,106
4.1875
4
def spiral_order(self, matrix): """ Returns the spiral order of the input matrix. I.e. [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] becomes [1, 2, 3, 6, 9, 8, 7, 4, 5]. :type matrix: List[List[int]] :rtype: List[int] """ if not matrix or matrix is None: return [] output = [] # holds the limits for when we change axis direction curr_x_lim = len(matrix[0]) curr_y_lim = len(matrix) # holds the total number of entries in the array # as well as the number of total hops we need to do total_hops = curr_x_lim * curr_y_lim # the current directions we are travelling in the array # if x_direction is not 0 then y_direction will be 0, vice versa x_direction = 1 y_direction = 0 # the total number of steps we need to take in the current direction steps_in_direction = curr_x_lim # keep going until we've traversed each node x, y = 0, 0 while total_hops != 0: # append the current spot in the matrix output.append(matrix[y][x]) # increment variables keeping track of position steps_in_direction -= 1 total_hops -= 1 # we're done travelling in this direction if steps_in_direction == 0: # if we were travelling in x direction if x_direction: # y direction follows what x direction just was y_direction = x_direction # set x dir to zero x_direction = 0 # the next time we traverse in x direction, we dont go as far curr_x_lim -= 1 # set the number of steps we're expecting to take next steps_in_direction = curr_y_lim - 1 else: # x direction changes direction to y x_direction = -y_direction y_direction = 0 curr_y_lim -= 1 steps_in_direction = curr_x_lim # get the next spot in the array x += x_direction y += y_direction return output
true
3dd6609f9805f7c8bbf9949b56584a2c044475a3
mjdall/leet
/count_elements.py
668
4.28125
4
def count_elements(arr): """ Given an integer array arr, count element x such that x + 1 is also in arr. If there're duplicates in arr, count them seperately. :type arr: List[int] :rtype: int """ if arr is None or len(arr) == 0: return 0 found_numbers = {} for num in arr: found_numbers.setdefault(num, 0) found_numbers[num] += 1 nums_in_arr = found_numbers.keys() total_count = 0 for num in nums_in_arr: if num + 1 in found_numbers: total_count += found_numbers[num] return total_count
true
334da6ffae18a403cc33ae03c1600238a6a45ddd
denemorhun/Python-Problems
/Hackerrank/Strings/MatchParanthesis-easy.py
1,891
4.40625
4
# Python3 code to Check for balanced parentheses in an expression # EASY ''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true Solution: # position 0 -> [] # position 1 -> [] # position 2 -> () Use a stack to push all left paranthesis to open list. If the item equals the value in both open and closed lists, pop it. If we finish with an empty stack, paranthesis are balanced. ''' def isValid(input) -> bool: # convert string into a list input = list(input) # code: 0, 1, 2 open_list = ["[","{","("] close_list = ["]","}",")"] # No paranthesis means matching case if list is None: return True stack = [] # scroll through each char and add open paranthesis to the stack. for i in input: if i in open_list: stack.append(i) elif i in close_list: # get the paranthesis code: 0, 1, 2 code = close_list.index(i) if len(stack) > 0 and open_list[code] == stack[len(stack)-1]: stack.pop() # If all left paranthesis have been removed from stack we've found all the matches if len(stack) == 0: return True else: return False if __name__ == '__main__': input = ["khkjhkjhj", "#@#$@#$@", "()", "((([[[{}]]])))", ")(", "((]]", ""] for i in input: result = isValid(i) print("All paranthesis are matching.", i if result else "Mismatch", i)
true
bb708c316a2f7041f23c61036ff825153ad424a2
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Stacks and Queues/q_using_stack.py
1,149
4.21875
4
from typing import Deque from stack import MyStack # Push Function => stack.push(int) //Inserts the element at top # Pop Function => stack.pop() //Removes and returns the element at top # Top/Peek Function => stack.get_top() //Returns top element # Helper Functions => stack.is_empty() & stack.isFull() //returns boolean class NewQueue: def __init__(self): self.main_stack = MyStack() # Write your code here # Inserts Element in the Queue def enqueue(self, value): self.main_stack.push(value) return True # Removes Element From Queue def dequeue(self): # Write your code here temp_stack = MyStack() while not self.main_stack.size() == 1: temp_stack.push(self.main_stack.pop()) popped_item = self.main_stack.pop() while not temp_stack.is_empty(): self.main_stack.push(temp_stack.pop()) return popped_item def __str__(self): return str(self.main_stack) nq = NewQueue() nq.enqueue(1) nq.enqueue(2) nq.enqueue(3) nq.enqueue(4) nq.enqueue(5) val = nq.dequeue() print(nq) print(val)
true
a34383ee463d3c9749caf0e52c10e3e114fe02a7
denemorhun/Python-Problems
/AlgoExperts/LinkedList/remove_duplicates_from_linked_list.py
1,693
4.15625
4
''' A Node object has an integer data field, , and a Node instance pointer, , pointing to another node (i.e.: the next node in a list). A removeDuplicates function is declared in your editor, which takes a pointer to the node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list. Note: The pointer may be null, indicating that the list is empty. Be sure to reset your pointer when performing deletions to avoid breaking the list. Input Format Constraints The data elements of the linked list argument will always be in non-decreasing order. Your removeDuplicates function should return the head of the updated linked list. Sample Input 6 1 2 2 3 3 4 Sample Output 1 2 3 4 Explanation , and our non-decreasing list is . The values and both occur twice in the list , so we remove the two duplicate nodes. We then return our updated (ascending) list ''' # This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None # Even though this class says linkedlist, it's actually Node def removeDuplicatesFromLinkedList(linkedList): # actually this is the head node currentNode = linkedList print("Starting with head node") while currentNode is not None: nextNode = currentNode.next print(currentNode.value) # if next node is equal to current node's value repeat loop while nextNode is not None and nextNode.value == currentNode.value: print('duplicate') nextNode = nextNode.next currentNode.next = nextNode currentNode = currentNode.next return linkedList
true
07bab891b92ca248e39056da104d2a9afdff953c
denemorhun/Python-Problems
/Hackerrank/Arrays/validate_pattern.py
1,708
4.34375
4
'''Validate Pattern from array 1 to array b Given a string sequence of words and a string sequence pattern, return true if the sequence of words matches the pattern otherwise false. Definition of match: A word that is substituted for a variable must always follow that substitution. For example, if "f" is substituted as "monkey" then any time we see another "f" then it must match "monkey" and any time we see "monkey" again it must match "f". Examples input: "ant dog cat dog", "a d c d" output: true This is true because every variable maps to exactly one word and vice verse. a -> ant d -> dog c -> cat d -> dog input: "ant dog cat dog", "a d c e" output: false This is false because if we substitute "d" as "dog" then you can not also have "e" be substituted as "dog". a -> ant d, e -> dog (Both d and e can't both map to dog so false) c -> cat input: "monkey dog eel eel", "e f c c" output: true This is true because every variable maps to exactly one word and vice verse. e -> monkey f -> dog c -> eel ''' def is_it_a_pattern(arr, patt): # matching_values dictionary mv = {} #isPattern = True if len(arr) != len(patt): return False for i in range(len(arr)): if arr[i] not in mv.keys(): mv[arr[i]] = patt[i] else: if mv[arr[i]] != patt[i]: return False return True if __name__ == '__main__': color1 = ["red", "green", "green"] patterns1 = ["a", "b", "b", "d"] print( "True" if is_it_a_pattern(color1, patterns1) else "False") color2 = ["blue", "green", "blue", "blue"] patterns2 = ["blue", "b", "c", "c"] print( "True" if is_it_a_pattern(color2, patterns2) else "False")
true
7ff5903c490ef8c34099db9252ec42918f2e850b
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_5(3)_TC.py
1,028
4.46875
4
#!/usr/bin/env python3 """This is a function that returns heads or tails like the flip of a coin""" import random def FlipCoin(): if random.randrange(0, 2) == 0: return ("tails") return ("heads") def GetHeads(target): """Flips coins until it gets target heads in a row.""" heads = count = 0 while heads < target: count += 1 if FlipCoin() == 'heads': heads += 1 # print("heads") test code to show when heads occurs else: # 'tails' heads = 0 # print("tails") test code to show when tails occurs return count def GetAverage(number_of_experiments, target): """Calls GetHeads(target) that number_of_experiments times and reports the average.""" total = 0 for n in range(number_of_experiments): total += GetHeads(target) print ("Averaging %d experiments, it took %.1f coin flips to get %d in a row." % (number_of_experiments, total/number_of_experiments, target)) GetAverage(100, 3)
true
3b1315a4ffacc91f29a75daa3993a1cb2aab4133
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_6(3).py
2,442
4.46875
4
#!/usr/bin/env python3 """Introspect the random module, and particularly the randrange() function it provides. Use this module to write a "Flashcard" function. Your function should ask the user: What is 9 times 3 where 9 and 3 are any numbers from 0 to 12, randomly chosen. If the user gets the answer right, your function should print "Right!" and then return a 1. If the answer is wrong, print "Almost, the right answer is 27" and return a 0. Write a function called TestAndScore(n) that calls your Flashcard function n times and prints the percentage of right answers like this, "Score is 90". It also returns this percentage. Make another function called GiveFeedback(p) that receives a percentage, 0 - 100. If p is 100 it prints "Perfect!", if it's 90-99 it prints "Excellent", 80-89 prints "Very good", 70-79 prints "Good enough", and <= 69, "You need more practice". Test all that in your program, calling TestAndScore(10) and then pass the returned value into GiveFeedback(). Make a new function called "Praise" that takes no arguments. It prints one of (at least) 5 phrases of Praise, chosen randomly. It might print, "Right On!", or "Good work!", for example. Call this Praise() function from your Flashcard() function whenever your user gets the answer right. """ import random def FlashCard(): n1 = random.randrange(13) n2 = random.randrange(13) answer = n1 * n2 print ("What is %d times %d? " % (n1, n2)) while True: try: response = int(input()) except ValueError: print ("%d times %d is a number. What number? " % ( n1, n2)) continue if response == answer: print ("Right!", Praise()) return 1 print ("Almost, the right answer is %d." % answer) return 0 def GiveFeedback(p): if p == 100: print ('Perfect!') elif p >= 90: print ('Excellent') elif p >= 80: print ('Very good') elif p >= 70: print ('Good enough') else: print ('You need more practice') def Praise(): pats = ("That's great!", "You're right!", "Good work!", "Right On!", "Superb!") print (random.choice(pats)) def TestAndScore(n): score = 0 for time in range(n): score += FlashCard() score = int(100.0 * score/n) print ("Score is %d." % score) return score GiveFeedback(TestAndScore(10))
true
008fa26d54dc77f783b3b60f5e2f85c83535a3fd
tcano2003/ucsc-python-for-programmers
/code/lab_14_Magic/circle_defpy3.py
1,823
4.1875
4
#!/usr/bin/env python3 """A Circle class, acheived by overriding __getitem__ which provides the behavior for indexing, i.e., []. This also provides the correct cyclical behavior whenever an iterator is used, i.e., for, enumerate() and sorted(). reversed() needs __reversed__ defined. """ #need to have def __getitem__(<<obj>> , <<3>>): in order to call obj[3], otherwise will fail class Circle: def __init__(self, data, times): #want to prevent infinite results with a circle class """Put the 'data' in a circle that goes around 'times' times.""" self.data = data self.times = times def __getitem__(self, i): #i is index given by the caller """circle[i] --> Circle.__getitem__(circle, i).""" l_self = len(self) if i >= self.times * l_self: raise IndexError ("Circle object goes around %d times" % (self.times)) #raise IndexError return self.data[i % l_self] # return answer def __len__(self): return len(self.data) #given the len() of the data def main(): circle = Circle("around", 3) print ("Works with circle[i], for i > len(circle) too:") for i in range(3 * len(circle) + 1): try: print ("circle[%2d] = %s" % (i, circle[i])) except IndexError as e: print(e) break print ("Works with sorted:") print (sorted(circle)) print ("Works for loops:") small_circle = Circle("XO", 2) for i, elementi in enumerate(small_circle): print ("small_circle[%d] = %s" % (i, elementi)) print ("Works for nested loops:") for i, elementi in enumerate(small_circle): for j, elementj in enumerate(small_circle): print ("%3d:%3d -> %s%s" % (i, j, elementi, elementj)) if __name__ == '__main__': main()
true