blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ac565e0d4d3b948dcf0d8767039d6ccb2d9f71d
Tabsdrisbidmamul/PythonBasic
/Chapter_10_files_and_exceptions/04 guest_book.py
448
4.1875
4
# program that asks the user name, once entered print a prompt to say it was # accepted and append the string onto the file filename = 'programming.txt' while True: userName = str(input('What is your name? ')) print('Welcome ', userName) with open(filename, 'a') as file_object: # the \n is required, as the write method doesn't put newlines, # so it has to be put in manually file_object.write('\n' + userName + ' has been recorded\n')
true
3c5b8e6838f2ebead83149f9e35c12f3c7a9b96c
Tabsdrisbidmamul/PythonBasic
/Chapter_7_user_inputs_and_while_loops/08 dream_vacation.py
819
4.28125
4
# set an empty dictionary to be filled up with polling later responses = {} # make a flag set to true polling_active = True while polling_active: # prompt for user's name and their destination name = input('\nWhat is your name: ') dream_vacation = input('What place is your dream vacation? ') # store the user input as key-value pair in the empty dictionary responses[name] = dream_vacation # To see if anyone wants to take the poll loop = input('\nWould you like another person to take this poll? (' 'yes/no) ') if loop.lower() in ['no', 'n']: polling_active = False # print the results from your poll print('\n\t---Poll Results---') for name, dream_vacation in responses.items(): print(name.title() + ' would like to go to ' + dream_vacation.title())
true
24c95a3ab3e6b6e6a6cfa4ab1fbfc0f43dbf9409
GudjonGunnarsson/python-challenges
/codingbat/warmup1/9_not_string.py
884
4.40625
4
#!/usr/bin/python3 """ This challenge is as follows: Given a string, return a new string where "not" has been added to the front. However, if the string already begins with "not", return the string unchanged. Expected Results: 'candy' -> 'not candy' 'x' -> 'not x' 'not bad' -> 'not bad' """ def not_string(str): # This part is where the challenge is supposed to be solved return str if str.split()[0] == "not" else "not " + str if __name__ == '__main__': # This part is only to test if challenge is a success print("Scenario 1: candy : {}".format("success" if not_string('candy') == 'not candy' else "fail")) print("Scenario 2: x : {}".format("success" if not_string('x') == 'not x' else "fail")) print("Scenario 3: not bad: {}".format("success" if not_string('not bad') == 'not bad' else "fail"))
true
915deca3aed8bb835c8d915589a91e5f02cf3f49
DocAce/Euphemia
/dicey.py
2,108
4.1875
4
from random import randint def roll_die(sides): return randint(1, sides) def flip_coin(): if randint(0, 1) == 0: return 'Heads' else: return 'Tails' def generate_coin_flip_output(args): numflips = 1 # just use the first number we find as the number of coins to flip for arg in args: if arg.isdigit(): numflips = int(arg) break result = '' for i in range(numflips): if i > 0: result += ', ' result += flip_coin() return result def generate_dice_roll_output(args): numdice = 1 addsgn = 1 add = 0 sides = 6 # evaluate the first argument that contains the letter d # neither the @ nor the command contain that letter, so this should always work for arg in args: index_d = arg.find('d') if index_d > 0: rollstring = arg # the number in front of the d is how many dice to roll (1 by default) numdice = int(rollstring[:index_d]) rollstring = rollstring[index_d + 1:] # either + or -, followed by a number, can be at the end index_operator = rollstring.find('+') if index_operator == -1: index_operator = rollstring.find('-') addsgn = -1 if index_operator != -1: add = int(rollstring[index_operator + 1:]) * addsgn rollstring = rollstring[:index_operator] # if there is a number between the d and the + or - it's the number of sides on the dice (6 by default) if rollstring != '': sides = int(rollstring) break total = add result = 'Rolling ' + str(numdice) + 'd' + str(sides) if add < 0: result += '-' else: result += '+' result += str(abs(add)) + '\n' result += 'Rolls: ' for i in range(numdice): rollresult = roll_die(sides) total += rollresult if i > 0: result += ', ' result += str(rollresult) result += '\nTotal: ' + str(total) return result
true
71adcc544a902e71d283a4ffefb069622b2a03c6
vesteinnbjarna/Forritun_Vesteinn
/Lestrarverkefni/Kafli 2/simple_while.py
251
4.15625
4
#simple while x_int = 0 #test loop-controled variable at the start while x_int < 10: print(x_int, end =' ') # print x_each time it loops x_int = x_int + 1 # changing x_int while in loop print () print ('Final value of x_int: ', x_int)
true
e5dbd401cbb63acdd259b185a02eeee98498734e
vesteinnbjarna/Forritun_Vesteinn
/Hlutapróf 2 undirbúningur/longest_word.py
682
4.40625
4
def open_file(filename): file_obj = open(filename, 'r') return file_obj def find_longest(file_object): '''Return the longest word and its length found in the given file''' max_length = 0 longest_word = "" for word in file_object: word = word.strip() length = len(word) if length > max_length: longest_word = word max_length = length return longest_word, max_length def main(): filename = input('Enter filename: ') file_object = open_file(filename) longest, length = find_longest(file_object) print("Longest word is '{:s} of length {:d}".format(longest, length)) file_object.close()
true
e9b16fba6e3a93f03f9e0b4950b9f3692f2a8cc8
vesteinnbjarna/Forritun_Vesteinn
/Tímaverkefni/Assignment 12/Q4.py
606
4.5
4
def merge_lists(first_list, second_list): a_new_list = [] for element in first_list: if element not in a_new_list: a_new_list.append(element) for element in second_list: if element not in a_new_list: a_new_list.append(element) a_new_list = sorted(a_new_list) return a_new_list # Main program starts here - DO NOT change it def main(): list1 = input("Enter elements of list separated by commas: ").split(',') list2 = input("Enter elements of list separated by commas: ").split(',') print(merge_lists(list1, list2)) main()
true
e0b0f0b3ec6cfe4adb826d78aadaf9496db112ad
vesteinnbjarna/Forritun_Vesteinn
/Tímaverkefni/Assignment 7/A7.5.py
699
4.1875
4
import string # palindrome function definition goes here def is_palindrom (imported_string): original_str = imported_string modified_str = original_str.lower() bad_chars = string.whitespace + string.punctuation for char in modified_str: if char in bad_chars: modified_str = modified_str.replace(char,'') if modified_str == modified_str [::-1]: answer = '"' + original_str + '"'+ " is a palindrome." else: answer = '"' + original_str + '"' " is not a palindrome." return answer in_str = input("Enter a string: ") result = is_palindrom(in_str) print(result) # call the function and print out the appropriate message
true
17f31ab18c5d3f2d100c967bb88ca7b399d28278
vesteinnbjarna/Forritun_Vesteinn
/Tímaverkefni/Assignment 7/A7.3.py
353
4.15625
4
# The function definition goes here def is_num_in_range(number): if number > 1 and number < 555: answer = str(number) + " is in range." else: answer = str(number) + " is outside the range!" return answer num = int(input("Enter a number: ")) result = is_num_in_range(num) print (result) # You call the function here
true
d4321a075f9540f36673bc598bfc9f1990598094
vesteinnbjarna/Forritun_Vesteinn
/Skilaverkefni/Skilaverkefni 5/project.py
1,683
4.5625
5
# The program should scramble each word in the text.txt # with the following instructions: # 1.The first and last letter of each word are left unscrambled # 2. If there is punctuation attached to a word it should be left unscrambled # 3. The letter m should not be scrambled # 4. The letters between the first and the last letter should swap adjacent # letter. # Lastly the user should be able to input the name of the file he wishes to scramble # If no file contains that name he should get a error message: # File xxx.txt not found! # # Steps to do this: # 1. Create a function that opens the tries to open the file. # If it cannot open it it should print a out the error message: # file not found. # # # def open_file(file_object): '''A function that tries to open a file if the filename is not found it prints a errorr message''' file_object = open(file_object, "r") except FileNotFoundError: print('File', file_object, 'not found!') return file_object #def write_file(file_object): # out_file = open(file_object,'w') # sentence = '' # for line in file_object: # line = line.strip() # sentence = sentence + line # print (sentence) # return out_file def read_file(file_object): new_line ='' for line in file_object: line = line.strip() line = line.replace("\n",' ') new_line = line + new_line print(new_line) def main(): valid_input_bool = False while not valid_input_bool: file_name =input('Enter name of file: ') try: file_object = open_file(file_name) main ()
true
c55af45dee5dd8861b67840741f798d791302b35
AHoffm24/python
/Chapter2/classes.py
999
4.40625
4
# # Example file for working with classes # #methods are functions in python #self argument refers to the object itself. Self refers to the particular instance of the object being operated on # class Person: #example of how to initalize a class with variables # def __initialize__(self, name, age, sex): # self.name = name # self.age = age # self.sex = sex class myClass(): #super class def method1(self): print("myClass Method1") def method2(self, someString): print(someString + " myClass Method2 ") class anotherClass(myClass): #inherited class allows you to call methods from myClass inside of anotherClass def method1(self): myClass.method1(self) print("another class method1") def method2(self, someString): print("another calss method2") def main(): c = myClass() c.method1() c.method2("this is my string for") c2 = anotherClass() c2.method1() c2.method2("This is a string") if __name__ == "__main__": main()
true
e22f5ff5265d5073eeac203c5a6c8e017babdf23
rodrigo9000/PycharmProjects
/PlayingWithSeries/Mission3_RollTheDice.py
513
4.34375
4
# User should be able to enter how many dices he wants to roll: 1 ,2 or 3. He should pass this value as a parameter in the # function RollTheDice(num). Dices should show random numbers from 1 to 6. import random def main(): def RollTheDice(num): if num in [1, 2, 3]: for turns in range(1, (num + 1)): print "Dice {} is number: ".format(turns), random.randint(1, 6) else: print "Number out of range" RollTheDice(1) if __name__== "__main__": main()
true
b410db6a9ea07a05b7e80afad10bfed4a7d643b6
95subodh/Leetcode
/116. Populating Next Right Pointers in Each Node.py
1,266
4.28125
4
#Given a binary tree # #struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; #} #pulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # #itially, all next pointers are set to NULL. # #te: # #u may only use constant extra space. #u may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). #r example, #ven the following perfect binary tree, # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 #ter calling your function, the tree should look like: # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ / \ # 4->5->6->7 -> NULL # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): stk=[] if root: stk=[root] root=next = None while stk: z=stk.pop() if z.left: z.left.next=z.right stk.append(z.left) if z.right: if z.next: z.right.next=z.next.left else: z.right.next=None stk.append(z.right)
true
93149f960c8b7d342dde0ea643b3977b3ae35bd3
95subodh/Leetcode
/326. Power of Three.py
240
4.34375
4
#Given an integer, write a function to determine if it is a power of three. from math import * class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ return True if n>0 and 3**20%n==0 else False
true
33fa289bf90d66af8fb90cedcf7d52a4a3613baf
kphillips001/Edabit-Python-Code-Challenges
/usingternaryoperators.py
380
4.34375
4
# The ternary operator (sometimes called Conditional Expressions) in python is an alternative to the if... else... statement. # It is written in the format: # result_if_true if condition else result_if_false # Ternary operators are often more compact than multi-line if statements, and are useful for simple conditional tests. def yeah_nope(b): return "yeah" if b else "nope"
true
36a0f49179f1135a619d1d694fa71974e0ffb71b
jbulka/CS61A
/hw2_solns.py
2,545
4.15625
4
"""Submission for 61A Homework 2. Name: Login: Collaborators: """ # Q1: Done def product(n, term): """Return the product of the first n terms in a sequence. We will assume that the sequence's first term is 1. term -- a function that takes one argument """ prod, k = 1, 1 while k <= n: prod, k = prod * term(k), k + 1 return prod def factorial(n): """Return n factorial by calling product. >>> factorial(4) 24 """ return product(n, identity) def identity(k): ''' returns the value k''' return k # Q2: Done from operator import add, mul def accumulate(combiner, start, n, term): """Return the result of combining the first n terms in a sequence. """ total, k = start, 1 while k <= n: total, k = combiner(total, term(k)), k + 1 return total def summation_using_accumulate(n, term): """An implementation of summation using accumulate.""" return accumulate(add, 0, n, term) def product_using_accumulate(n, term): """An implementation of product using accumulate.""" return accumulate(mul, 1, n, term) # Q3: Done def double(f): """Return a function that applies f twice. f -- a function that takes one argument """ return lambda x: f(f(x)) # Q4: Done def repeated(f, n): """Return the function that computes the nth application of f. f -- a function that takes one argument n -- a positive integer >>> repeated(square, 2)(5) 625 """ func = f k = 1 while k < n : func = compose1(f,func) k = k + 1 return func def square(x): """Return x squared.""" return x * x def compose1(f, g): """Return a function h, such that h(x) = f(g(x)).""" def h(x): return f(g(x)) return h # Q5 (Extra) def zero(f): """Church numeral 0.""" return lambda x: x def successor(n): return lambda f: lambda x: f(n(f)(x)) def one(f): """Church numeral 1.""" "*** YOUR CODE HERE ***" def two(f): """Church numeral 2.""" "*** YOUR CODE HERE ***" def add_church(m, n): """Return the Church numeral for m + n, for Church numerals m and n.""" "*** YOUR CODE HERE ***" def church_to_int(n): """Convert the Church numeral n to a Python integer. >>> church_to_int(zero) 0 >>> church_to_int(one) 1 >>> church_to_int(two) 2 >>> church_to_int(add_church(two, two)) 4 """ "*** YOUR CODE HERE ***"
true
215aed3bd3d66a69c49bc841e6dc9011cc8bf156
QinmengLUAN/Daily_Python_Coding
/wk4_findNumbers.py
860
4.28125
4
""" 1295. Find Numbers with Even Number of Digits Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. Example 2: Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits. """ def findNumbers(nums): oup = 0 k = 0 for i in range(len(nums)): nu = nums[i] while nu > 0: nu = nu // 10 k += 1 if (k % 2) == 0: oup += 1 k = 0 return oup nums = [437,315,322,431,686,264,442] print(findNumbers(nums))
true
9261b5b8c174058a10632b6cbe2a580c0a5e9cba
QinmengLUAN/Daily_Python_Coding
/DailyProblem20_maximum_product_of_three.py
651
4.375
4
""" Hi, here's your problem today. This problem was recently asked by Microsoft: You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array. Example: [-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128. Here's a starting point: def maximum_product_of_three(lst): # Fill this in. print maximum_product_of_three([-4, -4, 2, 8]) # 128 """ def maximum_product_of_three(nums): # Fill this in. nums.sort() return max(nums[-1]*nums[-2]*nums[-3], nums[0]*nums[1]*nums[-1]) print(maximum_product_of_three([-4, -4, 2, 8])) # 128
true
99845dad934230a83a99d4e8ac1ab96b24cd0c3f
QinmengLUAN/Daily_Python_Coding
/DailyProblem19_findKthLargest.py
653
4.125
4
""" Hi, here's your problem today. This problem was recently asked by Facebook: Given a list, find the k-th largest element in the list. Input: list = [3, 5, 2, 4, 6, 8], k = 3 Output: 5 Here is a starting point: def findKthLargest(nums, k): # Fill this in. print findKthLargest([3, 5, 2, 4, 6, 8], 3) """ import heapq def findKthLargest(nums, k): # Fill this in. if len(nums) < 3: return None h = [] for i in range(3): heapq.heappush(h, nums[i]) for j in range(3, len(nums)): heapq.heappush(h, nums[j]) heapq.heappop(h) return heapq.heappop(h) print(findKthLargest([3, 5, 2, 4, 6, 8], 3))
true
5ff35f6f7a920113cec07c88e253ad06a9bdcfec
QinmengLUAN/Daily_Python_Coding
/LC354_maxEnvelopes_DP.py
2,042
4.40625
4
""" 354. Russian Doll Envelopes Hard You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? (put one inside other) Note: Rotation is not allowed. Example: Input: [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). """ class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if len(envelopes) == 0: return 0 envelopes.sort(key = lambda x: (x[0], -x[1])) f = [0] * len(envelopes) size = 0 for w,h in envelopes: i, j = 0, size while i != j: m = i + (j - i)//2 if f[m] < h: i = m + 1 else: j = m f[i] = h size = max(size, i + 1) # print(f) return size """ Trick: let's suppose the values are given as... [2,3] [4,6] [3,7] [4,8] If we Sort this envelopes in a tricky way that Sort the envelopes according to width BUT when the values of height are same, we can sort it in reverse way like this : [2,3] [3,7] [4,8] [4,6] Now just Do LIS on the all height values, you will get the answer Solution: # only seek height's LIS (longest increasing subsequence), alike Leetcode Question 300. # https://leetcode.com/problems/longest-increasing-subsequence/ # follow up question, how about 3D cases? since Russian Doll are actually with x,y,z dimensions! # [2,3], [5,4], [6,4], [6,7], [1,2] # will be sorted to be: [1,2], [2,3], [5,4], [6,7], [6,4] # where the answer is: 4 for [1,2], [2,3], [5,4], [6,7] # [2,3], [5,4], [6,4], [7,1], [8,2], [9,3] # will be sorted to be: [2,3], [5,4], [6,4], [7,1], [8,2], [9,3] # where the answer is: 3 for [7,1], [8,2], [9,3] """
true
dc33830a1d3708345a5d77f6f9dfd86017137e31
QinmengLUAN/Daily_Python_Coding
/wk2_sqrt.py
609
4.125
4
# Write a function to calculate the result (integer) of sqrt(num) # Cannot use the build-in function # Method: binary search def my_sqrt(num): left_boundary = 0 right_boundary = num if num <= 0: return False elif num < 1: return 0 elif num == 1: return num while (right_boundary - left_boundary) > 1: mid_num = (right_boundary + left_boundary) // 2 #Update mid_num new_num = mid_num * mid_num if new_num < num: left_boundary = mid_num elif new_num > num: right_boundary = mid_num elif new_num == num: return mid_num return left_boundary #Input: a = 15 print(my_sqrt(a))
true
7dab89ca1ef40d80b0ea0728cca5126bd021f291
QinmengLUAN/Daily_Python_Coding
/wk2_MoeList.py
1,106
4.28125
4
# To understand object and data structure # Example 1: https://www.w3schools.com/python/python_classes.asp # Example 2: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm # write an object MyList with many methods: MyList, append, pop, print, node class MyNode: def __init__(self, value): self.value = value self.before = None self.next = None class MyList: def __init__(self): self.head = None self.tail = None def append(self, value): appended = MyNode(value) if self.head == None: self.head = appended self.tail = appended else: curr_tail = self.tail appended.before = curr_tail curr_tail.next = appended self.tail = appended def print(self): curr_node = self.head while curr_node != None: print(curr_node.value) curr_node = curr_node.next def get(self, n): curr_node = self.head i = 0 while i < n and curr_node != None: curr_node = curr_node.next i = i + 1 if curr_node == None: return None else: return curr_node.value lis = MyList() lis.append(1) lis.append(2) lis.print() print(lis.get(1))
true
c48afae5e64ef91588c53ce962ea8c326a529d1b
QinmengLUAN/Daily_Python_Coding
/LC1189_maxNumberOfBalloons_String.py
858
4.125
4
""" 1189. Maximum Number of Balloons Easy: String, Counter, dictionary Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example 1: Input: text = "nlaebolko" Output: 1 Example 2: Input: text = "loonbalxballpoon" Output: 2 Example 3: Input: text = "leetcode" Output: 0 """ class Solution: def maxNumberOfBalloons(self, text: str) -> int: cnt = Counter(text) return min(cnt[ch]//n for ch, n in Counter('balloon').items()) def maxNumberOfBalloons(self, text: str) -> int: c = Counter("balloon") c_text = Counter(text) res = len(text) for i in c: res = min(res, c_text[i]//c[i]) return res
true
24b60cb185dcf1770906a0b042b297aa7ea0784b
QinmengLUAN/Daily_Python_Coding
/LC326_isPowerOfThree_Math.py
420
4.25
4
""" 326. Power of Three Easy: Math Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Follow up: Could you do it without using any loop / recursion? """ class Solution: def isPowerOfThree(self, n: int) -> bool: return n > 0 and 3**19 % n == 0
true
ea27a81da0146733e81e51b59fcb87622e5f8cea
QinmengLUAN/Daily_Python_Coding
/DailyProblem04_isValid_String.py
1,649
4.21875
4
""" Hi, here's your problem today. This problem was recently asked by Uber: Leetcode 20 Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings. Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: - Open brackets are closed by the same type of brackets. - Open brackets are closed in the correct order. - Note that an empty string is also considered valid. Example: Input: "((()))" Output: True Input: "[()]{}" Output: True Input: "({[)]" Output: False class Solution: def isValid(self, s): # Fill this in. # Test Program s = "()(){(())" # should return False print(Solution().isValid(s)) s = "" # should return True print(Solution().isValid(s)) s = "([{}])()" # should return True print(Solution().isValid(s)) """ class Solution: def isValid(self, s): # Fill this in. bra_dic = {")":"(", "}": "{", "]":"["} stack = [] for i in range(len(s)): if s[i] not in bra_dic: stack.append(s[i]) else: if len(stack) == 0 or stack[-1] != bra_dic[s[i]]: return False else: stack.pop() if len(stack) > 0: return False else: return True # Test Program s = "()(){(())" # should return False print(Solution().isValid(s)) s = "" # should return True print(Solution().isValid(s)) s = "([{}])()" # should return True print(Solution().isValid(s))
true
7e4c89bc3812a0bf3707b3de2183ca661b693f3d
QinmengLUAN/Daily_Python_Coding
/LC207_canFinish_Graph.py
2,214
4.1875
4
""" 207. Course Schedule Medium: Graph There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2: Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. """ from collections import deque class Solution: def canFinish(self, numCourses, prerequisites): cnext = {} npre = {} for i in range(len(prerequisites)): if prerequisites[i][1] in cnext: cnext[prerequisites[i][1]].append(prerequisites[i][0]) else: cnext[prerequisites[i][1]] = [prerequisites[i][0]] if prerequisites[i][0] not in npre: npre[prerequisites[i][0]] = 1 else: npre[prerequisites[i][0]] += 1 if prerequisites[i][1] not in npre: npre[prerequisites[i][1]] = 0 print(cnext) print(npre) if len(npre) == 0 and numCourses == 1: return True dq = deque([i for i in npre if npre[i] == 0]) print(dq) finished = 0 while len(dq) > 0: c = dq.popleft() finished += 1 # print(finished) print(cnext, npre) if c not in cnext: continue for cn in cnext[c]: npre[cn] -= 1 if npre[cn] == 0: dq.append(cn) return finished == len(npre) numCourses = 4 prerequisites = [[3,0],[0,1]] s = Solution() print(s.canFinish(numCourses, prerequisites))
true
f27497e9a8acc603807d738e36b3937ad47f1b77
NkStevo/daily-programmer
/challenge-003/intermediate/substitution_cipher.py
1,260
4.125
4
import json def main(): with open('ciphertext.json') as json_file: ciphertext = json.load(json_file) print("----Substitution Cipher Program----") choice = input("Input 1 to encode text and 2 to decode text:\n") if choice == '1': text = input("Input the text you would like to be encoded:\n") print(encode(text, ciphertext)) elif choice == '2': text = input("Input the text you would like to be decoded:\n") print(decode(text, ciphertext)) else: print("Invalid input") def encode(text, ciphertext): coded_text = "" for char in text: char_code = ord(char) if (char_code >= ord('a') and char_code <= ord('z')) or (char_code >= ord('A') and char_code <= ord('Z')): coded_text += ciphertext[char] else: coded_text += char return coded_text def decode(text, ciphertext): coded_text = "" inverse_ciphertext = {value: key for key, value in ciphertext.items()} for char in text: if char in inverse_ciphertext: coded_text += inverse_ciphertext[char] else: coded_text += char return coded_text if __name__ == '__main__': main()
true
505816e71a2df217a36b6dc74ae814e40208b26d
zszinegh/PyConvert
/pyconvert/conversions.py
1,068
4.375
4
"""A module to do various unit conversions. This module's functions convert various units of measurement. All functions expect a 'float' as an argument and return a 'float'. 'validate_input()' can be used before running any function to convert the input to a 'float'. """ def validate_input(incoming): """Convert input to float. Args: incoming (str): String probably coming from a 'raw_input()'. Returns: result (str or float): Depends on try statement. """ try: result = float(incoming) except ValueError: result = incoming return result # Conversion functions. def celsius_fahrenheit(number): """Convert celsius to fahrenheit.""" return (number * 9.0 / 5.0) + 32.0 def fahrenheit_celsius(number): """Convert fahrenheit to celsius.""" return (number - 32.0) * 5.0 / 9.0 def kms_miles(number): """Convert kms to miles.""" return number * 0.62137 def miles_kms(number): """Convert miles to kms.""" return number / 0.62137 if __name__ == '__main__': pass
true
82be926a6549078edf9b27ea2e56c0993d5e6b3a
isaiah1782-cmis/isaiah1782-cmis-cs2
/Assignment_Guessing_Game.py
950
4.25
4
import math import random Minimum_Number = int(raw_input("What is the minimum number? ")) Maximum_Number = int(raw_input("What is the maximum number? ")) print "I'm thinking of a number from " + str(Minimum_Number) + " to " + str(Maximum_Number) + "." Guess = str(raw_input("What do you think it is?: ")) def Correct_or_Over_or_under(): x = number = random.randint(Minimum_Number, Maximum_Number) if int(x) == int(Guess): print """ The target was {}. Your guess was {}. That's correct! You must be psychic! """.format(str(x), str(Guess)) elif str(x) > str(Guess): Under = int(x) - int(Guess) print """ The target was {}. Your guess was {}. That's under by {}. """.format(str(x), str(Guess), Under) elif str(x) < str(Guess): Over = int(Guess) - int(x) print """ The target was {}. Your guess was {}. That's over by {}. """.format(str(x), str(Guess), Over) Correct_or_Over_or_under()
true
77069ee92fcb26ff76619058b379d05e8c177153
kammariprasannalaxmi02/sdet
/python/Activity12.py
264
4.21875
4
#Write a recursive function to calculate the sum of numbers from 0 to 10 def calculate(i): if i <= 1: return i else: return i + calculate(i-1) num = int(input("Enter a number: ")) print("The sum of numbers: ", calculate(num))
true
26343c2e7d1a57463b71faee58c204afd426b5b8
noemiko/design_patterns
/factory/game_factory.py
2,774
4.75
5
# Abstract Factory # The Abstract Factory design pattern is a generalization of Factory Method. Basically, # an Abstract Factory is a (logical) group of Factory Methods, where each Factory # Method is responsible for generating a different kind of object # Frog game class Frog: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): act = obstacle.action() msg = f"{self} the Frog encounters {obstacle} and {act}!" print(msg) class Bug: def __str__(self): return "a bug" def action(self): return "eats it" class FrogGame: def __init__(self, name): print(self) self.player_name = name def __str__(self): return "\n\n\t------ Frog World -------" def make_character(self): return Frog(self.player_name) def make_obstacle(self): return Bug() # Wizard game class Wizard: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): act = obstacle.action() msg = f"{self} the Wizard battles against {obstacle} and {act}!" print(msg) class Ork: def __str__(self): return "an evil ork" def action(self): return "kills it" class WizardGame: def __init__(self, name): print(self) self.player_name = name def __str__(self): return "\n\n\t------ Wizard World -------" def make_character(self): return Wizard(self.player_name) def make_obstacle(self): return Ork() # Game environment class GameEnvironment: def __init__(self, factory): self.hero = factory.make_character() self.obstacle = factory.make_obstacle() def play(self): self.hero.interact_with(self.obstacle) def validate_chosen_game(user_name): print(f"Would you like to play {user_name} in Wizard game?") print(f"Would you like to play {user_name} in Frog game?") game_number = input("Wizard game press: 1, From game press: 2 ") try: game_number = int(game_number) if game_number not in (1, 2): raise ValueError except ValueError as err: print("You have chosen the wrong game number") return False, game_number return True, game_number def main(): user_name = input("Hello. What's your name? ") is_valid_input = False while not is_valid_input: is_valid_input, game_number = validate_chosen_game(user_name) games = { 1: FrogGame, 2: WizardGame } chosen_game = games[game_number] environment = GameEnvironment(chosen_game(user_name)) environment.play() main()
true
95a9f4e25127241ba07696dacca17dfe3740c930
vladflore/py4e
/course3/week6/extract-data-json.py
1,396
4.40625
4
# In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The # program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment # counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: We provide two files # for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual # data you need to process for the assignment. # # Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data: # http://py4e-data.dr-chuck.net/comments_330796.json (Sum ends with 66) The closest sample code that shows how to # parse JSON and extract a list is json2.py. You might also want to look at geoxml.py to see how to prompt for a URL # and retrieve data from a URL. import json import ssl import urllib.request # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter URL: ') if len(url) < 1: url = "http://py4e-data.dr-chuck.net/comments_330796.json" # context is not needed because the data source link is NOT https data = urllib.request.urlopen(url, context=ctx).read() json_data = json.loads(data) comments = json_data['comments'] s = 0 for comment in comments: s = s + int(comment['count']) print(s)
true
f7f87810b50c50b2828e2c404763cdb3f44b08a0
alindsharmasimply/Python_Practice
/seventySecond.py
307
4.21875
4
def sumsum(): sum1 = 0 while True: try: a = input("Enter a valid number to get the sum ") if a == ' ': break sum1 = sum1 + a print sum1, "\n" except Exception: print "Enter a valid number only " sumsum()
true
3a50f698d6a65fafa0c72bfc75b8ec175896b9d8
SimonFromNeedham/Project_Euler_Problems
/euler16.py
1,072
4.125
4
# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # What is the sum of the digits of the number 2^1000? # I'm aware that this approach is more complex than necessary and that I could just use a long to store the number, # But I honestly find it a lot more interesting to work through the problem trying to save memory by using an array if __name__ == '__main__': # Use an array instead of an int/long to store the number because # with hundreds of digits, the latter would take up a ton of memory digits = [1] for i in range(1000): digits[0] *= 2 if digits[0] > 9: digits[0] %= 10 digits.insert(0, 1) # If the first digit == 1, then the second digit was already doubled because # the higher digit (> 10) was "carried" over to the next digit --> inserted at index 0 for j in range(1 if digits[0] != 1 else 2, len(digits)): digits[j] *= 2 if digits[j] > 9: digits[j] %= 10 digits[j-1] += 1 print(sum(digits))
true
c0bdf60e9dd878b032e2372faf6babe022ee1201
littlejoe1216/Daily-Python-Exercise-01
/#1-Python-Daily-Exercise/Daily Exercise-1-02082018.py
290
4.1875
4
#Joe Gutierrez - Python Daily Exercise - 2/16/18 # 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice). name = input('Enter First name:') sna = input('Enter Last name:') joe = name + sna print ('Is your name ' + str(joe))
true
518087b3406afc65b712cee808f5849e98d40197
palepriest/python-notes
/src/ex32.py
635
4.1875
4
# -*- coding:utf-8 -*- t_count = [1, 2, 3, 4, 5] fruits = ['apples', 'bananas', 'Blueberries', 'oranges'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # print a integer list for number in t_count: print "The number is %d." % number # print a string list for fruit in fruits: print "The fruit type is %s." % fruit # print a multi-type list for i in change: print "I got %r." % i elements = [] # use the range function to construcr a list for i in range(0, 6): print "Add %d into elements list." % i elements.append(i) # the print them out for element in elements: print "The element is %d." % element
true
ca03996c06e344c39557e27a53fd7a4b8d243471
Nasir1004/assigment-3-python-with-dahir
/lopping numbers from one to ten.py
235
4.1875
4
''' numbers=1 for i in range (1,10): print(i) #this is example of for loop numbers from one to ten ''' # the whileloop example is current_number = 1 while current_number <=10: print(current_number ) current_number += 1
true
db42b6acb7d451e412f58c2837e4d1c309a412dc
wbluke/python_dojang
/01_input_output.py
649
4.15625
4
# if you divide integer by integer, result is float. num = 4 / 2 print(num) # 2.0 # convert float to int(int to float) num = int(4/2) print(num) # 2 num = float(1+3) print(num) # 4.0 # delete variable del num # if you want to know class' type print(type(3.3)) # <class 'float'> # when save input data on variable s = input() # string type a = int(input()) # integer type # several inputs b, c = input().split() # two string types b, c = map(int, input().split()) # two int types by using map() # control print method # sep : seperate character print(1, 2, 3, sep=', ') # 1, 2, 3 # end : end character print(1, end=' ') print(2) # 1 2
true
1c5ae131528b6e48953212686c066c5a9736a334
brandonkbuchs/UWisc-Python-Projects
/latlon.py
2,073
4.5
4
# This program collects latitude and longitude inputs from the user and returns # Information on the location of the quadrant of the coordinate provided def latlon(latitude, longitude): # Defines function # Latitude logic tests. if latitude == 0: # Test if on equator print "That location is on the equator." elif latitude > 0 and latitude <= 90: # Test if north of equator print "That location is north of the equator." elif latitude < 0 and latitude >= -90: # Test if south of equator. print "That location is south of the equator." elif latitude < -90 or latitude > 90: # Invalid entry. print "That location does not have a valid latitude!" # Longitude logic tests. if longitude == 0: # Test if prime meridian print "That location is on the prime meridian." elif longitude > 0 and longitude <= 180: # Tests if east of PM. print "That location is east of the prime meridian." elif longitude < 0 and longitude >= -180: # Tests if west of PM. print "That location is west of the prime meridian." elif longitude < -180 or longitude > 180: # Invalid entry. print "That location does not have a valid longitude!" while True: # Print instructions to the user. print "This program will tell you where latitude and longitude fall on the Earth." print "Please follow the instructions. Enter only real numbers." print "Latitude must be a number between -90 and 90." print "Longitude must be a number between -180 and 180.\n" latitude = raw_input("Enter your latitude here.>") # Latitude variable longitude = raw_input("Enter your longitude here.>") # Longitude variable try: # Test whether input is real number. latitude = float(latitude) longitude = float(longitude) break except: # Prints error message, restarts program for all non-real numbers. print "Please enter a valid number for both latitude and longitude." latlon(latitude, longitude) # Calls function
true
659e981c2f135e1ae4e3db3d62d90d359c787e71
21eleven/leetcode-solutions
/python/0673_number_of_longest_increasing_subsequence/lsubseq.py
1,203
4.125
4
""" 673. Number of Longest Increasing Subsequence Medium Given an integer array nums, return the number of longest increasing subsequences. Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Constraints: 1 <= nums.length <= 2000 -106 <= nums[i] <= 106 """ class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: N = len(nums) if N <= 1: return N lengths = [0]*N counts = [1]*N for j, num in enumerate(nums): for i in range(j): if nums[i] < nums[j]: if lengths[i] >= lengths[j]: lengths[j] = 1 + lengths[i] counts[j] = counts[i] elif lengths[i] + 1 == lengths[j]: counts[j] += counts[i] longest = max(lengths) return sum(c for i, c in enumerate(counts) if lengths[i] == longest)
true
6a52d60f15ef338e27b8c62ce8c034653c0a0f2f
21eleven/leetcode-solutions
/python/0605_can_place_flowers/three_slot.py
1,411
4.15625
4
""" 605. Can Place Flowers Easy You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false Constraints: 1 <= flowerbed.length <= 2 * 104 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 <= n <= flowerbed.length """ class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if len(flowerbed) == 1 and 1 != flowerbed[0]: return True left = n if flowerbed[0] == 0 and flowerbed[1] == 0: flowerbed[0] = 1 left -= 1 if flowerbed[-1] == 0 and flowerbed[-2] == 0: flowerbed[-1] = 1 left -= 1 if len(flowerbed) >= 3: for i in range(1,len(flowerbed)-1): if flowerbed[i-1] == 0 and flowerbed[i] == 0 and flowerbed[i+1] == 0: flowerbed[i] = 1 left -= 1 if left < 1: return True return False
true
a3f61908d09cba128724d0d6a533c59075156091
21eleven/leetcode-solutions
/python/1631_path_with_minimum_effort/bfs_w_heap.py
2,594
4.125
4
""" 1631. Path With Minimum Effort Medium You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. Example 1: Input: heights = [[1,2,2],[3,8,2],[5,3,5]] Output: 2 Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3. Example 2: Input: heights = [[1,2,3],[3,8,4],[5,3,5]] Output: 1 Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5]. Example 3: Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] Output: 0 Explanation: This route does not require any effort. Constraints: rows == heights.length columns == heights[i].length 1 <= rows, columns <= 100 1 <= heights[i][j] <= 106 """ class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: lcol = len(heights[0]) lrow = len(heights) path_effort = math.inf q = [(0,0,0)] visited = set() while q: effort, row, col = heapq.heappop(q) if row == lrow -1 and col==lcol-1: return effort if (row,col) in visited: continue visited.add((row,col)) up = (row-1, col) if up[0] < 0: up = None if col + 1 < lcol: right = (row,col+1) else: right = None if row+1 < lrow: down = (row+1, col) else: down = None if col -1 < 0: left = None else: left = (row, col-1) here = heights[row][col] routes = [up,down,left,right] for d in routes: if d: there = heights[d[0]][d[1]] step_effort = abs(there - here) heapq.heappush(q,(max(effort,step_effort),d[0],d[1]))
true
0790ccdc036798bf7ce9d542345f784dd6009d39
makhmudislamov/leetcode_problems
/microsoft/arr_and_str/set_matrix_zeroes.py
2,465
4.46875
4
""" Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] Follow up: A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? Youtube solution: https://www.youtube.com/watch?v=6_KMkeh5kEc """ def setZeroes(matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ # declaring height and width variables for iteration # initialize boolean (false)to mark if the first row should be filled with 0s height = len(matrix) width = len(matrix[0]) first_row_zero = False # iterate over the first row # if it has 0 change the boolean to true for cell in range(width): if matrix[0][cell] == 0: first_row_zero = True # iterate over each cell # if the cell contains 0 # mark the corresponding index of first row as zero >> denotes the whole column as 0 for row in range(height): for col in range(width): if matrix[row][col] == 0: matrix[0][col] = 0 # denotes: whole column as 0s # iterate each cell starting second row # declare boolean (false) if the cell is 0 # once a cell with 0 is reached change the boolean, break the loop for row in range(1, height): cell_has_zero = False for col in range(width): if matrix[row][col] == 0: cell_has_zero = True break # iterate over the columns # if the cell has 0 or (boolean above) or corresponding index of first row is 0 # change this cell to 0 for col in range(width): if cell_has_zero or matrix[0][col] == 0: matrix[row][col] = 0 # if the first row has 0 (boolean above) # iterate over the first row and change each cell to 0 if first_row_zero: for cell in range(width): matrix[0][cell] = 0 return matrix matrix = [ [0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5] ] print(setZeroes(matrix))
true
27a566d6f5312cf2b427d42c1e542d53a1384c21
makhmudislamov/leetcode_problems
/microsoft/arr_and_str/trapping_rain_water.py
1,224
4.28125
4
""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! Example: Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 """ # helper func # at the target index # expand to two sides until on of the side values is less then previous value - should increase # in that condition >> max value of one side - min value of another side # return the value >> cubes of water in each section def trap(height: [int]): if height is None or len(height) == 0: return 0 total = 0 level = 0 left = 0 right = len(height) - 1 while left < right: if height[left] < height[right]: lower = height[left] left += 1 else: lower = height[right] right -= 1 level = max(lower, level) total += level - lower print("lower", lower) print("total", total) return total height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] print(trap(height))
true
ff83309a29010223b289355195fad25ac86d36c7
karandevgan/Algorithms
/LargestNumber.py
779
4.28125
4
def compare(number, number_to_insert): str_number_to_insert = str(number_to_insert) str_number = str(number) num1 = str_number + str_number_to_insert num2 = str_number_to_insert + str_number if num1 > num2: return -1 elif num1 == num2: return 0 else: return 1 def largestNumber(A): ''' Given a list of numbers, return the string arranging the numbers in the given list forming largest number. Eg: A = [3,30,90,9], the function should return 990330 ''' isAllZero = True for num in A: if num != 0: isAllZero = False if (isAllZero): return '0' A.sort(cmp=compare) return ''.join([str(i) for i in A]) A = [3, 30, 34, 5, 9] print largestNumber(A)
true
6b3c9e414503f3b249e372f690c97e6f8cd52d78
Keikoyao/learnpythonthehardway
/Ex20.py
881
4.25
4
# -- coding: utf-8 -- from sys import argv script, input_file = argv #read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中 def print_all(f): print (f.read()) #seek() 移动文件读取指针到指定位置 def rewind(f): f.seek(0) #readline() will read the file line by line as if there is a for next loop automatically vs readlines()一次读取整个文件 def print_a_line(line_count,f): print (line_count,f.readline()) current_file = open(input_file) print("First let's print the whole file:\n") print_all(current_file) print("Now let's rewind, kind of like a tape.") rewind(current_file) print("Let's print three lines:") current_line = 1 print_a_line(current_line,current_file) current_line += 1 print_a_line(current_line,current_file) current_line += current_line + 1 print_a_line(current_line,current_file)
true
33e1e11d95b94d22e1fc939c716cd8251d04b034
TwoChill/Learning
/Learn Python 3 The Hard Way/ex34 - Accessing Elements of Lists.py
2,096
4.21875
4
# Remember, if it says "first," "second," then it's using ORDINAL, so subtract 1. # If it gives you CARDINAL, like "The animal at 1", then use it directly. # Check later with Python to see if you were correct. animal = ['bear','python3.7', 'peacock', 'kangaroo', 'whale', 'platypus'] # Q1. The animal at 1. <-- CARDINAL # A. The animal at 1 is the 2nd animal and is a python3.7.. # The 2nd animal is at 1 and is a; # PYTHON3.7 print("Q1: >>:",animal[1] ) # Q2. The third (3rd) animal. <-- ORDINAL # A. The third (3rd) animal is at 2 and is a peacock. # The animal at 2 is the 3rd animal and is a; # PEACOCK print("Q2: >>:",animal[(3 -1)] ) # Q3. The first (1st) animal. <-- ORDINAL # A. The first (1st) animal is at 0 and is a bear. # The animal at 0 is the 1st animal and is a; # BEAR print("Q3: >>:",animal[(1 -1)] ) # Q4. The animal at 3. <-- CARDINAL # A. The animal at 3 is the 4th animal and is a kangaroo. # The 4th animal is at 3 and is a; # KANGAROO print("Q4: >>:",animal[3] ) # Q5. The fifth (5th) animal. <-- ORDINAL # A. The fifth (5th) animal is at 4 and is a whale. # The animal at 4 is the 5th animal and is a; # WHALE print("Q5: >>:",animal[(5 -1)] ) # Q6. The animal at 2. <-- CARDINAL # A. The animal at 2 is the 3rd animal and is a peacock. # The 3rd animal is at 2 and is a; # PEACOCK print("Q6: >>:",animal[2] ) # Q7. The sixth (6th) animal. <-- ORDINAL # A. The sisth (6th) animal is at 5 and is a platypus. # The animal at 5 is the 6th animal and is a; # PLATYPUS print("Q7: >>:",animal[(6 -1)] ) # Q8. The animal at 4. <-- CARDINAL # A. The animal at 4 is the 5th animal and is a whale. # The 5th animal is at 4 and is a; # WHALE print("Q8: >>:",animal[4] )
true
2ffa957733ffcd46c2fd448b75f6bbe9c64043ec
TwoChill/Learning
/Learn Python 3 The Hard Way/ex32 - Loops and Lists.py
1,770
4.5625
5
hair = ['brown', 'blond', 'red'] eye = ['brown', 'blue', 'green'] weights = [1, 2, 3, 4] the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print(f'This is count {number}') # same as above for fruit in fruits: print(f'A fruit of type: {fruit}') # als we can go through mixxed lists too. # notice we have to use {} since we don't know what's in it for i in change: print(f'I got {i}') # we can also build lists, first start with an empty one. elements = [] # then use the range function to do 0 to 5 counts for i in range(0,6): print(f'Adding {i} to list.') # append is a function that lists understand. elements.append(i) # now we can print them out too for i in elements: print(f'Element was: {i}') # Q. Could you have avoided that for-loop on line 27 and just assigned range(0,6) directly to elements? # No, that would just show the tekst range(0,6) # Q. What other operations can you do to lists besides append? # .append() -> Adds an item to a list. # .clear() -> Removes all item in a list # .copy() -> Returns a shallow copy of itself # .count() -> Return a number of occurrences in a list # .extend() -> Extend list by appending elements from the iterable. # .index() -> Return first index of value. # .insert() -> Insert object before index. # .pop() -> Remove and return item at index (default last). # .remove() -> Remove first occurrence of value. # .reverse() -> Reverse items in a list. # .sort() -> Sorts items in a list alphabetically.
true
545cbfef3ca36549f96c421a54fafc0c0c92d318
TwoChill/Learning
/Learn Python 3 The Hard Way/ex15 - Reading Files.py
1,845
4.625
5
# This line imports the variable argument argv from the sys module. from sys import argv # These are the TWO command line arguments you MUST put in when running the script. script, filename = argv # This line opens the filename argument and puts it content in a variable. txt = open(filename) print("\n\nTHIS IS THE ARGV METHODE TO OPEN A FILE\n") # This line prints out the name of the filename. print(f"Here's your file {filename}:\n ") # This line prints out the txt variable by calling the .read() function. print(txt.read()) # # This line asked the user to put in the filename again. # print("Type the filename again: ") # #This line creates a variable unnoticable to the user. # file_again = input('>') # # # This line uses the previous variable to open the typed in filename # # and places this in a second variable. # txt_again = open(file_again) # # # This line prints out the second variable which contains the ex15_sample.txt # print(txt_again.read()) # txt_again.close() ### EX QUESTION ### # Remove line 18 to 29 # Use only input and try the script that way. print("\nTHIS IS THE INPUT METHODE TO OPEN A FILE\n") file_name = input('What is the name of the txt file?: ') print("\nHere's your filename:", str(file_name), "\n") txt = open(file_name) # Here Python makes a "file object" print(txt.read()) # This is were the file is being read and printed. txt.close() # This code closes the file, # Why is one way of getting the filename better that another? # Michael: I think the use of the input function instead of the arvg # is better because it only uses the input from a user. # The user doesn't start this program from a terminal, # thus it can't put in the filename before the program runs. # On the other hand I think the agvr METHODE uses less code and probably uses # less computing power.
true
4c7fdd6fe35f53ac8a12e8b3a3c69a64e08b3b28
cazzara/mycode
/random-stdlib/use-random.py
2,112
4.65625
5
#!/usr/bin/env python3 import random ## Create a random number generator object # This can be used to instantiate multiple instances of PRNGs that are independent of one another and don't share state r = random.Random() ## Seed random number generator # This initializes the state of the PRNG, by default it uses the current system time # Calling this function isn't entirely necessary because the seed function is called when the Random object is created r.seed() print("[+] Initialized a PRNG using default seed (system time)") ## Optionally you can specify the source of randomness (os.urandom) or pass in a str, int or bytes like object # r.seed('banana') ## randrange(start, stop) -- Select a random element from range(start, stop) print("[+] Print 5 random numbers between 1 and 10 using r.randrange(1, 11)") for i in range(5): print("{} ".format(r.randrange(1, 11)), end='') # Prints a number between 1 and 10 print() ## randint(a, b) -- return a random int N such that a <= N <= b, basically like saying randrange(a, b+1) print("[+] Print 5 random numbers between 1 and 10 using r.randint(1, 10)") for i in range(5): print("{} ".format(r.randint(1, 10)), end='') print() flavors = ['apple', 'kiwi', 'orange', 'grape', 'strawberry'] print("[+] List of items (flavors):") print(flavors) ## choice(seq) -- Returns a random element from a non-empty sequence print("[+] Select a random element from a list using r.choice(flavors)") print(r.choice(flavors)) # Prints a random flavor from the list ## shuffle(list) -- shuffles a list in place print("[+] Use r.shuffle(flavors) to randomly redistribute items in a list") r.shuffle(flavors) print(flavors) ## sample(population, k) -- returns a list of k elements from a population, sampling without replacement print("[+] Select k elements from a range or collection (w/o replacement) using r.sample(l, 10)") l = range(1, 101) print(r.sample(l, 10)) # print 10 random numbers from 1 - 100 ## random() -- returns a random float in the range [0.0, 1.0) print("[+] Print 5 random floats using r.random()") for i in range(5): print(r.random())
true
8068f6de2b10e0d0673a0d96f8a62135223624f7
cazzara/mycode
/if-test2/if-test2.py
380
4.1875
4
#!/usr/bin/env python3 # Author: Chris Azzara # Purpose: Practice using if statements to test user input ipchk = input("Set IP Address: ") if ipchk == '192.168.70.1': print("The IP Address was set as {}. That is the same as the Gateway, not recommended".format(ipchk)) elif ipchk: print("The IP Address was set as {}".format(ipchk)) else: print("No IP Address provided")
true
5eca3115baaf3a1f4d09a92c3e8bef73b5e655e8
cazzara/mycode
/datetime-stdlib/datetime-ex01.py
931
4.28125
4
from datetime import datetime # required to use datetime ## WRITE YOUR OWN CODE TO DO SOMETHING. ANYTHING. # SUGGESTION: Replace with code to print a question to screen and collect data from user. # MORE DIFFICULT -- Place the response(s) in a list & continue asking the question until the user enters the word 'quit' startTime = datetime.now() # returns the time of right now from the datetime object # Note that datetime is an object, not a simple string. ## Explore the statrTime object print('The startTime hour is: ' + str(startTime.hour)) print('The startTime minute is: ' + str(startTime.minute)) print('The startTime day is: ' + str(startTime.day)) print('The startTime year is: ' + str(startTime.year)) print("This is how long it takes Python to count to 50:") for i in range(50): pass ## Figure out how long it took to do that something print('The code took: ' + str(datetime.now() - startTime) + ' to run.')
true
1ed15bd4d250bfc4fc373c26226f84f83c40cdcd
shishir7654/Python_program-basic
/listcomprehension1.py
513
4.375
4
odd_square = [x **2 for x in range(1,11) if x%2 ==1] print(odd_square) # for understanding, above generation is same as, odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print( odd_square) # below list contains power of 2 from 1 to 8 power_of_2 = [2 ** x for x in range(1, 9)] print (power_of_2 ) string = "my phone number is : 11122 !!" print("\nExtracted digits") numbers = [x for x in string if x.isdigit()] print (numbers )
true
c084419e361233b87f85c9a688e29f6471376579
brennanmcfarland/physics-class
/18-1a.py
1,469
4.125
4
import matplotlib.pyplot as plt import math def graphfunction(xmin,xmax,xres,function,*args): "takes a given mathematical function and graphs it-how it works is not important" x,y = [],[] i=0 while xmin+i*xres<=xmax: x.append(xmin+i*xres) y.append(function(x[i],*args)) i+=1 return [x,y] def iterateX(xn,yn,zn,a,b,c,dt): "iterate for x" return xn+a*(yn-xn)*dt def iterateY(xn,yn,zn,a,b,c,dt): "iterate for y" return yn+(-yn+b*xn-xn*zn)*dt def iterateZ(xn,yn,zn,a,b,c,dt): return zn+(-c*zn+xn*yn)*dt #HERE IS WHERE THE PROGRAM STARTS: #iterate 100 times: iterations = 100 #create our list of n integers and configure the axes: n = list(range(0,iterations+1)) #plt.axis([0,len(n)-1,0,1]) #give it our initial variables: x = [0] y = [10] z = [0] dt = .01 a = 10 b = 28 c = 8/3 #for 100 iterations, find the next x and y by iterating: for i in range(0,iterations): x.append(iterateX(x[i],y[i],z[i],a,b,c,dt)) y.append(iterateY(x[i],y[i],z[i],a,b,c,dt)) z.append(iterateZ(x[i],y[i],z[i],a,b,c,dt)) #plot the approximation: plt.plot(n,x) #reset variables x = [0] y = [11] z = [0] dt = .01 a = 10 b = 28 c = 8/3 #for 100 iterations, find the next x and y by iterating: for i in range(0,iterations): x.append(iterateX(x[i],y[i],z[i],a,b,c,dt)) y.append(iterateY(x[i],y[i],z[i],a,b,c,dt)) z.append(iterateZ(x[i],y[i],z[i],a,b,c,dt)) #plot the approximation: plt.plot(n,x) plt.show()
true
65a294810e1afc9d10fa24f84d8a4d60b5ec02c3
jle33/PythonLearning
/PythonMasterCourse/PythonMasterCourse/GenetratorExample.py
1,494
4.25
4
import random #Generator Example def get_data(): """Return 3 random integers between 0 and 9""" print("At get_data()") return random.sample(range(10), 3) def consume(): """Displays a running average across lists of integers sent to it""" running_sum = 0 data_items_seen = 0 print("At top of consume()") while True: print("Calling consume() Yield") data = yield #Saves current state and sends control back to the caller. Resumes at this spot when a callee calls send #Resumes here print("At consume() after send({}) was called".format(data)) data_items_seen += len(data) running_sum += sum(data) print('The running average is {}'.format(running_sum / float(data_items_seen))) def produce(consumer): """Produces a set of values and forwards them to the pre-defined consumer function""" print("At top of produce()") while True: data = get_data() print('Produced {}'.format(data)) print("Before consumer.send({}) is called".format(data)) consumer.send(data) #Saves current state and sends control to consumer print("Calling produce() Yield") #Resumes here yield print("At produce() after next(producer) is called") if __name__ == '__main__': consumer = consume() print("Before consumer.send(none)") consumer.send(None) producer = produce(consumer) for _ in range(10): print('Producing...') next(producer)
true
218254f6a4c1152326423160bebdb9d8461d05a2
jodaz/python-sandbox
/automate-boring-stuff-python/tablePrinter.py
1,093
4.34375
4
#! python3 # tablePrinter.py - Display a list of lists of strings in # a well-organized table. table_data = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def print_table(main_arr): col_widths = [0] * len(main_arr) # Look for largest str length and save it in a column for single_arr in main_arr: curr_index = main_arr.index(single_arr) for string in single_arr: if len(string) > col_widths[curr_index]: col_widths[curr_index] = len(string) # Create a table from array `(x, y)` => `(y, x)` table = [] for x in range(len(main_arr[0])): temp_arr = [] for y in range(len(main_arr)): temp_arr.append(main_arr[y][x]) table.append(temp_arr) temp_arr = [] # Print pretty table for arr in table: for string in arr: str_index = arr.index(string) print(string.rjust(col_widths[str_index] + 1), end='') print() print_table(table_data)
true
b3bba5c4526cff24bd9b71a60aadddcf6e623228
jodaz/python-sandbox
/automate-boring-stuff-python/strongPassword.py
424
4.34375
4
#! python3 # strongPassword.py - Find is your password is strong. import re password = input('Introduce your password: ') find_upper = re.compile(r'[A-Z]').findall(password) find_lower = re.compile(r'[a-z]').findall(password) find_d = re.compile(r'\d').search(password) if find_upper and find_lower and find_d and len(password) >= 8: print('Your password is strong.') else: print('Your password is NOT strong.')
true
98f72a0486ba5cc22b42028c6bb0cd5e79ca2597
Peterbamidele/PythonDeitelChapterOneExercise
/2.3 Fill in the missing code.py
394
4.125
4
"""(Fill in the missing code) Replace *** in the following code with a statement that will print a message like 'Congratulations! Your grade of 91 earns you an A in this course' . Your statement should print the value stored in the variable grade : if grade >= 90""" #Solution grade = 90 if grade >= 90: #print("Congratulations! Your grade of 91 earns you an A in this course")
true
201a2cbfa51168e159fae14bf438adb71c2b129e
cmdellinger/Code-Fights
/Interview Practice/01 Arrays/isCryptSolution.py
1,213
4.1875
4
""" Codefights: Interview Prep - isCryptSolution.py Written by cmdellinger This function checks a possible solution to a cryptarithm. Given a solution as a list of character pairs (ex. ['A', '1']), the solution is valid of word_1 + word_2 == word_3 once decoded. See .md file for more information about cryptarithm and problem constraints. """ def isCryptSolution(crypt, solution): ''' checks that list of pairs is a solution for 3 word cryptarithm; see problem for more details ''' # change list of pairs to dictionary dictionary = dict(solution) # helper functions for map def str_decode(string = ''): #-> string ''' changes values in string according to key,value pair ''' return ''.join([dictionary[letter] for letter in string]) def lead_zeros(string = ''): #-> boolean ''' checks if a string of numbers has no lead zero ''' return len(string) == len(str(int(string))) # decode crypt values decoded = map(str_decode, crypt) # check that no leading zeros and word_1+word_2==word_3 return all(map(lead_zeros, decoded)) and int(decoded[0]) + int(decoded[1]) == int(decoded[2]) if __name__ == '__main__': print(__doc__)
true
53bc1949d4d989f076e481341e6c52fffb549da4
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.01_ex_02.py
655
4.15625
4
height = float(input("What is your height?")) weight = float(input("What is your weight?")) BMI = 0 condition = "undetermined" def calcBMI(height,weight): global BMI,condition BMI = (weight/height) * 703 if BMI < 18.5 : condition = "condition is Underweight" elif BMI < 24.9 : condition = "condition is Normal" elif BMI < 29.9 : condition = "Overweight" elif BMI < 34.9 : condition = "Obese" elif BMI < 39.9 : condition = "Very obese" elif BMI > 39.9 : condition = "Morbidly Obese" calcBMI(height, weight) print("Your BMI is", BMI) print("Your condition is", condition)
true
9bfca2db61d14c15064ed7c42e3bdeb6714de64c
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.02_ex06.py
559
4.25
4
def recursion(): username = input("Please enter your username: ") password = input("Please enter your password: ") if username == "username" and password == "password": print("correct.") else: if password == "password": print("Username is incorrect.") recursion() elif username == "username": print("Password is incorrect.") recursion() else: print("Username and password are incorrect.") recursion() recursion()
true
bf23188fb3c90c34da9d2b64ba6aeed16d623fd1
shashankgargnyu/algorithms
/Python/GreedyAlgorithms/greedy_algorithms.py
1,920
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains Python implementations of greedy algorithms from Intro to Algorithms (Cormen et al.). The aim here is not efficient Python implementations but to duplicate the pseudo-code in the book as closely as possible. Also, since the goal is to help students to see how the algorithm works, there are print statements placed at key points in the code. The performance of each function is stated in the docstring, and loop invariants are expressed as assert statements when they are not too complex. This file contains: recursive_activity_selector() greedy_activity_selector() """ def recursive_activity_selector(s, f, k, n=None): """ Args: s: a list of start times f: a list of finish times k: current position in n: total possible activities Returns: A maximal set of activities that can be scheduled. (We use a list to hold the set.) """ if n is None: assert(len(s) == len(f)) # each start time must match a finish time n = len(s) # could be len f as well! m = k + 1 while m < n and s[m] < f[k]: # find an activity starting after our last # finish m = m + 1 if m < n: return [m] + recursive_activity_selector(s, f, m, n) else: return [] def greedy_activity_selector(s, f): """ Args: s: a list of start times f: a list of finish times Returns: A maximal set of activities that can be scheduled. (We use a list to hold the set.) """ assert(len(s) == len(f)) # each start time must match a finish time n = len(s) # could be len f as well! a = [] k = 0 for m in range(1, n): if s[m] >= f[k]: a.append(m) k = m return a
true
8f2a974d5aa0eb91db1b2978ced812678e34f69f
LYoung-Hub/Algorithm-Data-Structure
/wordDictionary.py
2,039
4.125
4
class TrieNode(object): def __init__(self): self.cnt = 0 self.children = [None] * 26 self.end = False class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: None """ curr = self.root for ch in word: idx = ord(ch) - 97 if not curr.children[idx]: curr.children[idx] = TrieNode() curr.cnt += 1 curr = curr.children[idx] curr.end = True def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ return self.searchHelper(word, 0, self.root) def searchHelper(self, word, idx, node): if len(word) == idx: return node.end ch = word[idx] if ch == '.': if node.cnt == 0: return False else: for n in node.children: if n and self.searchHelper(word, idx + 1, n): return True return False else: loc = ord(ch) - 97 if not node.children[loc]: return False else: return self.searchHelper(word, idx + 1, node.children[loc]) # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word) if __name__ == '__main__': wordDict = WordDictionary() wordDict.addWord('a') wordDict.addWord('ab') wordDict.addWord('a') wordDict.search('a.') wordDict.search('ab') wordDict.search('.a') wordDict.search('.b') wordDict.search('ab.') wordDict.search('.') wordDict.search('..')
true
cf90416b58d12338fb6c626109ef0ecf11c0807f
sravanneeli/Data-structures-Algorithms
/stack/parenthesis_matching.py
888
4.125
4
""" Parenthesis Matching: whether braces are matching in a string """ from stack.stack_class import Stack bracket_dict = {')': '(', ']': '[', '}': '{'} def is_balanced(exp): """ Check whether all the parenthesis are balanced are not :param exp: expression in string format :return: True or False """ st = Stack(len(exp)) st.create() for i in range(len(exp)): if exp[i] == '(' or exp[i] == '[' or exp[i] == '{': st.push(exp[i]) elif exp[i] == ')' or exp[i] == ']' or exp[i] == '}': if st.is_empty(): return False x = st.pop() if bracket_dict[exp[i]] != x: return False return st.is_empty() def main(): exp = '({a+b}*(c-d))' print("The expression parenthesis are balanced or not ?", is_balanced(exp)) if __name__ == '__main__': main()
true
db069f0bdb81b54b5ca7ab589fd8db33bff0368b
lajospajtek/thought-tracker.projecteuler
/p057.py
1,097
4.15625
4
#!/usr/bin/python # -*- coding: Latin1 -*- # Problem 057 # # It is possible to show that the square root of two can be expressed as an infinite continued fraction. # # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # # By expanding this for the first four iterations, we get: # # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + 1/2) = 7/5 = 1.4 # 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... # 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... # # The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example # where the number of digits in the numerator exceeds the number of digits in the denominator. # # In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? # The continued fraction can be expressed recursively as: # a_n+1 = 1 / (1 + a_n) # # ans: 153 from fractions import Fraction from math import log, floor n = 0 a = Fraction(3, 2) for i in range(1, 1000): a = 1 + (1 / (1 + a)) if floor(log(a.denominator, 10)) < floor(log(a.numerator, 10)): n += 1 print n
true
4e612bc6b0425b59d37e9341cd4bc8783a2f2bad
sauravgsh16/DataStructures_Algorithms
/g4g/ALGO/Searching/Coding_Problems/12_max_element_in_array_which_is_increasing_and_then_decreasing.py
1,725
4.15625
4
''' Find the maximum element in an array which is first increasing and then decreasing ''' ''' Eg: arr = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1] Output: 500 Linear Search: We can search for the maximum element and once we come across an element less than max, we break and return max ''' ''' Binary Search We can modify the standard Binary Search algorithm for the given type of arrays. 1) If the mid element is greater than both of its adjacent elements, then mid is the maximum. 2) If mid element is greater than its next element and smaller than the previous element then maximum lies on left side of mid. Example array: {3, 50, 10, 9, 7, 6} 3) If mid element is smaller than its next element and greater than the previous element then maximum lies on right side of mid. Example array: {2, 4, 6, 8, 10, 3, 1} ''' def find_element(arr, low, high): # Base Case: Only one element is present in arr[low..high] if high == low: return arr[low] # If there are two elements and first is greater, then # the first element is maximum if high == low + 1 and arr[low] >= arr[high]: return arr[low] # If there are two elements and second is greater, then # the second element is maximum if high == low + 1 and arr[high] > arr[low]: return arr[high] mid = (low + high) / 2 if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]: return mid if arr[mid] > arr[mid - 1] and arr[mid] < arr[mid + 1]: return find_element(arr, mid+1, high) else: return find_element(arr, low, mid-1) arr = [1, 3, 50, 10, 9, 7, 6] print find_element(arr, 0, len(arr)-1)
true
b820d08879eecae30d95bcaa221be073f71a22ad
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/RN_7_check_each_internal_node_has_exactly_1_child.py
1,372
4.15625
4
''' Check if each internal node has only one child ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # In Preorder traversal, descendants (or Preorder successors) of every node # appear after the node. In the above example, 20 is the first node in preorder # and all descendants of 20 appear after it. All descendants of 20 are smaller # than it. For 10, all descendants are greater than it. In general, we can say, # if all internal nodes have only one child in a BST, then all the descendants # of every node are either smaller or larger than the node. The reason is simple, # since the tree is BST and every node has only one child, # all descendants of a node will either be on left side or right side, # means all descendants will either be smaller or greater. def has_only_one_child(pre): INT_MIN = -2**32 INT_MAX = 2**32 prev = pre[0] for i in range(1, len(pre)-1): ele = pre[i] if ele <= INT_MAX and ele >= INT_MIN: if ele < prev: INT_MAX = prev - 1 else: INT_MIN = prev + 1 prev = ele else: return False return True # Other solutions # 1) preorder = reverse (postorder) only if nodes contain one child pre = [8, 3, 5, 7, 6] print has_only_one_child(pre)
true
1507e2ab37a5f36e5ba8a20fd41acff2815e9fa8
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/24_symmetric_tree_iterative.py
1,250
4.28125
4
''' Check if the tree is a symmetric tree - Iterative ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def check_symmetric(root): if not root: return True if not root.left and not root.right: return True q = [] # Append left and right, since we don't need to check root node q.append(root.left) q.append(root.right) while len(q) > 0: left_node = q.pop(0) right_node = q.pop(0) if left_node.val != right_node.val: return False if left_node.left and right_node.right: q.append(left_node.left) q.append(right_node.right) elif left_node.left or right_node.right: return False if left_node.right and right_node.left: q.append(left_node.right) q.append(right_node.left) elif left_node.right or right_node.left: return False return True, count root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) print check_symmetric(root)
true
06354d4f46de16ca4d0162548992da2fe6061973
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/26_find_middle_of_perfect_binary_tree.py
900
4.15625
4
''' Find middle of a perfect binary tree without finding height ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None ''' Use two pointer slow and fast, like linked list Move fast by 2 leaf nodes, and slow by one. Once fast reaches leaf, print slow. Recursively call next route. ''' def find_middle_util(slow, fast): # import pdb; pdb.set_trace() if slow is None or fast is None: return if fast.left is None and fast.right is None: print slow.val, find_middle_util(slow.left, fast.left.left) find_middle_util(slow.right, fast.left.left) def find_middle(root): find_middle_util(root, root) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) find_middle(root)
true
748bccf48ef30c79bb9312e2d3be2c37c66cf459
HarperHao/python
/mypython/第七章文件实验报告/001.py
1,235
4.28125
4
"""统计指定文件夹大小以及文件和子文件夹数量""" import os.path totalSize = 0 fileNum = 0 dirNum = 0 def visitDir(path): global totalSize global fileNum global dirNum for lists in os.listdir(path): sub_path = os.path.join(path, lists) if os.path.isfile(sub_path): fileNum = fileNum + 1 totalSize = totalSize + os.path.getsize(sub_path) elif os.path.isdir(sub_path): dirNum = dirNum + 1 visitDir(sub_path) def sizeConvert(size): K, M, G = 1024, 1024 ** 2, 1024 ** 3 if size >= G: return str(size / G) + 'G Bytes' elif size >= M: return str(size / M) + 'M Bytes' elif size >= K: return str(size / K) + 'K Bytes' else: return str(size) + 'Bytes' def main(path): if not os.path.isdir(path): print("error") return visitDir(path) def output(path): print('The total size of {} is:{} ({}) Bytes'.format(path, sizeConvert(totalSize), str(totalSize))) print("The total number of files in {} is {}".format(path, fileNum)) print("The total number of directories in {} is {}".format(path, dirNum)) path = r'K:\编程' main(path) output(path)
true
6fecf6d2c96d29409c240b76a7a0844668b17594
kalyanitech2021/codingpractice
/string/easy/prgm4.py
701
4.25
4
# Given a String S, reverse the string without reversing its individual words. Words are separated by dots. # Example: # Input: # S = i.like.this.program.very.much # Output: much.very.program.this.like.i # Explanation: After reversing the whole # string(not individual words), the input # string becomes # much.very.program.this.like.i # Expected Time Complexity: O(|S|) # Expected Auxiliary Space: O(|S|) def reverseWords(str, n): words = str.split('.') string = [] for word in words: string.insert(0, word) reverseStr = '.'.join(string) return reverseStr str = "i.like.this.program.very.much" n = len(str) print(reverseWords(str, n))
true
83b5224314c1eba5d985c0413b69960dc9c26c3a
pavel-malin/new_practices
/new_practice/decorators_practice/abc_decorators_meta.py
654
4.1875
4
''' Using a subclass to extend the signature of its parent's abstract method import abc class BasePizza(object, metaclass=abc.ABCMeta): @abc.abstractmethod def get_ingredients(self): """Returns the ingredient list.""" class Calzone(BasePizza): def get_ingredients(self, with_egg=False): egg = Egg() if with_egg else None return self.ingredients + [egg] ''' import abc class BasePizza(object, metaclass=abc.ABCMeta): @abc.abstractmethod def get_ingredients(self): """Returns the ingredient list.""" class DiesPizza(BasePizza): @staticmethod def get_ingredients(): return None
true
9216d686ad0deb206998db55005c4e4889c6332f
courtneyng/Intro-To-Python
/If-exercises/If-exercises.py
681
4.125
4
# Program ID: If-exercises # Author: Courtney Ng, Jasmine Li # Period 7 # Program Description: Using if statements months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November'] # months.append('December') ans = input("Enter the name of a month: ") if ans == "January" or "March" or "May" or "July" or "August" or "October" or "December": print("No. of days: 31") elif ans == "February": print("No. of days: 28/29") elif ans == "April" or "June" or "September" or "November": print("No. of days: 30") elif ans in months: print ("found it") else: print("That is not a month.")
true
2d1e08e74910d00f238f27b705b7196a35dacdf9
courtneyng/Intro-To-Python
/Tuples_and_Lists/A_List_Of_Numbers.py
1,727
4.28125
4
# Program ID: A_List_Of_Numbers # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # numList = [1, 1, 2, 3, 5, 8, 11, 19, 30, 49] # product = 30*8*11*19*30*49 num1 = int(input("Enter the first number.")) numList = [100, 101, 102] numList.append(num1) numList.remove(100) numList.remove(101) numList.remove(102) print(numList) print("The amount of numbers is: 1") # gathering variables num2 = int(input("Add another number to the list")) numList.append(num2) num3 = int(input("Add another number to the list")) numList.append(num3) num4 = int(input("Add another number to the list")) numList.append(num4) num5 = int(input("Add another number to the list")) numList.append(num5) num6 = int(input("Add another number to the list")) numList.append(num6) num7 = int(input("Add another number to the list")) numList.append(num7) num8 = int(input("Add another number to the list")) numList.append(num8) num9 = int(input("Add another number to the list")) numList.append(num9) num10 = int(input("Add another number to the list")) numList.append(num10) print("This is the list of numbers:", numList) print("The amount of numbers is: 10") print("If you add all the numbers together the sum is:", sum(numList)) # sum = 0 # for x in range(0,9): # sum = sum + list[x] product = 1 for x in range(0, 9): product = product * numList[x] print("If you multiply all the numbers in the list the product is:", product) # this will sort the numbers in order from least to highest numList.sort() print("The smallest number is:", numList.pop(0)) print("The largest number is:", numList.pop(8)) print("The new amount is: 8") print(numList)
true
b4a981c76af3be316f3b22b2c0d979bd7386e73c
courtneyng/Intro-To-Python
/Tuples_and_Lists/list_extensions.py
797
4.34375
4
# Program ID: lists_extensions # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # Given list fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # The new list extensions test fruits.count('apple') print(fruits.count('apple')) # Added a print statement to show output fruits.count('tangerine') print(fruits.count('tangerine')) fruits.index('banana') print(fruits.index('banana')) fruits.index('banana', 4) # Find the next banana starting at pos 4 print(fruits.index('banana', 4)) fruits.reverse() print(fruits) fruits.append('grape') # Adds grape to the list print(fruits) fruits.sort() # Alphabetically sorts print(fruits) fruits.pop() # Takes a variable out and puts it back in print(fruits.pop(3))
true
bcef00fbacb443c75b8a69a97c56d78924ce4d7d
pouya-mhb/University-Excersises-and-Projects
/Compiler Class/prefix suffix substring proper prefix subsequence/substring of a string.py
454
4.53125
5
#substring of a string stringValue = input("Enter string : ") def substring(stringValue): print("The original string is : " + str(stringValue)) # Get all substrings of string # Using list comprehension + string slicing res = [stringValue[i: j] for i in range(len(stringValue)) for j in range(i + 1, len(stringValue) + 1)] # printing result print("All substrings of string are : " + str(res)) substring(stringValue)
true
d6cf7a9f246b4e57cc1f748eccfd1d24dc64575a
shiblon/pytour
/3/tutorials/recursion.py
1,988
4.78125
5
# vim:tw=50 """Recursion With an understanding of how to write and call functions, we can now combine the two concepts in a really nifty way called **recursion**. For seasoned programmers, this concept will not be at all new - please feel free to move on. Everyone else: strap in. Python functions, like those in many programming languages, are _recurrent_: they can "call themselves". A |def| is really a sort of template: it tells you *how something is to be done*. When you call it, you are making it do something *specific*, because you are providing all of the needed data as arguments. From inside of the function, you can call that same template with something specific *and different* - this is recursion. For example, look at the |factorial| function in the code window. It starts with a **base case**, which is usually a really easy version of the problem, where you know the answer right away. For non-easy versions of the problem, it then defines a **recursion**, where it calls itself with a smaller version of the problem and uses that to compute the answwer. Exercises - Uncomment the |print| statements inside of |factorial| (above and below |smaller_problem|) to see what is happening. - Practice saying "recur" instead of "recurse", which is not a word. Now practice feeling good because you are right. """ __doc__ = """Introduction to Recursion The "factorial" of something is formed by multiplying all of the integers from 1 to the given number, like this: factorial(5) == 5 * 4 * 3 * 2 * 1 You can do this recursively by noting that, e.g., factorial(5) == 5 * factorial(4) This can't go forever, because we know that factorial(1) == 1 See below. """ def factorial(n): if n <= 1: return 1 # print("before recursion", n) smaller_problem = factorial(n - 1) # print("after recursion", n) return n * smaller_problem # This gets big fast print("2! =", factorial(2)) print("7! =", factorial(7)) print("20! =", factorial(20))
true
d7771130f1ee54dc2d3924e8266c91c559bf4063
shiblon/pytour
/3/tutorials/hello.py
1,596
4.71875
5
# vim:tw=50 """Hello, Python 3! Welcome to Python version 3, a very fun language to use and learn! Here we have a simple "Hello World!" program. All you have to do is print, and you have output. Try running it now, either by clicking *Run*, or pressing *Shift-Enter*. What happened? This tutorial contains a *Python 3 interpreter*. It starts at the top of your program (or _script_) and does what you tell it to until it reaches the bottom. Here, we have told it to do exactly one thing: **print** a **string** (text surrounded by quotation marks) to the output window, and it has. The word |print| is a special function in Python 3. It instructs the interperter to output what you tell it to. In this tutorial, we capture that output in the window below the code so that you can easily see it. We will get very comfortable with this as the tutorial goes on. Meanwhile, let's talk about the tutorial itself: - The Table of Contents is above, marked *TOC*. - *Page-Up* and *Page-Down* keys can be used to navigate. - Code can be run with the *Run* button or *Shift-Enter*. - Check out the options in the *Run* menu (the arrow). Among other things, you can see what you have changed from the original slide. The tutorial will try to remember those changes for a long time. Exercises - Try removing each of the quotation marks in turn. What happens? - Change the string to say hello specifically to you. - Print 'Hello, Python!' using two strings instead of one, like this: |print('Hello', 'Python!')|. What did |print| do for you automatically? """ print('Hello, Python!')
true
60b0ff336ec48cb60786c47528fa31777ffc8693
shiblon/pytour
/tutorials/urls.py
1,583
4.125
4
# vim:tw=50 """Opening URLs The web is like a huge collection of files, all jamming up the pipes as they fall off the truck. Let's quickly turn our attention there, and learn a little more about file objects while we're at it. Let's use |urllib| (http://docs.python.org/2/library/urllib.html) to open the Google Privacy Policy, so we can keep an eye on how long it is getting. The result of urllib.urlopen is a file-like object. It therefore supports |read|, and it supports line-by-line iteration. This is classic Python: define a simple interface, then just make sure you provide the needed functions. It doesn't have to _be_ a file to _act_ like a file, and how it acts is all we care about. We'll continue in that spirit by writing our code so that we can accept any iterable over lines, which also makes it easy to test. Exercises - Open the web site as a file object, get all of the words by using |str.split| on each line (|help| will come in handy), then count and sum up. """ __doc__ = """Count the Words Note that "count_words" does not specify a file object, but rather something that can look like a bunch of lines, because that's all it needs. >>> count_words(['some words here\\n', 'some words there']) 6 """ import urllib def count_words(lines): """Counts all words in the 'lines' iterable.""" # # TODO: Fill this in. def main(): f = urllib.urlopen( "https://www.google.com/intl/en/policies/privacy/") print count_words(f) # I get 2571 f.close() if __name__ == '__main__': if not _testmod().failed: print "Success!" main()
true
503f1aa74c5d3c2dbd5f5b4e6f97cdbc67aeaa23
abhisek08/Basic-Python-Programs
/problem22.py
1,247
4.4375
4
''' You, the user, will have in your head a number between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high, too low, or your number. At the end of this exchange, your program should print out how many guesses it took to get your number. As the writer of this program, you will have to choose how your program will strategically guess. A naive strategy can be to simply start the guessing at 1, and keep going (2, 3, 4, etc.) until you hit the number. But that’s not an optimal guessing strategy. An alternate strategy might be to guess 50 (right in the middle of the range), and then increase / decrease by 1 as needed. After you’ve written the program, try to find the optimal strategy! (We’ll talk about what is the optimal one next week with the solution.) ''' import random import sys a=random.randint(0,1) print('the generated number is',a) b=input('Is it too high,too low or your number: ') if b=='your number': sys.exit() else: count=1 while b!='your number': a = random.randint(0, 3) print('the generated number is', a) b = input('Is it too high,too low or your number: ') count+=1 print('The computer took {} guesses'.format(count))
true
6affb302816e8fcf5015596806c5082fa2d3d30d
abhisek08/Basic-Python-Programs
/problem5.py
1,248
4.25
4
''' Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Extras: Randomly generate two lists to test this Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon) List properties ''' import random a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c=[] d=0 while d<len(a): if a[d] in b: c.append(a[d]) d+=1 d=0 while d<len(b): if b[d] in a: c.append(b[d]) d+=1 print(set(c)) # randomly creating a list from a range of numbers using random module and random.sample(array,no. of reqd elements) function a=random.sample(range(0,10),5) b=random.sample(range(0,20),8) print('the elements in a are: ',a) print('the elements in b are: ',b) c=[] d=0 while d<len(a): if a[d] in b: c.append(a[d]) d+=1 d=0 while d<len(b): if b[d] in a: c.append(b[d]) d+=1 print('the unique elements in list a and b are: ',set(c))
true
107a32642f0def5ce58017a4d6156bebf1287a1c
abhisek08/Basic-Python-Programs
/problem16.py
1,008
4.34375
4
''' Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull ... Until the user guesses the number. ''' import random a=random.sample(range(1000,10000),1) print('Welcome to the Cows and Bulls Game!') user_input= int(input('Guess a 4 digit number: '))
true
cc0fe65d97a1914cc986b3dd480ff97bd8a53320
wilsouza/RbGomoku
/src/core/utils.py
1,504
4.28125
4
import numpy as np def get_diagonal(table, offset): """ Get diagonal from table Get a list elements referencing the diagonal by offset from main diagonal :param table: matrix to get diagonal :param offset: Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0). :return: list elements from request diagonal """ diagonal = np.diag(table, k=offset).tolist() return diagonal def get_opposite_diagonal(table, offset): """ Get diagonal from table Get a list elements referencing the opposite diagonal by offset from opposite diagonal Positive get below, and negative get higher diagonal from opposite diagonal 0 1 2 3 4 0 a a a a . 1 a a a . b 2 a a . b b 3 a . b b b 4 . b b b b :param table: matrix to get diagonal :param offset: Offset of the opposite diagonal from the main diagonal. Can be positive or negative. Defaults to opposite diagonal (0). :return: list elements from request opposite diagonal """ column_inverted = table[:, ::-1] transposed = column_inverted.transpose() inverted_opp_diagonal = np.diag(transposed, k=-offset).tolist() opposite_diagonal = inverted_opp_diagonal[::-1] return opposite_diagonal
true
7653c8e4c2176b8672a531988ef26c1331540b5d
bsundahl/IACS-Computes-2016
/Instruction/Libraries/bryansSecondLibrary.py
245
4.4375
4
def factorial(n): ''' This function takes an integer input and then prints out the factorial of that number. This function is recursive. ''' if n == 1 or n == 0: return 1 else: return n * factorial(n-1)
true
7b5e3de71b6bdd958b6debafe5d0882503f87f20
rahul-pande/ds501
/hw1/problem1.py
1,445
4.3125
4
#------------------------------------------------------------------------- ''' Problem 1: getting familiar with python and unit tests. In this problem, please install python verion 3 and the following package: * nose (for unit tests) To install python packages, you can use any python package managment software, such as pip, conda. For example, in pip, you could type `pip install nose` in the terminal to install the package. Then start implementing function swap(). You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal. ''' #-------------------------- def bubblesort( A ): ''' Given a disordered list of integers, rearrange the integers in natural order using bubble sort algorithm. Input: A: a list, such as [2,6,1,4] Output: a sorted list ''' for i in range(len(A)): for k in range( len(A) - 1, i, -1): if ( A[k] < A[k - 1] ): swap( A, k, k - 1 ) #-------------------------- def swap( A, i, j ): ''' Swap the i-th element and j-th element in list A. Inputs: A: a list, such as [2,6,1,4] i: an index integer for list A, such as 3 j: an index integer for list A, such as 0 ''' ######################################### ## INSERT YOUR CODE HERE A[i], A[j] = A[j], A[i] #########################################
true
7de333d37e0af493325591c525cef536290f13be
GameroM/Lists_Practice
/14_Lists_Even_Extract.py
360
4.21875
4
## Write a Python program to print the numbers of a specified list after removing ## even numbers from it x = [1,2,3,4,5,6,7,8,15,20,25,42] newli = [] def evenish(): for elem in x: if elem % 2 != 0: newli.append(elem) return newli print('The original list is:', x) print('The list without even numbers is',evenish())
true
0632f5713b13eb0b83c1866566125a069d4f997d
GameroM/Lists_Practice
/8_Lists_Empty_Check.py
445
4.375
4
## Write a Python program to check if a list is empty or not x = [] def creation(): while True: userin=input('Enter values,type exit to stop:') if userin == 'exit': break else: x.append(userin) return x print('The list created from user input is:',creation()) if x == []: print('The list created is empty') else: print('The list created is not empty')
true
8a8ccbf32880b637bba81516a69e23b3cabd2229
blackseabass/Python-Projects
/Homework/week5_exercise2.py
1,483
4.3125
4
#!/usr/bin/env python """ File Name: week5_exercise2.py Developer: Eduardo Garcia Date Last Modified: 10/4/2014 Description: User plays Rock, Paper, Sciissors with the computer Email Address: garciaeduardo1223@gmail.com """ import random def main(): print("Rock. Paper. Scissors." "\n" "Enter 1 for Rock, 2 for Paper or 3 for Scissors.", "\n") answer() def random_integer(): return random.randrange(1,3) def answer(): player = int(input("Enter your choice: ")) while player != 1 and player != 2 and player != 3: print("Invalid entry. Please try again.") player = int(input("Enter 1, 2, or 3.: ")) display_answer(player) def display_answer(player): computer_answer = random_integer() print("Computer picks: ", computer_answer, "\n") winner(computer_answer, player) def winner(computer, player): if computer == player: print("Draw. Try again.") answer() elif computer == 1 and player == 2: print("Paper covers rock. Player wins!") elif computer == 1 and player == 3: print("Rock smashes scissors. Computer wins.") elif computer == 2 and player == 1: print("Paper covers rock. Computer wins.") elif computer == 2 and player == 3: print("Scissors cut paper. Player wins!") elif computer == 3 and player == 1: print("Rock smashes scissors. Player wins!") elif computer == 3 and player == 2: print("Scissors cut paper. Computer wins.") main()
true
c8639d6ef1d7044f1a840f7446fc7cfb624a1209
amitravikumar/Guvi-Assignments
/Program14.py
283
4.3125
4
#WAP to find the area of an equilateral triangle import math side = float(input("Enter the side: ")) def find_area_of_triangle(a): return(round(((1/4) * math.sqrt(3) * (a**2)), 2)) result = find_area_of_triangle(side) print("Area of equilateral triangle is ", result)
true
5e5803c836e3d83613e880061b29d6862774836b
amitravikumar/Guvi-Assignments
/Program4.py
309
4.3125
4
#WAP to enter length and breadth of a rectangle and find its perimeter length, breadth = map(float,input("Enter length and breadth with spaces").split()) def perimeter_of_rectangle(a,b): return 2*(a+b) perimeter = perimeter_of_rectangle(length,breadth) print("Perimeter of rectangle is", perimeter)
true
1971a9a13cc857df612840450c1fb3f455d8a034
gitfolder/cct
/Python/calculator.py
1,680
4.21875
4
# take user input and validate, keep asking until number given, or quit on CTRL+C or CTR+D def number_input(text): while True: try: return float(input(text)) except ValueError: print("Not a number") except (KeyboardInterrupt, EOFError): raise SystemExit def print_menu(): print("\n1. Add\n2. Substract\n3. Multiply\n4. Divide\n0. Exit") return number_input("Select option : ") # recursively calling this function to run def select_option( opt ): if opt == 0: return elif opt == 1: add() elif opt == 2: substract() elif opt == 3: multiply() elif opt == 4: divide() else: print("Not an option") select_option( print_menu() ) def add(): amount = number_input("Enter how many numbers you want to sum : ") total = 0 for n in range(int(amount)): total += number_input("Enter number {0} : ".format(n+1)) print( "\nSum result : " + str( total )) def substract(): one = number_input("Provide first number : ") two = number_input("Provide second number : ") print( "\nSubstraction result : " + str( one-two)) def multiply(): amount = number_input("Enter how many numbers you want to multiply : ") product = 1.0 if amount>0 else 0 for n in range(int(amount)): product *= number_input("Enter number {0} : ".format(n+1)) print( "\nMultiplication result : " + str( product )) def divide(): one = number_input("Provide first number : ") two = number_input("Provide second number : ") if two == 0: print("Cannot divide by zero") else: print( "\nDivision result : " + str( one/two)) select_option( print_menu() ) # initial call
true
45b822d5189e7e8317f7deb26deed12e7562d29e
jebarajganesh1/Ds-assignment-
/Practical 5.py
1,415
4.1875
4
#Write a program to search an element from a list. Give user the option to perform #Linear or Binary search. def LinearSearch(array, element_l):     for i in range (len(array)):         if array[i] == element_l:             return i     return -1 def BinarySearch(array, element_l):     first = 0     array.sort()     last = len(array)-1     done = False     while (first <= last) and not done:         mid = (first+last)//2         if array[mid] == element_l:             done = True         else:             if element_l < array[mid]:                 last = last - 1             else:                 first = first + 1     return done array = [45,78,23,17,453,7] print(array) element_l = int(input("Enter the element you want to search : ")) print("Select 'L' for Linear Search and 'B' for Binary Search") yourChoice = str(input("Enter your choice : ")) if yourChoice == 'L':         result = LinearSearch(array, element_l)     print(result)     if result == 1:         print("Element is present.")     else :         print("Element not present.") else:     result = BinarySearch(array, element_l)     print(result)     if result == -1:         print("Element not present.")     else :          print("Element is present.")
true
cfa2dee09f7d4b7dec7c328f8cef5f085e17dd95
Amirreza5/Class
/example_comparison02.py
218
4.125
4
num = int(input('How many numbers do you want to compare: ')) list_num = list() for i in range(0, num): inp_num = int(input('Please enter a number: ')) list_num.append(inp_num) list_num.sort() print(list_num)
true
5436a11b86faa2784d2a3aab6b9449bbca9df2fd
mynameismon/12thPracticals
/question_6#alt/question_6.py
1,755
4.125
4
<<<<<<< HEAD # Create random numbers between any two values and add them to a list of fixed size (say 5) import random #generate list of random numbers def random_list(size, min, max): lst = [] for i in range(size): lst.append(random.randint(min, max)) return lst x = random_list(5, 1, 100) # the list of random numbers print("The list of random numbers is:") print(x) l = int(input("Enter a number you would like to insert")) # enter the index to be inserted in x i = int(input("Enter the index to be inserted")) # insert the number in the list x.insert(i, l) print("The list after insertion is:") print(x) # Would you like to delete a number from the list? y = input("Would you like to delete a number from the list? (y/n)") if y == "y": # enter the index to be deleted j = int(input("Enter the index to be deleted")) # delete the number from the list x.pop(j) print("The list after deletion is:") print(x) else: print("Thank you for using the program") ======= def generate(n=5): import random a=int(input("Enter base number : ")) b=int(input("Enter ceiling number : ")) for i in range(0,n) : x=round(a+(b-a)*random.random(),2) list1.append(x) print(list1) global val val=float(input("Enter value to be removed: ")) temp(val) def update(pos,num) : list1.insert(pos-1,num) print(list1) def temp(val) : list1.remove(val) print(list1) global num global pos num=int(input("Enter value to be inserted : ")) pos=int(input("Enter position from start of previous value (1 onward) : ")) update(pos,num) n=int(input("Enter length of list : ")) list1=[] generate(n) >>>>>>> 964a130e5215f229fac07a4e9133df869309fe82
true
2300e2a3c3ccb603907e2bcbd895f25cbbca504d
Enfioz/enpands-problems
/weekdays.py
535
4.34375
4
# Patrick Corcoran # A program that outputs whether or not # today is a weekday or is the weekend. import datetime now = datetime.datetime.now() current_day = now.weekday weekend = (5,7) if current_day == weekend: print("It is the weekend, yay!") else: print("Yes, unfortunately today is a weekday.") time_diff = datetime.timedelta(days = 4) future_day = now + time_diff weekend = (5,7) if future_day == weekend: print("It is the weekend, yay!") else: print("Yes, unfortunately today is a weekday.")
true
617d4aa7fd56d6511a28954c6bfd384c8b9251d1
andreeaanbrus/Python-School-Assignments
/Assignment 1/8_setB.py
893
4.25
4
''' Determine the twin prime numbers p1 and p2 immediately larger than the given non-null natural number n. Two prime numbers p and q are called twin if q-p = 2. ''' def read(): x = int(input("Give the number: ")) return x def isPrime(x): if(x < 2): return False if(x > 2 and x % 2 == 0): return False for d in range(3, int(x / 2), 2): if(x % d == 0): return False return True def twin(x, y): if(y - x == 2): return True return False def printNumbers(a, p1): print("The twin prime numbers immediately larger than the given number",a,"are", p1) def determineTwinPrimeNumbers(x): n = x + 1 ok = False while(not ok): if(isPrime(n) and isPrime(n + 2)): return (n, n+2) n = n + 1 a = read() printNumbers(a, determineTwinPrimeNumbers(a))
true
cc608e03490880b23f1cb4e53a781670cb898d01
vlad-bezden/py.checkio
/oreilly/reverse_every_ascending.py
1,364
4.40625
4
"""Reverse Every Ascending https://py.checkio.org/en/mission/reverse-every-ascending/ Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should not modify the contents of the original iterable. Input: Iterable Output: Iterable Precondition: Iterable contains only ints """ from typing import List def reverse_ascending(items: List[int]) -> List[int]: result = [] cursor = 0 for i in range(1, len(items)): if items[i] <= items[i - 1]: result.extend(reversed(items[cursor:i])) cursor = i result = result + [*reversed(items[cursor:])] return result if __name__ == "__main__": assert list(reverse_ascending([1, 2, 3, 4, 5])) == [5, 4, 3, 2, 1] assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [ 10, 7, 5, 4, 8, 7, 2, 3, 1, ] assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1] assert list(reverse_ascending([])) == [] assert list(reverse_ascending([1])) == [1] assert list(reverse_ascending([1, 1])) == [1, 1] assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1] print("PASSED!!!")
true
d0ef4d781f2518afb1210abedf14239e6b06c0e2
vlad-bezden/py.checkio
/oreilly/remove_all_after.py
1,247
4.65625
5
"""Remove All After. https://py.checkio.org/en/mission/remove-all-after/ Not all of the elements are important. What you need to do here is to remove all of the elements after the given one from list. For illustration, we have an list [1, 2, 3, 4, 5] and we need to remove all the elements that go after 3 - which is 4 and 5. We have two edge cases here: (1) if a cutting element cannot be found, then the list shoudn't be changed; (2) if the list is empty, then it should remain empty. Input: List and the border element. Output: Iterable (tuple, list, iterator ...). """ from typing import List def remove_all_after(items: List[int], border: int) -> List[int]: return items[:items.index(border) + 1] if border in items else items if __name__ == "__main__": assert list(remove_all_after([1, 2, 3, 4, 5], 3)) == [1, 2, 3] assert list(remove_all_after([1, 1, 2, 2, 3, 3], 2)) == [1, 1, 2] assert list(remove_all_after([1, 1, 2, 4, 2, 3, 4], 2)) == [1, 1, 2] assert list(remove_all_after([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7] assert list(remove_all_after([], 0)) == [] assert list(remove_all_after([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7] print("PASSED!!!")
true
56e4820a3eb210789a5b4d86cf4386d4028edb91
vlad-bezden/py.checkio
/oreilly/how_deep.py
1,704
4.5625
5
"""How Deep. https://py.checkio.org/en/mission/how-deep/ You are given a tuple that consists of integers and other tuples, which in turn can also contain tuples. Your task is to find out how deep this structure is or how deep the nesting of these tuples is. For example, in the (1, 2, 3) tuple the depth of nesting is 1. And in the (1, 2, (3,)) tuple the depth of nesting is 2, since one of the elements of the first tuple is also a tuple. And in the (1, 2, (3, (4,))) tuple the depth of nesting is 3, since one of the elements of the first tuple is a tuple, but since inside it contains another tuple, it increases the depth by one, so the nesting depth turns out to be 3. It’s important to note that an empty tuple also increases the depth of the structure, that is, () - indicates the nesting depth 1, ((),) - indicates the nesting depth 2. Input: Tuple of tuple of tuple... Output: Int. Precondition: Given iterables have to be well founded. """ from typing import Any, Iterable, Tuple, Union T = Union[int, Tuple[Any]] def how_deep(structure: Tuple[T, ...]) -> int: return 1 + max( (how_deep(t) for t in structure if isinstance(t, Iterable)), default=0 ) if __name__ == "__main__": assert how_deep((1, 2, 3)) == 1 assert how_deep((1, 2, (3,))) == 2 assert how_deep((1, 2, (3, (4,)))) == 3 assert how_deep(()) == 1 assert how_deep(((),)) == 2 assert how_deep((((),),)) == 3 assert how_deep((1, (2,), (3,))) == 2 assert how_deep((1, ((),), (3,))) == 3 assert how_deep((1, 2, ((3,), (4,)))) == 3 assert how_deep((((), (), ()),)) == 3 print("PASSED!!!")
true
4ea6cc426ebeeaf6f594465a48a6bfb836555467
vlad-bezden/py.checkio
/mine/perls_in_the_box.py
2,354
4.65625
5
"""Pearls in the Box https://py.checkio.org/en/mission/box-probability/ To start the game they put several black and white pearls in one of the boxes. Each robot has N moves, after which the initial set is being restored for the next game. Each turn, the robot takes a pearl out of the box and puts one of the opposite color back. The winner is the one who takes the white pearl on the Nth move. Our robots don't like uncertainty, that's why they want to know the probability of drawing a white pearl on the Nth move. The probability is a value between 0 (0% chance or will not happen) and 1 (100% chance or will happen). The result is a float from 0 to 1 with two decimal digits of precision (±0.01). You are given a start set of pearls as a string that contains "b" (black) and "w" (white) and the number of the move (N). The order of the pearls does not matter. Input: The start sequence of the pearls as a string and the move number as an integer. Output: The probability for a white pearl as a float. Example: checkio('bbw', 3) == 0.48 checkio('wwb', 3) == 0.52 checkio('www', 3) == 0.56 checkio('bbbb', 1) == 0 checkio('wwbb', 4) == 0.5 checkio('bwbwbwb', 5) == 0.48 Precondition: 0 < N ≤ 20 0 < |pearls| ≤ 20 """ def checkio(marbles, step): n = len(marbles) def move(w, b, step): if step == 1: return w / n p1 = 0 if b == 0 else move(w + 1, b - 1, step - 1) p2 = 0 if w == 0 else move(w - 1, b + 1, step - 1) return w / n * p2 + b / n * p1 return round(move(marbles.count("w"), marbles.count("b"), step), 2) if __name__ == "__main__": result = checkio("wbb", 3) assert result == 0.48, f"1st {result=}" result = checkio("wwb", 3) assert result == 0.52, f"2nd {result=}" result = checkio("www", 3) assert result == 0.56, f"3rd {result=}" result = checkio("bbbb", 1) assert result == 0, f"4th {result=}" result = checkio("wwbb", 4) assert result == 0.5, f"5th {result=}" result = checkio("bwbwbwb", 5) assert result == 0.48, f"6th {result=}" result = checkio("w" * 20, 20) assert result == 0.57, f"7th {result=}" result = checkio("b" * 20, 20) assert result == 0.43, f"8th {result=}" print("PASSED!")
true