blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6169a5437d4ea11923d0857763dbc8c26ab8fc10
lonely7yk/LeetCode_py
/LeetCode484FindPermutation.py
2,821
4.21875
4
""" By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decreasing relationship between two numbers, 'I' represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n (n is the length of the secret signature plus 1). For example, the secret signature "DI" can be constructed by array [2,1,3] or [3,1,2], but won't be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can't represent the "DI" secret signature. On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, ... n] could refer to the given secret signature in the input. Example 1: Input: "I" Output: [1,2] Explanation: [1,2] is the only legal initial spectial string can construct secret signature "I", where the number 1 and 2 construct an increasing relationship. Example 2: Input: "DI" Output: [2,1,3] Explanation: Both [2,1,3] and [3,1,2] can construct the secret signature "DI", but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3] Note: The input string will only contain the character 'D' and 'I'. The length of input string is a positive integer and will not exceed 10,000 """ from typing import List # # reverse: O(n) - O(1) # class Solution: # def findPermutation(self, s: str) -> List[int]: # # 将 nums 从 left 到 right 中的进行反转 # def reverse(nums, left, right): # while left < right: # nums[left], nums[right] = nums[right], nums[left] # left += 1 # right -= 1 # n = len(s) # nums = list(range(1, n + 2)) # i = 0 # while i < n: # # I 表示上升,不需要改动 # if s[i] == 'I': # i += 1 # else: # j = i # # 找到递减的范围 # while j < n and s[j] == 'D': # j += 1 # reverse(nums, i, j) # i = j # return nums # Stack: O(n) - O(n) class Solution: def findPermutation(self, s: str) -> List[int]: stack = [1] res = [] n = len(s) for i in range(n): # 每当遇到 I,表明升序,把 stack 全部排出放到 res 中 if s[i] == 'I': while stack: res.append(stack.pop()) # 每个数当要放到 stack 中 stack.append(i + 2) while stack: res.append(stack.pop()) return res
true
1ffd9e7ad58b95c2cc0ea50932209de8ce1218c2
lonely7yk/LeetCode_py
/LeetCode425WordSquares.py
2,901
4.15625
4
""" Given a set of words (without duplicates), find all word squares you can build from them. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. b a l l a r e a l e a d l a d y Note: There are at least 1 and at most 1000 words. All words will have the exact same length. Word length is at least 1 and at most 5. Each word contains only lowercase English alphabet a-z. Example 1: Input: ["area","lead","wall","lady","ball"] Output: [ [ "wall", "area", "lead", "lady" ], [ "ball", "area", "lead", "lady" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). Example 2: Input: ["abat","baba","atan","atal"] Output: [ [ "baba", "abat", "baba", "atan" ], [ "baba", "abat", "baba", "atal" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). """ from typing import List import collections class TrieNode: def __init__(self): self.words = [] self.children = collections.defaultdict(TrieNode) class Trie: def __init__(self): self.root = TrieNode() def addWord(self, word): p = self.root for c in word: p = p.children[c] p.words.append(word) def getWordsWithPrefix(self, prefix): p = self.root for c in prefix: p = p.children[c] return p.words # Trie + BackTracking # 用 trie 记录每个前缀对应的 words。对于每一次 backtrack,找到下一层的前缀,根据前缀找到所有单词候选,然后依次回溯 # https://leetcode.com/problems/word-squares/discuss/91333/Explained.-My-Java-solution-using-Trie-126ms-1616 class Solution: def wordSquares(self, words: List[str]) -> List[List[str]]: trie = Trie() for word in words: trie.addWord(word) def dfs(curr, res, step, n): # step == n 说明已生成 word square if step == n: res.append(curr) return prefix = "" for i in range(step): prefix += curr[i][step] # 找到所有前缀为 prefix 的单词 wordsWithPrefix = trie.getWordsWithPrefix(prefix) for word in wordsWithPrefix: dfs(curr + [word], res, step + 1, n) res = [] for word in words: dfs([word], res, 1, len(word)) return res words = ["area","lead","wall","lady","ball"] res = Solution().wordSquares(words) print(res)
true
b336e49c34dff2b02b7fd80f3f1ef8ab12513ec5
lonely7yk/LeetCode_py
/LeetCode401BinaryWatch.py
2,155
4.1875
4
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. Example: Input: n = 1 Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] Note: - The order of output does not matter. - The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". - The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". """ from typing import List class Solution: # DFS: 24ms 90% # 注意精度问题 # def readBinaryWatch(self, num: int) -> List[str]: # def dfs(res, time, num, start, timeList): # # round 很关键 # if round((time - int(time)) * 100) > 59 or int(time) > 11: return # if num == 0: # hour = int(time) # minute = round(100 * (time - hour)) # round 很关键 # hourStr = str(hour) # minuteStr = str(minute) if minute >= 10 else '0' + str(minute) # res.append(hourStr + ':' + minuteStr) # return # for i in range(start, len(timeList)): # dfs(res, time + timeList[i], num - 1, i + 1, timeList) # timeList = [8, 4, 2, 1, 0.32, 0.16, 0.08, 0.04, 0.02, 0.01]; # res = [] # dfs(res, 0, num, 0, timeList) # return res # Bit operation: 32ms 57% def readBinaryWatch(self, num: int) -> List[str]: res = [] for h in range(12): for m in range(60): if (bin(h) + bin(m)).count('1') == num: res.append('%d:%02d' % (h, m)) return res if __name__ == '__main__': res = Solution().readBinaryWatch(2) print(res)
true
8c36c1856f7a002736f85d36d5b6af586b613faf
lonely7yk/LeetCode_py
/LeetCode1000/LeetCode1363LargestMultipleofThree.py
2,572
4.25
4
""" Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. Since the answer may not fit in an integer data type, return the answer as a string. If there is no answer return an empty string. Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: "" Example 4: Input: digits = [0,0,0,0,0,0] Output: "0" Constraints: 1 <= digits.length <= 10^4 0 <= digits[i] <= 9 The returning answer must not contain unnecessary leading zeros. """ from typing import List class Solution: # O(n): 88ms 100% # 3的倍数的数必须满足所有位数加起来是3的倍数 # 如果加起来是 %3=1 说明要减去一个 %3=1 或者两个 %3=2 # 如果加起来是 %3=2 说明要减去一个 %3=2 或者两个 %3=1 def largestMultipleOfThree(self, digits: List[int]) -> str: # 使用map_生成字符串 def generateStr(map_): res = "" for i in range(9, 0, -1): res += str(i) * map_[i] # res 为空,说明1-9都没值 if res == "": return "0" if map_[0] else "" res += "0" * map_[0] return res # 删除num个 map_ 中余数为 remainder 的数 def delMap(map_, num, remainder): tmp = {1: [1, 4, 7], 2: [2, 5, 8]} l = tmp[remainder] cnt = 0 for i in l: while map_[i]: map_[i] -= 1 cnt += 1 if cnt == num: break if cnt == num: break map_ = [0 for i in range(10)] s = 0 for digit in digits: map_[digit] += 1 s += digit r1 = map_[1] + map_[4] + map_[7] r2 = map_[2] + map_[5] + map_[8] if s % 3 == 0: return generateStr(map_) elif s % 3 == 1: if r1 >= 1: delMap(map_, 1, 1) return generateStr(map_) elif r2 >= 2: delMap(map_, 2, 2) return generateStr(map_) elif s % 3 == 2: if r2 >= 1: delMap(map_, 1, 2) return generateStr(map_) elif r1 >= 2: delMap(map_, 2, 1) return generateStr(map_) return "" if __name__ == '__main__': digits = [0,0,0] res = Solution().largestMultipleOfThree(digits) print(res)
true
07f16a7a3c94ffb901cfa58800c1ea6d43c01ba2
lonely7yk/LeetCode_py
/LeetCode080RemoveDuplicatesfromSortedArrayII.py
2,097
4.125
4
""" Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory. Clarification: Confused why the returned value is an integer, but your answer is an array? Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } Example 1: Input: nums = [1,1,1,2,2,3] Output: 5, nums = [1,1,2,2,3] Explanation: Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Input: nums = [0,0,1,1,1,1,2,3,3] Output: 7, nums = [0,0,1,1,2,3,3] Explanation: Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length. Constraints: 0 <= nums.length <= 3 * 10^4 -10^4 <= nums[i] <= 10^4 nums is sorted in ascending order. """ from typing import List # O(n) class Solution: def removeDuplicates(self, nums: List[int]) -> int: if not nums: return 0 idx1 = 1 idx2 = 1 lastVal = nums[0] cnt = 1 while idx2 < len(nums): if nums[idx2] == nums[idx2 - 1]: cnt += 1 else: lastVal = nums[idx2] cnt = 1 if cnt <= 2: nums[idx1] = nums[idx2] idx1 += 1 idx2 += 1 return idx1
true
5e6d19174f78688d3bf5abc2d9b7c1cf8e2233b0
lonely7yk/LeetCode_py
/MergeSort.py
866
4.15625
4
def mergeSort(nums): sort(nums, 0, len(nums) - 1) def sort(nums, left, right): if left < right: mid = (left + right) // 2 sort(nums, left, mid) sort(nums, mid + 1, right) merge(nums, left, mid, right) def merge(nums, left, mid, right): tmp = [0 for i in range(right - left + 1)] p1, p2 = left, mid + 1 p = 0 while p1 <= mid and p2 <= right: if nums[p1] < nums[p2]: tmp[p] = nums[p1] p += 1 p1 += 1 else: tmp[p] = nums[p2] p += 1 p2 += 1 while p1 <= mid: tmp[p] = nums[p1] p += 1 p1 += 1 while p2 <= right: tmp[p] = nums[p2] p += 1 p2 += 1 for i in range(left, right + 1): nums[i] = tmp[i - left] nums = [2,6,1,23,6,5,3] mergeSort(nums) print(nums)
false
2ad306d0b108ae285a558caf7a29d762f3a2caee
devendrapansare21/Python-with-Lets-Upgrage
/Assignment_Day-4.py
693
4.1875
4
'''Program to find number of 'we' in given string and their positions in string ''' str1="what we think we become ; we are Python pragrammers" print("Total number of 'we' in given string are ", str1.count("we")) print("position of first 'we'--> ",str1.find("we")) print("position of last 'we'--> ",str1.rfind("we")) '''Program to check whether the given string is in lower case or upper case''' str1 = input("Enter the string --->") while str1.isalpha()!=True: str1=input("Given string is not proper. Please enter again--->") if str1.islower()==True: print("Given string is in Lower Case") elif str1.isupper()==True: print("Given string is in Upper Case")
true
48021044a11b7c223777765d4586f343212bc0ac
dasszer/sudoki
/sudoki.py
2,445
4.15625
4
import pprint # sudoki.py : solves a sudoku board by a backtracking method def solve(board): """ Solves a sudoku board using backtracking :param board: 2d list of ints :return: solution """ find = find_empty(board) if find: row, col = find else: return True for i in range(1, 10): if valid(board, (row, col), i): board[row][col] = i if solve(board): return True board[row][col] = 0 return False def find_empty(board): """ finds an empty space in the board :param board: partially complete board :return: (int, int) row col """ for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None def valid(board, pos, num): """ Returns true if the attempted move is valid :param board: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # Check in row for i in range(0, len(board)): if board[pos[0]][i] == num and pos[1] != i: return False # Check in col for i in range(0, len(board)): if board[i][pos[1]] == num and pos[1] != i: return False # Check in box box_x = pos[1]//3 box_y = pos[0]//3 for i in range(box_y * 3, box_y * 3 + 3): for j in range(box_x * 3, box_x * 3 + 3): if board[i][j] == num and (i, j) != pos: return False return True def print_board(board): """ prints the board :param board: 2d List of ints :return: None """ for i in range(len(board)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - -") for j in range(len(board[0])): if j % 3 == 0: print(" | ", end = "") if j == 8: print(board[i][j], end="\n") else: print(str(board[i][j]) + " ", end="") board = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7], ] pp = pprint.PrettyPrinter(width=41, compact=True) solve(board) pp.pprint(board)
true
a1f9631072c3e8da6a46de97db2cb0a3b9bcdb99
priyatharshini23/2
/power.py
217
4.4375
4
# 2 num=int(input("Enter the positive integer:")) exponent=int(input("Enter exponent value:")) power=1 i=1 while(i<=exponent): power=power*num i=i+1 print("The Result of{0}power{1}={2}".format(num,exponent,power)
true
6730b03c1a640ce24dcca9a2a335906295209339
rajasekaran36/GE8151-PSPP-2020-Examples
/unit2/practice-newton-squareroot.py
362
4.3125
4
print("Newton Method to find sq_root") num = int(input("Enter number: ")) guess = 1 while(True): x = guess f_x = (x**2) - num f_d_x = 2*x actual = x - (f_x/f_d_x) actual = round(actual,6) if(guess == actual): break else: print("guess=",guess,"actual=",actual) guess = actual print("sq_root of",num,"is",guess)
true
70d0f8c4cc2fc8bb64513fa5b4350501a0812ad7
Aamir-Meman/BoringStuffWithPython
/sequences/reduce-transforming-list.py
646
4.15625
4
""" The reduce function is the one iterative function which can be use to implement all of the other iterative functions. The basic idea of reduce is that it reduces the list to a single value. The single value could be sum as shown below, or any kind of object including a new list """ from _functools import reduce nums = [1, 2, 3, 4, 5] def sum_number(total, next_val): print("total: {}, next_val: {}".format(total, next_val)) return (total + next_val)/2 # total_sum = reduce(sum_number, nums) total_sum = reduce(lambda acc, current: acc + current, nums) # total_sum = reduce(lambda x, y: (x + y)/2, nums) print(total_sum)
true
067c7fea36ae0de1ac94277db2f3215270a1040d
Tiger-a11y/PythonProjects
/dict Exercise.py
479
4.21875
4
# Apni Dictionary dict = { "Set" : "Sets are used to store multiple items in a single variable.", "Tuples" : "Tuples are used to store multiple items in a single variable.", "List" : "Lists are used to store multiple items in a single variable.", "String" : "Strings in python are surrounded by either single quotation marks, or double quotation marks."} print("enter the Word:") Search=input() print(dict[Search]) print("Thanks for using Dictionary")
true
e6dd483cc36f30e58d629cb0936ce4ef10c7e840
zachariahsharma/learning-python
/numbers/6.py
1,313
4.40625
4
#this is telling python to remmember the types of people types_of_people=10 #this is showng us a sentance that tells us how many types of people x=f"there are {types_of_people} types of people" #this is telling python to remmember the word binary under the word binary binary='binary' #this is telling python to remmember 'don't' under do_not do_not="don't" #this telling us that not every type knows binary y=f"people who know {binary} and people who {do_not}" #this is telling us again how many types of people there are print(x) #this is telling us again that not everyone knows binary print(y) #this telling us that they said that there are 10 types print(f"I said:'{x}'") #this telling us that they said that not every one knows binary print(f"I also said:'{y}'") #this is telling python to remmember false under hilarious hilarious=False #this tells python that eny time someone types in joke_evalouation it says 'ins't that # joke so funny' joke_evaloation="isn't that joke so funny?! {}" #this is telling us that the joke is not funny print(joke_evaloation.format(hilarious)) #this is telling python half of a sentance w=("this the left side of...") #this is telling python the other half of the sentance e=("a string with a right side.") #this is telling us the sentance put together print(w+e)
false
0d19edda62a7a9a5d74f0cd59405eb82cbaa924f
sankalpg10/GAN_Even_Num_Generator
/dataset.py
1,240
4.125
4
import math import numpy as np def int_to_bin(number: int) -> int: # if number is negative or not an integer raise an error if number < 0 or type(number) is not int: raise ValueError("only positive integers are allowed") # converts binary number into a list and returns it return [int(x) for x in list(bin(number))[2:]] from typing import Tuple, List def data_generator(max_int: int, batch_size: int=16) -> Tuple[List[int], List[List[int]]]: # calculate number of digits required to represent the largest number provided by user # i.e. max length = log2(max_int) max_length = int(math.log(max_int, 2)) # generate data, i.e. total batch_size numeer of even integers between 0 and max_int/2 sampled_integers = np.random.randint(0, int(max_int)/2, batch_size) # generate labels for that, all would be 1 as all of them are even numbers labels = [1] * batch_size # generate binary numbers for training data = [int_to_bin(int(x*2)) for x in sampled_integers] # 0 padding to make the length of all binary numbers of same length i.e. equal to max_length data = [([0]*(max_length - len(x))) + x for x in data] return labels, data
true
75764f96681592643f63082b017aa4c1a64d5e56
justawho/Python
/TablePrinter.py
620
4.25
4
## A function named printTable() that rakes a list of lists of strings and ## displays it in a well-organized table def printTable(someTable): colWidths = [0] * len(someTable) for j in range (len(someTable[0])): for i in range(len(someTable)): colWidths[i] = len(max(someTable[i], key=len)) item = someTable[i][j] print (item.rjust(colWidths[i]), end='' + ' ') print('') tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] printTable(tableData)
true
92f7400e1ffa24879e1626c42e1e5c21c2e4eda8
eshthakkar/coding_challenges
/bit_manipulation.py
1,108
4.125
4
# O(n^2 + T) runtime where n is the total number of words and T is the total number of letters. def max_product(words): """Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. >>> print max_product(["ac","abb"]) 0 >>> print max_product(["wtfn","abcde","abf"]) 20 """ max_product = 0 bytes = [0] * len(words) for i in xrange(len(words)): val = 0 for char in words[i]: val |= 1<<(ord(char) - ord('a')) bytes[i] = val for i in xrange(len(words)): for j in xrange(i+1,len(words)): if bytes[i] & bytes[j] == 0: max_product = max(max_product,len(words[i]) * len(words[j])) return max_product if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
true
3e6f61f56ba8f3973be04896b5827c9bf99f664b
eshthakkar/coding_challenges
/rectangle_overlap.py
1,895
4.1875
4
# Overlapping rectangle problem, O(1) space and time complexity def find_rectangular_overlap(rect1, rect2): """ Find and return the overlapping rectangle between given 2 rectangles""" x_overlap_start_pt , overlap_width = find_range_overlap(rect1["x_left"], rect1["width"], rect2["x_left"], rect2["width"]) y_overlap_start_pt , overlap_height = find_range_overlap(rect1["y_bottom"], rect1["height"], rect2["y_bottom"], rect2["height"]) # return null rectangle if there is no overlap if not overlap_width or not overlap_height: return { "x_left" : None, "y_bottom" : None, "width" : None, "height" : None } return { "x_left" : x_overlap_start_pt, "y_bottom" : y_overlap_start_pt, "width" : overlap_width, "height" : overlap_height } def find_range_overlap(point1, length1, point2, length2): """ find and return the overlapping start point and length""" highest_start_point = max(point1, point2) lowest_end_point = min(point1 + length1, point2 + length2) if highest_start_point >= lowest_end_point: return (None, None) overlap_length = lowest_end_point - highest_start_point return (highest_start_point, overlap_length) rect1 = { "x_left" : 1, "y_bottom" : 5, "width" : 10, "height" : 4 } rect2 = { "x_left" : 5, "y_bottom" : 7, "width" : 8, "height" : 6 } rect3 = { "x_left" : 11, "y_bottom" : 5, "width" : 2, "height" : 4 } print find_rectangular_overlap(rect1, rect2) # Expected answer # {'width': 6, 'y_bottom': 7, 'x_left': 5, 'height': 2} print find_rectangular_overlap(rect1, rect3) # Expected answer # {'width': None, 'y_bottom': None, 'x_left': None, 'height': None}
true
49421b3c6d6cd17108c8a9ef1c58130c2c531d3e
eshthakkar/coding_challenges
/kth_largest_from_sorted_subarrays.py
676
4.125
4
# O(k) time complexity and O(1) space complexity def kth_largest(list1,list2,k): """ Find the kth largest element from 2 sorted subarrays >>> print kth_largest([2, 5, 7, 8], [3, 5, 5, 6], 3) 6 """ i = len(list1) - 1 j = len(list2) - 1 count = 0 while count < k: if list1[i] > list2[j]: result = list1[i] i -= 1 else: result = list2[j] j -= 1 count += 1 return result if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "All tests passed. Good work!" print
true
2dfff17f70a01dcaf4d742352055b160fbc06669
jimibarra/cn_python_programming
/miniprojects/trip_cost_calculator.py
396
4.375
4
print("This script will calculate the cost of a trip") distance = int(input("Please type the distance to drive in kilometers: ")) usage = float(input("Please type the fuel usage of your car in liters/kilometer: ")) cost_per_liter = float(input("Please type the cost of a liter of fuel: ")) total_cost = cost_per_liter * usage * distance print(f'The total cost of your trip is {total_cost}.')
true
a9cfee9934cc75445451574cfc4878cb11d39f4d
jimibarra/cn_python_programming
/07_classes_objects_methods/07_02_shapes.py
1,539
4.625
5
''' Create two classes that model a rectangle and a circle. The rectangle class should be constructed by length and width while the circle class should be constructed by radius. Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle), perimeter (of the rectangle) and circumference of the circle. ''' import math class Rectangle: '''Class to model a rectangle ''' def __init__(self, length, width): self.length = length self.width = width def __str__(self): return f'Rectangle has length {self.length} and width {self.width}.' def area_rect(self): area_r = self.length * self.width return area_r def perim_rect(self): perim_r = (2 * self.length) + (2 * self.width) return perim_r class Circle: '''Class to model a circle''' def __init__(self, radius): self.radius = radius def __str__(self): return f'Circle has radius {self.radius}.' def area_circle(self): area_c = math.pi * (self.radius ** 2) return area_c def circum_circle(self): circum_c = 2 * math.pi * self.radius return circum_c my_rect = Rectangle(3, 4) my_circ = Circle(5) print(my_rect) print(my_circ) print (f'The area of the rectangle is {my_rect.area_rect()}.') print (f'The perimeter of the rectangle is {my_rect.perim_rect()}.') print (f'The area of the circle is {my_circ.area_circle()}.') print (f'The circumference of the circle is {my_circ.circum_circle()}.')
true
b1b191321e4f71bf57f4052aaa91cb01c8d60501
jimibarra/cn_python_programming
/07_classes_objects_methods/07_01_car.py
1,075
4.53125
5
''' Write a class to model a car. The class should: 1. Set the attributes model, year, and max_speed in the __init__() method. 2. Have a method that increases the max_speed of the car by 5 when called. 3. Have a method that prints the details of the car. Create at least two different objects of this Car class and demonstrate changing the objects attributes. ''' class Car: '''Class to model cars''' def __init__(self, model, year, max_speed=60): self.model = model self.year = year self.max_speed = max_speed def __str__(self): return f'The car is a {self.year} {self.model} with a max speed of {self.max_speed}.' def increment_max_speed(self): self.max_speed += 5 j_car = Car('BMW Z3', 1998) d_car1 = Car('BMW Z3', 2001) d_car2 = Car('Jaguar VP', 2005, 70) print(j_car) print(d_car1) print(d_car2) j_car.increment_max_speed() j_car.increment_max_speed() print(j_car) d_car2.increment_max_speed() d_car2.increment_max_speed() d_car2.increment_max_speed() print(d_car2) d_car2.year = 2008 print(d_car2)
true
8c1053a3d6092c244c89f36e11d60cc63b1d9090
jimibarra/cn_python_programming
/03_more_datatypes/2_lists/03_11_split.py
540
4.40625
4
''' Write a script that takes in a string from the user. Using the split() method, create a list of all the words in the string and print the word with the most occurrences. ''' user_string = input("Please enter a string: ") my_list = user_string.split(" ") print(my_list) my_dict = {} my_set = set(my_list) for item in my_set: count = 0 count = my_list.count(item) my_dict[item] = count max_count = max(my_dict, key=lambda x: my_dict.get(x)) print(f'The word {max_count} appears the most at {my_dict[max_count]} times')
true
900c1185f0af45dd797ce33c0e0ce11fb759a449
jimibarra/cn_python_programming
/02_basic_datatypes/2_strings/02_09_vowel.py
991
4.4375
4
''' Write a script that prints the total number of vowels that are used in a user-inputted string. CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel in the string and print a count for each of them? ''' #Total Vowel Count vowel = ['a', 'e', 'i', 'o', 'u'] string = input('Please enter a string of characters: ') count = 0 for i in string: if i in vowel: count = count + 1 print(f'The number of vowels in the string is {count}.') #Count of Each Vowel count_a = 0 count_e = 0 count_i = 0 count_o = 0 count_u = 0 for i in string: if i in vowel: if i == 'a': count_a = count_a + 1 elif i == 'e': count_e = count_e + 1 elif i == 'i': count_i = count_i + 1 elif i == 'o': count_o = count_o + 1 else: count_u = count_u + 1 print(f'Counts By Vowel - a:{count_a}, e:{count_e}, i:{count_i}, o:{count_o}, u:{count_u}')
true
1c551d5fdea25beebc8b9c566d17fc4c23a1c3b1
jimibarra/cn_python_programming
/04_conditionals_loops/04_10_squares.py
237
4.34375
4
''' Write a script that prints out all the squares of numbers from 1- 50 Use a for loop that demonstrates the use of the range function. ''' for num in range(1,51): square = num ** 2 print(f'The square of {num} is {square} ')
true
6bfee747928fa37a7cbcf03d73fd118133f6c930
jimibarra/cn_python_programming
/01_python_fundamentals/01_07_area_perimeter.py
277
4.1875
4
''' Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4. ''' area = 6.4 * 2.4 perimeter = 2 * (6.4 + 2.4) print(f"The area of the rectangle is {area}") print(f"The perimeter of the rectangle is {perimeter}")
true
f884581a74b2fa33ba0754284fac126e5e7e9bd6
namnamgit/pythonProjects
/emprestimo_bancario.py
949
4.125
4
# rodrigo, may0313 # escreva um programa para aprovar o empréstimo bancário para compra de uma casa. # o programa deve perguntar o valor da casa a comprar, o salário e a quantidade de anos a pagar. # o valor da presta;ão mensal não pode ser superior a 30% do salário. # calcule o valor da presta;ão como sendo o valor da casa a comprar dividido pelo número de meses a pagar. print('[APROVACAO DE EMPRESTIMO]\n') valor_casa = float(input('Valor da casa: ')) salario_cliente = float(input('Salário do cliente: ')) qtd_anos = int(input('Quantidade de anos a pagar: ')) qtd_meses = qtd_anos * 12 prest_mensal = valor_casa / qtd_meses test_emprestimo = salario_cliente * 30 / 100 if prest_mensal < test_emprestimo: print('Valor da casa: %.2f / Prestacao mensal: %.2f\nEmpréstimo aprovado.' % (valor_casa, prest_mensal)) else: print('Valor da casa: %.2f / Prestacao mensal: %.2f\nEmpréstimo negado.' % (valor_casa, prest_mensal)) input()
false
d8dfdd0ab64c2408a82be5fcbbd1b37fddbe0fee
namnamgit/pythonProjects
/maior_e_menor_numero.py
810
4.125
4
# rodrigo, apr1013 # escreva um programa que leia três números e que imprima o maior e o menor while True: numero1 = int(input('Digite o primeiro número: ')) numero2 = int(input('Digite o segundo número: ')) numero3 = int(input('Digite o terceiro número: ')) if numero1 > numero2 and numero1 > numero3: print('%d é o maior número.' % numero1) if numero2 > numero1 and numero2 > numero3: print('%d é o maior número.' % numero2) if numero3 > numero1 and numero3 > numero2: print('%d é o maior número.' % numero3) if numero1 < numero2 and numero1 < numero3: print('%d é o menor número.\n' % numero1) if numero2 < numero1 and numero2 < numero3: print('%d é o menor número.\n' % numero2) if numero3 < numero1 and numero3 < numero2: print('%d é o menor número.\n' % numero3)
false
d0e9358885e01dee964f826d9302180cb7d3ab90
AmyShackles/LearnPython3TheHardWay
/ex7.py
1,396
4.28125
4
# prints the string 'Mary had a little lamb' print("Mary had a little lamb.") # prints 'Its fleece was white as snow', the {} indicated replacement and 'snow' was the replacement text print("Its fleece was white as {}.".format('snow')) # prints 'And everywhere that Mary went' print("And everywhere that Mary went.") # prints 10 periods print("." * 10) # what'd that do? # assigns letter 'C' to variable end1 end1 = "C" # assigns letter 'h' to variable end2 end2 = "h" # assigns letter 'e' to variable end3 end3 = "e" # assigns letter 'e' to variable end4 end4 = "e" # assigns letter 's' to variable end5 end5 = "s" # assigns letter 'e' to variable end6 end6 = "e" # assigns letter 'B' to variable end7 end7 = "B" # assigns letter 'u' to variable end8 end8 = "u" # assigns letter 'r' to variable end9 end9 = "r" # assigns letter 'g' to variable end10 end10 = "g" # assigns letter 'e' to variable end11 end11 = "e" # assigns letter 'r' to variable end12 end12 = "r" # prints end1 plus end2 plus end3 plus end4 plus end5 plus end6 # with end=' ' at the end, it prints 'Cheese Burger' to screen # without end=' ' at the end, it prints 'Cheese\nBurger' to screen # end is an argument of print and by default equals new line print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # prints end7 plus end8 plus end9 plus end10 plus end11 plus end12 print(end7 + end8 + end9 + end10 + end11 + end12)
true
7d9600f2d3b44ba69232a20d4586c61dc48fb8b6
shkyler/gmit-cta-problems
/G00364753/Q2d.py
957
4.375
4
# Patrick Moore 2019-03-05 # This is a script to create a function that finds the max value in a list # using an iterative approach, as directed by Question 2(d) of the # Computational Thinking with Algorithms problem sheet # define a function that takes a list as an argument def max_iter(data): # set the maximum value to be the first item in the list maximum = data[0] # create a counter variable for the while loop counter = 0 # use a while loop to iterate over the length of the list while counter < len(data): # check if any item in the list is greater than the current maximum if data[counter] > maximum: # if so, set maximum to that value maximum = data[counter] # increment the counter counter = counter + 1 # once the while loop terminates, return the max value return maximum # create a variable to store the data list y = [0, -247, 341, 1001, 741, 22] # call the finder # function print(max_iter(y))
true
9d6e2e6e6d8c55965fe4206b140c78b2ee145772
michaelobr/gamble
/Gamble.py
1,667
4.3125
4
#Short introduction of the purpose of this program print("This short little program will help determine the probability of profitability and ROI from playing 50/50 raffles.") #The number of tickets the user will purchase num_user_tickets = int(input("How many tickets will you purchase? ")) #The total amount of tickets sold to everybody participating in the 50/50 raffle, this includes the user's. sum_tickets_sold = int(input("How many tickets in total are expected to be purchased? ")) #Parentheses must be used here, because multiplication comes before divsion in the order of operations which Python adheres to. winning_probability = (num_user_tickets / sum_tickets_sold) * 100 ticket_price = int(input("What is the price per 50/50 ticket? ")) #Only 50% of the total ticket sales is available to win, so we must divide by 2 here possible_winnings = (sum_tickets_sold * ticket_price) / 2 #profit = revenue - cost. If the number is negative, then it is a loss, but the same formula is still used. profit = possible_winnings - (num_user_tickets * ticket_price) #Return on Investment = profit (or loss) from investment / cost of investment ROI = ((profit) / (num_user_tickets * ticket_price)) * 100 #No " " is needed after "purchase," num_user_tickets, etc. because Python automatically includes a space. print("If you purchase", num_user_tickets, "ticket(s) at a price per ticket of $", ticket_price, "for a total of $", (num_user_tickets * ticket_price), "you have a", (winning_probability), "% of winning $", possible_winnings, ".") print("This would result in a profit of $", profit, "and a ROI of", ROI, "%.")
true
bca2eb0df154973cc48900b3493b812846429288
Izabela17/Programming
/max_int.py
727
4.25
4
"""If users enters x number of positive integers. Program goes through those integers and finds the maximum positive and updates the code. If a negative integer is inputed the progam stops the execution """ """ num_int = int(input("Input a number: ")) # Do not change this line max_int = num_int while num_int >= 0: if num_int > max_int: max_int = num_int num_int = int(input("Input a number: ")) print ("The maximum is", max_int) """ n = int(input("Enter the length of the sequence: ")) # Do not change this line num1 = 0 num2 = 0 num3 = 1 i = 1 for i in range(n): temp3 = num3 num3 = num1 + num2 + num3 if i > 1: num1 = num2 num2 = temp3 print(num3)
true
62f9cca5ef39e633b5a20ffd6afb27772a5291fc
NikolaosPanagiotopoulos/python-examples-1
/Addition.py
225
4.21875
4
#this program adds two numbers num1=input('Enter first number: ') num2=input('Enter second number: ') #Add two numbers sum=float(num1)+float(num2) #display the sum print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
true
14765ce398a35e4730122fb867cd45d386d19c7f
allysonvasquez/Python-Projects
/2-Automating Tasks/PhoneAndEmail.py
852
4.15625
4
# author: Allyson Vasquez # version: May.15.2020 # Practice Exercises: Regular Expressions # https://www.w3resource.com/python-exercises/re/index.php import re # TODO: check that a string contains only a certain set of characters(a-z, A-Z and 0-9) charRegex = re.compile(r'\d') test_str = str('My name is Allyson and I am 20 years old') # TODO: match a string that contains only upper and lowercase letters, numbers, and underscores # TODO: remove leading zeros from an IP address # TODO: convert a date from yyyy-mm-dd to mm-dd-yyyy # TODO: separate and print the numbers of a given string # TODO: abbreviate Road as Rd. in a home address # TODO: replace all spaces with a - # TODO: find all words that are 5 characters long in a string # TODO: extract values between quotation marks in a string # TODO: remove all the .com from a list of websites
true
c36172a0a429a3b3fb4a47464f7516ea21f3aac3
OscarDani/EjerciciosUnidad3
/03 Creational Patterns/AbstractFactory.py
1,684
4.15625
4
# AbstractFactory.py class Dog: """A simple dog class""" def speak(self): return "Woof!" def __str__(self): return "Dog" class Cat: """A simple cat class""" def speak(self): return "Maow!" def __str__(self): return "Cat" class CatFactory: """Concrete Factory""" def get_pet(self): """Return a Cat object""" return Cat() def get_food(self): """Return a Cat food objetc""" return "Fishes" class DogFactory: """Concrete Factory""" def get_pet(self): """Return a Dog object""" return Dog() def get_food(self): """Return a Dog food objetc""" return "Chiken" class PetStore: """PetStore houses our Abstract Factory""" def __init__(self, pet_factory = None): """pet_factoy ia our Abstract Factory""" self._pet_factory = pet_factory def show_pet(self): """Utility method to display the details of the objects by the factory""" pet = self._pet_factory.get_pet() pet_food = self._pet_factory.get_food() print("Our pet is '{}'".format(pet)) print("Our pet say hello by '{}'".format(pet.speak())) print("Its food is'{}'".format(pet_food)) def set_factory(self, pet_factory): self._pet_factory = pet_factory #Create a concrete factory factory = DogFactory() #Create a pet store housing our abstract factory shop = PetStore(factory) shop.show_pet() #Create a Cat factory cat_factory = CatFactory() shop.set_factory(cat_factory) shop.show_pet()
false
a9842c9896f227bb707b36906ec06f6fe93c0fc2
talrab/python_excercises
/fibonacci.py
707
4.3125
4
run_loop = True num_elements = int(input("Please enter the number of elements: ")) if num_elements < 0: run_loop = False while (run_loop): answer = [] for x in range(num_elements): print( "X=" + str(x)) if (x+1==1): answer.append(1) elif (x+1==2): answer.append(1) else: answer.append (answer[x-2] + answer[x-1]) print (answer) num_elements = int(input("Please enter the number of elements: ")) if num_elements < 0: run_loop = False # a 'classier' solution to find the nth element of fibonacchi: def fib(n): a,b = 0,1 for i in range(n): a,b = b,b+a return a print(fib(5))
true
5ecc9a206a36401a31124acf585a4a121a98291b
Pectin-eng/Lesson-6-Python
/lesson_6_task_4.py
2,301
4.3125
4
print('Задача 4.') # Пользователь вводит атрибуты всего класса: class Car: speed = int(input('Введите вашу скорость: ')) color = input('Введите цвет машины: ') name = input('Введите марку машины: ') is_police = input('У вас полицейская машина? да/нет ') def go(self, color, name): print(f'{color} {name} поехала.') def show_speed(self, speed): print(f'Скорость {speed}') def turn(self, color, name, turn): turn = input('Куда будем поворачивать? ') print(f'{color} {name} повернула {turn}.') def stop(self, color, name): print(f'{color} {name} остановилась.') class TownCar(Car): def show_speed(self, speed): if speed > 60: print('Скорость превышена.') else: print(f'Скорость {speed}') class SportCar(Car): def go(self, color, name): print(f'{color} {name} поехала.') class WorkCar(Car): def show_speed(self, speed): if speed > 40: print('Скорость превышена.') else: pass class PoliceCar(Car): def police(self, is_police): if is_police == 'да': print('Вы полицейский.') else: print('Вы не полицейский.') # В консоль по очереди выводятся экземпляры каждого подкласса: car = Car() town_car = TownCar() town_car.go(car.color, car.name) town_car.show_speed(car.speed) town_car.turn(car.color, car.name, car.turn) town_car.stop(car.color, car.name) sport_car = SportCar() sport_car.go(car.color, car.name) sport_car.show_speed(car.speed) sport_car.turn(car.color, car.name, car.turn) sport_car.stop(car.color, car.name) work_car = WorkCar() work_car.go(car.color, car.name) work_car.show_speed(car.speed) work_car.turn(car.color, car.name, car.turn) work_car.stop(car.color, car.name) police_car = PoliceCar() police_car.go(car.color, car.name) police_car.show_speed(car.speed) police_car.turn(car.color, car.name, car.turn) police_car.stop(car.color, car.name)
false
51a4bcb49223b93ebc60b0cce21f4cbde2c5b8da
yankwong/python_quiz_3
/question_1.py
506
4.25
4
# create a list of number from 1 to 10 one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # using list comprehension, generate a new list with only even numbers even_from_one_to_ten = [num for num in one_to_ten if (num % 2 == 0)] # using list comprehension, generate a new list with only odd numbers odd_from_one_to_ten = [num for num in one_to_ten if (num % 2 == 1)] # print out the sum of all even numbers print(sum(even_from_one_to_ten)) # print out the sum of all odd numbers print(sum(odd_from_one_to_ten))
true
421ce0dabf326248c65348bd3506e5596570730a
pnthairu/module7_Arrays
/sort_and_search_array.py
2,039
4.3125
4
from array import array as arr from filecmp import cmp # Start Program """ Program: sort_and_Search_array.py Author: Paul Thairu Last date modified: 06/23/2020 You can make a new files test_sort_and_search_array.py and sort_and_search_array.py. In the appropriate directories. For this assignment, you can hard-code a list you pass to the sort_array() and search_array(). Eventually write 2 functions sort_array() and search_array(). search_array() will return the index of the object in the list or a -1 if the item is not found sort_array() will sort the list """ # declaring getList function and with array list parameter def get_array(arr): print(arr) # print the list of items # Declaring searchList function with array list and subject to search parameters def search_array(arr, subject): print("****************************************************") print(subject) # element to search on th list for i in arr: # looping through the list to find an element if (i == subject): # if car is not in the list break break if subject in arr: pass else: return -1 # returning a value that does not exit in the array def sort_array(arr): arr.sort() # in build sort function to sort subject in alphabetical order print("Subjects in alphabetical order") print(arr) # Print list of subjects in order if __name__ == '__main__': arr = ['Maths', 'English', 'Biology', 'Chemistry', 'Physics'] # my hard coded array list subject = "French" # car to search subject in the array list get_array(arr) # function call and assigning to array of subjects if (search_array(arr, subject) == -1): # If subject not found print(subject + " 'Does not exit in the ARRAY !!!!!!!'") else: # if subject is found print(subject + " FOUND in the subject array..") print("****************************************************") sort_array(arr) # sorting list in alphabetical order
true
0d7b86cad05e0a7391f3eb150175446a58f20c6b
ratneshgujarathi/Encryptor-GUI-
/encrypt_try.py
1,299
4.4375
4
#ceasor cipher method encryption #this is trial module to easy encrypyt the message #c=(x-n)%26 we are ging to follow this equation for encrytion #c is encryted text x is the char n is the shifting key that should be in numbers % is modulus 26 is total alphabets #function for encrytion def encryption(string,shift): cipher='' for char in string: if char=='': cipher=cipher+char elif char.isupper(): cipher=cipher+chr((ord(char)+shift-65)%26+65) else: cipher=cipher+chr((ord(char)+shift-97)%26+97) return cipher def decryption(string,shift): cipher1='' for char in string: if char=='': cipher1=cipher1+char elif char.isupper(): cipher1=cipher1+chr((ord(char)-shift-65)%26+65) else: cipher1=cipher1+chr((ord(char)-shift-97)%26+97) return cipher1 ascii_text='' text=input("Enter your text here ") for i in text: ascii_text=ascii_text+int(i) print(ascii_text) s=int(input("enter the desired shifting key ")) print("the original text was ",text) print("the encrypted message is ",encryption(text,s)) en=encryption(text,s) print("The encrypted message is ",en) print("decrypted message is ",decryption(en,s))
true
a7ca5c75d43d8fbdb082f89d549b1db9959e101a
praveendareddy21/ProjectEulerSolutions
/src/project_euler/problem4/problem4.py
2,395
4.21875
4
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. Created on Feb 18, 2012 @author: aparkin ''' from project_euler.timing import timeruns, format_runs def ispalindrome(num): ''' Simple predicate to test if num is a palindromic number. @return: true if num is a palindrome, false otherwise ''' str_num = str(num) return str_num == (str_num[::-1]) def prob4(numdigits=3): ''' 1st attempt to solve problem 4, pretty much brute force. @param numdigits: how many digits should the two factors have. @type numdigits: int @return: a 3-tuple (factor1, factor2, num) such that num is the largest palindrome that is a product of two numdigits numbers: factor1 and factor2 @rtype: (int, int, int) ''' biggest = 10**numdigits-1 smallest = 10**(numdigits-1) palindromes = {} # loop over all possible 3 digit factors, taking advantage of the # commutivity of multiplication (ie 3 x 4 == 4 x 3) for num1 in range(biggest, smallest, -1): for num2 in range(num1, smallest, -1): if ispalindrome(num1 * num2): palindromes[num1*num2] = (num1, num2, num1 * num2) return palindromes[sorted(palindromes, reverse=True)[0]] def prob4v2(numdigits=3): ''' Same as v1, but using a dict comprehension to see if the move from nested for loop to nested dict comprehension would be faster ''' biggest = 10**numdigits-1 smallest = 10**(numdigits-1)-1 palindromes = {i * j : (i, j, i * j) for i in range(biggest, smallest, -1) for j in range(i, smallest, -1) if ispalindrome(i * j)} return palindromes[sorted(palindromes, reverse=True)[0]] def main(): print prob4(3) print prob4v2(3) # time different approaches setup = """ from project_euler.problem4.problem4 import prob4, prob4v2 """ runs = [("""prob4(3)""", setup, "Nested For Loop"), ("""prob4v2(3)""", setup, "Dict comprehension"), ] num_iterations = 100 print format_runs(timeruns(runs, num_iterations)) if __name__ == "__main__": main()
true
1ff64de9934c840e397cc2a3b07690cae8566481
Diksha-11/OOPM-C-Notes
/python all sheets (Saurabh Shukla)/python ass 2/ass2.7.py
485
4.1875
4
print("Form of Quadratic Equation is :- ax^2+bx+c") a=int(input("Enter 'a' of an quadratic question: ")) b=int(input("Enter 'b' of an quadratic question: ")) c=int(input("Enter 'c' of an quadratic question: ")) D=(b*b)-(4*a*c) if (D<0): print("Nature is unequal and imaginary") elif(D==0): print("Nature is equal and real") elif(D>0): print("Nature is unequal real and rational") else: print("Enter a valid equation") input("Enter any key to exit")
false
eea1a67f02c852cd6ca7b2997c9bb7ffdff4e7ba
coomanky/game-v1
/main.py
2,848
4.3125
4
#user information print("hello and welcome to (game v2) , in this game you will be answering a series of questions to help inprove your knowledge of global warming ") print (" ") name = input ("What is your name? ") print ("Hello " + name) print(" ") # tutorial def yes_no(question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response == "n": response = "no" return response else: print("Please answer yes / no") show_instructions = yes_no("Have you played the " "game before? ") print("You chose {}".format(show_instructions)) # rounds start rounds_played = 0 play_again = input("Press <Enter> to play...").lower() def new_game(): guesses = [] correct_guesses = 0 question_num = 1 for key in questions: print("-------------------------") print(key) for i in options[question_num-1]: print(i) guess = input("Enter (A, B, C, or D): ") guess = guess.upper() guesses.append(guess) correct_guesses += check_answer(questions.get(key), guess) question_num += 1 display_score(correct_guesses, guesses) # ------------------------- def check_answer(answer, guess): if answer == guess: print("CORRECT!") return 1 else: print("WRONG!") return 0 # ------------------------- def display_score(correct_guesses, guesses): print("-------------------------") print("RESULTS") print("-------------------------") print("Answers: ", end="") for i in questions: print(questions.get(i), end=" ") print() print("Guesses: ", end="") for i in guesses: print(i, end=" ") print() score = int((correct_guesses/len(questions))*100) print("Your score is: "+str(score)+"%") # ------------------------- def play_again(): response = input("Do you want to play again? (yes or no): ") response = response.upper() if response == "YES": return True else: return False # ------------------------- questions = { "is the ice melting in the artic?: ": "A", "why is the ice melting in the artic?: ": "B", "is it effecting the animals that live there?: ": "C", "are there any ways we could fix this issue?: ": "A" } options = [["A. yes", "B. no", "C. maybe", "D. sometimes"], ["A. because of trees", "B. because of humans", "C. because of sharks", "D. because of penguins"], ["A. no", "B. sometimes", "C. yes", "D. only on weekends"], ["A. yes","B. no", "C. sometimes", "D. maybe"]] new_game() while play_again(): new_game() # completed game
true
52dad76686a481f7218cc435f240c3086897bc37
DesignisOrion/DIO-Tkinter-Notes
/grid.py
467
4.40625
4
from tkinter import * root = Tk() # Creating Labels label1 = Label(root, text="Firstname") label2 = Label(root, text="Lastname") # Creating Text fields entry1 = Entry(root) entry2 = Entry(root) # Arrange in the grid format label1.grid(row=0, column=0) label2.grid(row=1, column=0) # Want to have the labels place in front of the entry level respectively.add() entry1.grid(row=0, column=1) entry2.grid(row=1, column=1) root.mainloop()
true
fa5cdbad427a59b56aedf23a00a36b3dfc8dee2e
hubbm-bbm101/lab5-exercise-solution-b2200765016
/Exercise 1.py
307
4.21875
4
number = int(input("Welcome, enter a number: " )) sum = 0 if number % 2 == 0 : for i in range(1, number + 1): sum = sum +i print("the sum is: ", sum) else: for i in range(1, number + 1, 2): sum = sum +i average = sum / number print("The average is: ", average)
false
39d2367ba2910304e1e50724783ffbd3ece60b0f
divyakelaskar/Guess-the-number
/Guess the number .py
1,862
4.25
4
import random while True: print("\nN U M B E R G U E S S I N G G A M E") print("\nYou have 10 chances to guess the number.") # randint function to generate the random number between 1 to 100 number = random.randint(1, 100) """ number of chances to be given to the user to guess the number or it is the inputs given by user into input box here number of chances are 10 """ chances = 0 print("Guess a number (1 - 100):") # While loop to count the number of chances while chances < 10: # Enter a number between 1 to 100 guess = int(input()) # Compare the user entered number with the number to be guessed if guess == number: """ if number entered by user is same as the generated number by randint function then break from loop using loop control statement "break" """ print("Congratulation YOU WON!!!") break # Check if the user entered number is smaller than the generated number elif guess < number: print("Your guess was too low: Guess a number higher than", guess) # The user entered number is greater than the generated number else: print("Your guess was too high: Guess a number lower than", guess) # Increase the value of chance by 1 as 1 chance is used chances += 1 # Check whether the user guessed the correct number if not chances < 10: print("YOU LOSE!!! The number is", number) ans=input("Do you want to play again (y/n) : ") if ans != 'y' : break print("\n T H A N K S F O R P L A Y I N G ! ! ! ! !\n")
true
356ad2bf5d602c408dd3c44c2e475c5a8379da0a
emorycs130r/Spring-2021
/class_8/lists_intro.py
454
4.25
4
fruits = ['Apple', 'Strawberry', 'Orange'] # Index = Position - 1 # print(fruits[3]) print(type(fruits)) vegetables = [] print(f"Before adding value: {vegetables}") vegetables.append('Brocolli') print(f"After adding value: {vegetables}") # print(vegetables) fruits.append('Kiwi') print(f"Fruits are: {fruits}") fruits.insert(2, 'Raspberry') print(f"Updated fruit list: {fruits}") fruits.remove('Apple') print(f"Updated fruit list 2: {fruits}")
true
9af404e0faeff67ace5589e05ecb3fdc9c680104
emorycs130r/Spring-2021
/class_6/temperature_conversion.py
662
4.40625
4
''' Step 1: Write 2 functions that converts celsius to farenheit, celsius to kelvin. Step 2: Get an input from user for the celsius value, and f/k for the value to convert it to. Step 3: Based on the input call the right function. ''' def c_to_f(temp): return (9/5) * temp + 32 def c_to_k(temp): return temp + 273.15 if __name__ == "__main__": function = input("Which conversion? (F or K) ") temp = float(input("Enter a temperature in Celsius: ")) if function == "F" or function == "f": print(c_to_f(temp)) elif function == "K" or function == "k": print(c_to_k(temp)) else: print("Invalid conversion")
true
90653fca5369a36f393db2f49b30322080d0a944
emorycs130r/Spring-2021
/class_11/pop_quiz_1.py
458
4.1875
4
''' Create a dictionary from the following list of students with grade: bob - A alice - B+ luke - B eric - C Get input of name from user using the "input()" and use it to display grade. If the name isn't present, display "Student not found" ''' def working_numbers_set(input_list): return list(dict.fromkeys(input_list)) if __name__ == "__main__": input_list = [2,2,3,5,6,8,7,6,2] result = working_numbers_set(input_list) print(result)
true
c0cb66d637c94a99eb4255c5991a2fcc0aae122c
vparjunmohan/Python
/Basics-Part-II/program30.py
513
4.125
4
'''Write a Python program to reverse the digits of a given number and add it to the original, If the sum is not a palindrome repeat this procedure. Note: A palindrome is a word, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar.''' def rev_number(n): while True: k = str(n) if k == k[::-1]: break else: m = int(k[::-1]) n += m return n print(rev_number(1234)) print(rev_number(1473))
true
6da942919c4afcaf3e6a219f42c642b4a34761c3
vparjunmohan/Python
/Basics-Part-I/program19.py
334
4.40625
4
'Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.' str = input('Enter a string ') if str[:2] != 'Is': newstr = 'Is' + str print('New string is',newstr) else: print('String unchanged',str)
true
a73d72582cc340a3c517b4f5ecde7a396175b7cc
vparjunmohan/Python
/Basics-Part-I/program150.py
241
4.1875
4
'Python Program for sum of squares of first n natural numbers.' def squaresum() : sm = 0 for i in range(1, n+1): sm = sm + (i * i) return sm n = int(input('Enter a number ')) print('Sum of squares is',squaresum())
true
55e157e4a5c65734f28ef1a72c3c987732ca8ebc
vparjunmohan/Python
/Basics-Part-I/program7.py
375
4.46875
4
''' Write a Python program to accept a filename from the user and print the extension of that. Sample filename : abc.java Output : java''' filename = input('Enter file name: ') extension = filename.split('.') #split() method returns a list of strings after breaking the given string by the specified separator. print('Extension of the file',extension[0],'is',extension[1])
true
5ba74fcc46711f7c2ce61a3e700579dc8323f775
vparjunmohan/Python
/Basics-Part-I/program24.py
244
4.125
4
'Write a Python program to test whether a passed letter is a vowel or not.' def vowel(): if n in ['a','e','i','o','u']: print(n,'is a vowel') else: print(n,'is not a vowel') n = input('Enter a letter ') vowel()
false
b07684fbb0a42f18683a21a8fc4d08abe25c5712
vparjunmohan/Python
/String/program1.py
215
4.15625
4
'Write a Python program to calculate the length of a string.' def strlen(string): length = len(string) print('Length of {} is {}'.format(string, length)) string = input('Enter a string ') strlen(string)
true
b206558992aed8a4b4711787dff8f4933ad1d2ec
vparjunmohan/Python
/Basics-Part-II/program45.py
671
4.15625
4
'''Write a Python program to that reads a date (from 2016/1/1 to 2016/12/31) and prints the day of the date. Jan. 1, 2016, is Friday. Note that 2016 is a leap year. Input: Two integers m and d separated by a single space in a line, m ,d represent the month and the day. Input month and date (separated by a single space): 5 15 Name of the date: Sunday''' from datetime import date print('Input month and date (separated by a single space):') m, d = map(int, input().split()) weeks = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'} w = date.isoweekday(date(2016, m, d)) print('Name of the date: ', weeks[w])
true
26e6febc3d8ee93be39496e3c05ef6e62def8bac
mandeeppunia2020/python2020
/Day8.py
1,477
4.46875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: Intronduction to tuple datatype: # In[ ]: defination: an immutable list is called tuple: classfication: tuple is classified as an immutable datatype: how to define the tuple:------>() # In[1]: student=('mandeep','punia','muskan','ravi','rohit','prince') print(student) # In[2]: type(student) # In[ ]: Req: in muskan place i want to replace whith anu....! # In[3]: student[2]= 'anu' # in which if you declaried a tuple that means no one change it.....! # In[ ]: For Example: # In[4]: dimensions=(220,100) # In[6]: print(dimensions) # In[ ]: Req: i want to change 220 into 300..! # In[9]: dimensions[0]= 300 # hence once you create a tuple you not do any change in it...! # In[10]: print(dimensions) # In[ ]: # In[11]: print(student) # In[ ]: For loop in tuple: # In[13]: for x in student: print(x) # In[15]: for x in student: print(x.title()) # In[ ]: Introduction to Dictionary datatpe: # In[16]: defination: A dictionary is a combination odf key-value pairs. classification: it is classified as mutable datatype. how to define-----> {}#curley brackeys...! # In[ ]: Req: i want to create a alien game and add properties of it color and points...! # In[ ]: # In[17]: alien={'color':'green','points':5} print(alien) # In[18]: type(alien) # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
false
97cc5bf2f5ebc0790d157a8ad00a2006aa53ca64
AbhishekKunwar17/pythonexamples
/11 if_elif_else condition/unsolved02.py
236
4.21875
4
Write Python code that asks a user how many pizza slices they want. The pizzeria charges Rs 123.00 a slice if user order even number of slices, price per slice is Rs 120.00 Print the total price depending on how many slices user orders.
true
194a7d2d1d862cfda300d7e94bc7b8398af7be5b
icydee/python-examples
/fibonacci.py
1,151
4.1875
4
#!/usr/local/bin/python3 # Python 2.6 script to calculate fibonacci number # Raises exception if invalid input is given class fib_exception(Exception): pass def fib_recursive(input): n = int(input) if n <= 0 or n != input : raise fib_exception() elif n==1 : # first in series return 1 elif n==2 : # second in series return 1 else : # return sum of two previous return fib_recursive(n-2)+fib_recursive(n-1) fib_array = [0,1] def fib_dynamic(input): n = int(input) if n <= 0 or n != input: raise fib_exception() elif n == 0: return 0 elif n == 1: return 1 elif n<=len(fib_array): return fib_array[n-1] else: temp_fib = fib_dynamic(n-2)+fib_dynamic(n-1) fib_array.append(temp_fib) return temp_fib # optimise for size def fib_optimize(input): n = int(input) a = 0 b = 1 if n <= 0 or n != input: raise fib_exception() if n == 1: return b else: for i in range(2,n+1): c = a + b a = b b = c return c
false
1ac7a9e8d9ee10eeb8e571d3dd6e5698356a1a47
NitinSingh2020/Computational-Data-Science
/week3/fingerExc3.py
1,503
4.28125
4
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if len(L) == 0: return float('NaN') stdDev = 0 avgL = 0 lenList = [len(string) for string in L] for a in lenList: avgL += a avgL = avgL/float(len(L)) N = len(L) for string in L: stdDev += (len(string) - avgL)**2 return (stdDev/float(N))**0.5 L = ['a', 'z', 'p'] print stdDevOfLengths(L) # 0 L = ['apples', 'oranges', 'kiwis', 'pineapples'] print stdDevOfLengths(L) # 1.8708 # =============================================== def avg(L): """ L: a list of numbers returns: float, the average of the numbers in the list, or NaN if L is empty """ if len(L) == 0: return float('NaN') avgL = 0 for a in L: avgL += a avgL = avgL/float(len(L)) return avgL def stdDev(L): """ L: a list of numbers returns: float, the standard deviation of the numbers in the list, or NaN if L is empty """ if len(L) == 0: return float('NaN') stdDev = 0 avgL = avg(L) for a in L: stdDev += (a - avgL)**2 return (stdDev/float(len(L)))**0.5 def coeffOfVar(L): avgL = avg(L) stdDevL = stdDev(L) return stdDevL/float(avgL) print coeffOfVar([10, 4, 12, 15, 20, 5]) print coeffOfVar([1, 2, 3]) print coeffOfVar([11, 12, 13]) print coeffOfVar([0.1, 0.1, 0.1])
true
80d674fa13606ccecb4943feb34ea9878cf45cca
AutumnColeman/python_basics
/python-strings/caesar_cipher.py
688
4.5625
5
#Given a string, print the Caesar Cipher (or ROT13) of that string. Convert ! to ? and visa versa. string = raw_input("Please give a string to convert: ").lower() cipher_list = "nopqrstuvwxyzabcdefghijklm" alpha_list = "abcdefghijklmnopqrstuvwxyz" new_string = "" for letter in string: if letter == "m": new_string += "z" elif letter == " ": new_string += " " elif letter == "!": new_string += "?" elif letter == "?": new_string += "!" elif letter not in alpha_list: print "Invalid character" else: i = cipher_list.index(letter) new_letter = alpha_list[i] new_string += new_letter print new_string
true
3bac6dcded9f050f8c3d8aff2e2f9f5083310d00
nishesh19/CTCI
/educative/rotateLinkedList.py
1,146
4.1875
4
from __future__ import print_function class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(temp.value, end=" ") temp = temp.next print() def rotate(head, rotations): # TODO: Write your code here if (not head) or (not head.next) or rotations == 0: return head curr = head ll_len = 1 while curr.next: ll_len += 1 curr = curr.next jumps = rotations % ll_len curr = head while jumps > 1: curr = curr.next jumps -= 1 new_head = curr.next curr.next = None new_tail = new_head while new_tail.next: new_tail = new_tail.next new_tail.next = head head = new_head return head def main(): head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) print("Nodes of original LinkedList are: ", end='') head.print_list() result = rotate(head, 3) print("Nodes of rotated LinkedList are: ", end='') result.print_list() main()
true
9c091e4e3c4090e276eaad3b8ae15ea5e8fb6654
nishesh19/CTCI
/Arrays and Strings/Urlify.py
721
4.28125
4
# Write a method to replace all spaces in a string with '%20: You may assume that the string # has sufficient space at the end to hold the additional characters, and that you are given the "true" # length of the string. (Note: If implementing in Java, please use a character array so that you can # perform this operation in place.) # EXAMPLE # Input: "Mr John Smith "J 13 # Output: "Mr%20John%20Smith" #!/bin/python3 import math import os import random import re import sys def URLify(sentence): char_list = list(sentence.rstrip()) for i in range(len(char_list)): if char_list[i] == " ": char_list[i] = "%20" print(''.join(char_list)) if __name__ == '__main__': URLify(str(input()))
true
6e58c3d2c52524ae138b55a4d4dbaf57512d363b
nishesh19/CTCI
/LinkedList/deletemiddlenode.py
1,892
4.125
4
''' 2.3 Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. EXAMPLE Input: the node c from the linked list a->b->c->d->e->f Result: nothing is returned, but the new linked list looks like a->b->d->e->f ''' class Node: def __init__(self, value): self._next = None self._value = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value @property def next(self): return self._next @next.setter def next(self, next): self._next = next class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert(self, item): newNode = Node(item) if self.head == None: self.head = newNode if self.tail: self.tail.next = newNode self.tail = newNode def size(self): head = self.head length = 0 while head: length += 1 head = head.next return length def iterate(self): head = self.head print('\n') while head: print(head.value) head = head.next def delete(self,node): node.value = node.next.value node.next = node.next.next if __name__ == '__main__': nodes = input().split() no_of_nodes = int(nodes[0]) k = int(nodes[1]) sl = SinglyLinkedList() for i in range(no_of_nodes): sl.insert(int(input())) head = sl.head while k>0: head = head.next k -= 1 print(f'Node to delete : {head.value}') sl.delete(head) print('Updated list') sl.iterate()
true
e94f1f07150945766804cb28a1e831429bc880de
L0GI0/Python
/Codes/functions_with_lists.py
919
4.25
4
#!/usr/bin/python3 lucky_numbers = [32, 8, 15, 16, 23, 42] friends = ["Kevin", "Karen", "Jim", "Oscar", "Tom"] print(friends) #append another lists at the end of a list friends.extend(lucky_numbers) print(friends) #adding indivitual elements at the end of given list friends.append("Creed") #adding individual elements at the specific index friends.insert(1, "Kelly") #remobing specific element friends.remove("Jim") #removing whole list friends.clear() #poping an item from a list, getting rid of the last element friends.pop() #checking the existence of a element if it is on the list it give its index print(friends.index("Kevin")) #couting duplicates print(friends.count("Jim")) #sorting the list in alphabetical order friends.sort() print(friends) lucky_numbers.sort(); print(lucky_numbers) #reversing the list lucky_numbers.reverse() #copying a list, creates a copy of given list friends2 = friends.copy()
true
7255e858a67f1640b7f82972435b916b1dc4f301
L0GI0/Python
/Codes/if_statement_and_comparistion.py
245
4.3125
4
#!/usr/bin/python3 #comparison operators eg. >=, <. <=, ==, != def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print (max_num(3, 4, 5))
false
e4434cfa2ff0b2b53664dd678bb0d6c9490e8e67
ibnahmadCoded/how_to_think_like_a_computer_scientist_Chapter_5
/palindrom_checker.py
248
4.21875
4
def is_palindrome(word): """Reverses word given as argument""" new_word = "" step = len(word) + 1 count = 1 while step - count != 0: new_word += word[count * -1] count += 1 return new_word == word
true
0ff0a238da2e48a751d66401f303090375a03ed1
Sandbox4KidsTM/Python_Basics
/Supplemental_Material/PythonProjects/14. ALGEBRA/ALGEBRA/StringManipulation.py
733
4.125
4
# https://www.youtube.com/watch?v=k9TUPpGqYTo&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=2 # MATH FUNCTIONS in Python: https://docs.python.org/3.2/library/math.html #all key methods related to string manipulation message = "Hello World" print(message[0:3]) #including lower limit, but not including upper limit print(message.lower()) #prints lower case print(message.upper()) #prints uppoer case print(message.count('l')) #counts the number of occurances of substring 'l' print(message.find('World')) #prints index of first occurance of substring 'l' print(message.find('bobo')) #prints -1, if substring is not found print(message.casefold()) message = message.replace('World', 'Universe') print(message)
true
111a4db76992a35f4590e21b69684d8f7d057b94
SherMM/programming-interview-questions
/epi/sorting/selection_sort.py
812
4.21875
4
import sys import random def selection_sort(array): """ docstring """ def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] for i in range(len(array)): min_value = array[i] min_index = i for j in range(i+1, len(array)): value = array[j] if value < min_value: min_value = value min_index = j swap(array, i, min_index) if __name__ == "__main__": n = int(sys.argv[1]) array = [] for _ in range(n): array.append(random.randrange(151)) print("orginal array") print(array) correct_answer = sorted(array) selection_sort(array) print() print() print("sorted array") print(array) print("sort is correct: {}".format(correct_answer == array))
false
fa987c3d6e2c2e1dba192beee4cb430cb9d265ce
DZGoldman/Google-Foo-Bar
/problem22.py
2,284
4.40625
4
# things that are true: """ Peculiar balance ================ Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit population is at stake, so Beta reads the challenge: There is a scale with an object on the left-hand side, whose mass is given in some number of units. Predictably, the task is to balance the two sides. But there is a catch: You only have this peculiar weight set, having masses 1, 3, 9, 27, ... units. That is, one for each power of 3. Being a brilliant mathematician, Beta Rabbit quickly discovers that any number of units of mass can be balanced exactly using this set. To help Beta get into the room, write a method called answer(x), which outputs a list of strings representing where the weights should be placed, in order for the two sides to be balanced, assuming that weight on the left has mass x units. The first element of the output list should correspond to the 1-unit weight, the second element to the 3-unit weight, and so on. Each string is one of: "L" : put weight on left-hand side "R" : put weight on right-hand side "-" : do not use weight To ensure that the output is the smallest possible, the last element of the list must not be "-". x will always be a positive integer, no larger than 1000000000. """ def answer(x): # helper: converts int input to base-three string def toBase3(n): convertString = "012" return str(n) if n < 3 else toBase3(n // 3) + convertString[n % 3] # find max power of three such that power of 3 series is still less than x current_sum = 2 current_power = 0 while current_sum +3**(current_power+1) <= x: current_power += 1 current_sum += 3**current_power difference = x - current_sum # convert difference of x and 3-series to base 3 base_three = toBase3(difference) # prepend 0s to base 3 number while len(base_three) < current_power: base_three = '0'+base_three # convert number into instructions string instructions = 'R'+ base_three.replace('0', 'L').replace('1', '-').replace('2', 'R') return list(reversed(instructions)) print(answer(23))
true
3b0cf9d684b3b6c02b9fad9165f2df2904cdf20c
thomaswhyyou/python_examples
/indentation_behavior.py
298
4.53125
5
# Example 1. numbers = [1, 2, 3] letters = ["a", "b", "c"] print("\nExample 1:") for n in numbers: print(n) for l in letters: print(l) # Example 2. numbers = [1, 2, 3] letters = ["a", "b", "c"] print("\nExample 2:") for n in numbers: print(n) for l in letters: print(l)
false
dd37dfdb73c77dc4cbacd57bf754b6b9b6c131ac
LucienVen/python_learning
/algorithm/insertionSort.py
752
4.3125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 插入排序 def insertion_sort(list): for index in range(1, len(list)): current_value = list[index] position = index while position > 0 and list[position - 1] > current_value: print '比较项>>> list[position]: {} -- current_value: {}'.format(list[position - 1], current_value) list[position] = list[position - 1] position = position - 1 list[position] = current_value print "sorting list: {}".format(list) # def insertion_sort_binarysearch(list): # for index in range(1, len(list)) if __name__ == '__main__': test_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(test_list) print test_list
false
303dc61ab22c33d78817134b852e8f4826c0d97b
AneliyaPPetkova/Programming
/Python/2.StringsAndDataStructures/1.StringWith10Symbols.py
342
4.125
4
"""Напишете програма, която взима текст от потребителя използвайки input() и ограничава текста до 10 символа и добавя ... накрая """ stringInput = input() if len(stringInput) >= 10: print(stringInput[:10] + "...") else: print(stringInput)
false
79a7c011b0ed82c278939fef81f60c4be7c88320
ashutoshfolane/PreCourse_1
/Exercise_2.py
2,030
4.34375
4
# Exercise_2 : Implement Stack using Linked List. class Node: # Node of a Linked List def __init__(self, data=0, next=None): self.data = data self.next = next class Stack: def __init__(self): # Head is Null by default self.head = None # Check if stack is empty def isEmpty(self): if self.head == None: return True else: return False def push(self, data): if self.head is None: self.head = Node(data) else: newnode = Node(data) newnode.next = self.head self.head = newnode def pop(self): if self.isEmpty(): return None else: poppednode = self.head self.head = self.head.next poppednode.next = None return poppednode.data def peek(self): if self.isEmpty(): return None else: return self.head.data def show(self): headnode = self.head if self.isEmpty(): print("Stack is empty") else: while headnode is not None: print(headnode.data, "->", end=" ") headnode = headnode.next return # Driver code a_stack = Stack() while True: print('push <value>') print('pop') print('peek') print('show') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'peek': peek = a_stack.peek() if peek is None: print('Stack is empty') else: print('Peek value: ', int(peek)) elif operation == 'show': a_stack.show() elif operation == 'quit': break
true
3c0133cdc322e6dd514e693f319baa869857ee73
amandineldc/git
/exo python.py
1,340
4.25
4
#exo1 : Write a Python program to convert temperatures to and from celsius, fahrenheit. #[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ] print("---MENU---\n1) °C en °F\n2) °F en °C\nPour quitter tape 0") menu=int(input("Fais un choix :")) if menu == 1: C = int(input(print("Entre une température en °C : "))) F = (C*1.8)+32 print("ça équivaut à " + str(F)) print("---MENU---\n1) °C en °F\n2) °F en °C") menu = int(input("Fais un choix :")) elif menu == 2: F = int(input(print("Entre une température en °F : "))) C = (F - 32) / 1.8 print("ça équivaut à " + str(C)) print("---MENU---\n1) °C en °F\n2) °F en °C") menu = int(input("Fais un choix :")) elif menu == 0: print("EXIT") else: print("choisi 1 ou 2") menu = int(input("Fais un choix :")) #exo2 dic1 = {1: 10, 2: 20} dic2 = {3: 30, 4: 40} dic3 = {5: 50, 6: 60} dictot = {**dic1, **dic2, **dic3} print(dictot) #exo3 from datetime import datetime dt = datetime.now() print("current date and time :" + str(dt)) #exo4 color_list = input("Entre une liste : ") #color_list = ["Red", "Green", "White", "Black"] print("la première couleur est " + color_list[0] + ". La dernière couleur est " + color_list[-1]) #exo5
false
6686ad3efa4b2036988196c50b0ab6f56c1903f7
debajyoti-ghosh/Learn_Python_The_Hard_Way
/Exe8.py
527
4.125
4
formatter = "{} {} {} {}" #format can take int as argument print(formatter.format(1, 2, 3, 4)) #.format can take string as argument print(formatter.format('one', 'two', 'three', 'four')) #.format can take boolean as argument print(formatter.format(True, False, True, False)) #.format can take variable as argument print(formatter.format(formatter, formatter, formatter, formatter)) #.format can take line separated string as argument print(formatter.format( "Radio Mrich", "Sunle wale", "Always", "Khus" ))
true
72301ec7c64df86bd3500a01d59262d2037866dd
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/10_EvenFactors/Demo.py
411
4.125
4
''' Write a program which accept number from user and print even factors of that number Input : 24 Output: 2 4 6 8 12 ''' def PrintEvenFactors(no): if(no<0): no = -no; for i in range(2,int(no/2)+1): if(no%i == 0): print("{} ".format(i),end = " "); def main(): no = int(input("Enter number:")); PrintEvenFactors(no); if __name__ == "__main__": main();
true
408babae6f2e8b73ff56eaab659d421628c46cab
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/6 Problems on characters/2_CheckCapital/Demo.py
408
4.15625
4
''' Accept Character from user and check whether it is capital or not (A-Z). Input : F Output : TRUE Input : d Output : FALSE ''' def CheckCapital(ch): if((ch >= 'A') and (ch <= 'Z')): return True; else: return False; def main(): ch = input("Enter character:"); result = False; result = CheckCapital(ch); print(result); if __name__ == "__main__": main();
true
c3c59745e3de6f17d1f404221048e9ce92aed2e3
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/22_DisplayTable/Demo.py
348
4.125
4
''' Write a program which accept number from user and display its table. Input : 2 Output : 2 4 6 8 10 12 14 16 18 20 ''' def PrintTable(num): if(num == 0): return; for i in range(1,11): print(num*i,end = " "); def main(): no = int(input("Enter number: ")); PrintTable(no); if __name__ == "__main__": main();
true
f31b354b73c09c00f6c797bbefd5e89017b93fe2
Aditya-A-Pardeshi/Coding-Hands-On
/4 Python_Programs/1 Problems on numbers/3_Print_Numbers_ReverseOrder/Demo.py
356
4.15625
4
#Accept a positive number from user and print numbers starting from that number till 1 def DisplayNumbers(no1): if(no1 < 0): print("Number is not positive"); else: for i in range(no1,0,-1): print(i); def main(): no1 = int(input("Enter number: ")); DisplayNumbers(no1); if __name__ == "__main__": main();
true
c40119ce76ad55a08ee28a35e120940d643a2b49
DMSstudios/Introduction-to-python
/input.py
726
4.28125
4
#first_name = input('enter your first name: ') #second_name = input('enter your first name: ') #print( f'My name is:' first_name, second_name') #print(f"My name is,{first_name},{second_name}") #print("My name is {} {}" .format(first_name,second_name)) taskList = [23, "Jane", ["Lesson 23", 560, {"currency": "KES"}], 987, (76,"John")] """ Determing type of variable in taskList using an inbuilt function Print KES Print 560 Use a function to determine the length of taksList Change 987 to 789 without using an inbuilt -method (I.e Reverse) Change the name “John” to “Jane” . """ print(type(taskList)) print(taskList[2][2]['currency']) print(taskList[2][1]) print(len(taskList)) taskList[3]=789 print(taskList)
true
7a1ae6018cb2d4f2eba4296c4a1e928de77f9089
Watersilver/cs50
/workspace/pset6/mario/less/mario.py
390
4.125
4
# Draws hash steps from left to right. Last step is double as wide as others from cs50 import get_int # Gets height by user height = -1 while height < 0 or height > 23: height = get_int("Height: ") # Prints half pyramid # Iterate rows for i in range(height): # Iterate collumns for j in range(height + 1): print(" " if j < height - 1 - i else "#", end="") print()
true
78cc32c777d2be27d9a280fd1b8478b02d2d78d2
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_03/005.2-pizza-order-nested-conditional.py
1,149
4.25
4
# 🚨 Don't change the code below 👇 print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") add_pepperoni = input("Do you want pepperoni? Y or N ") extra_cheese = input("Do you want extra cheese? Y or N ") # 🚨 Don't change the code above 👆 # Write your code below this line 👇 # size and toppings inputs already established, now write the code # set the bill variable to 0 # recursion example from class notes - https://www.udemy.com/course/100-days-of-code/learn/lecture/17965124#content # start with conditional statement using elif not nested (nested is ok but longer) # then add a nested if / else statement for the pepperoni depending on size # then add a if statement for the cheese (just one option so no alternatives here) # your inputs must exactly match the capital cases or will end up with the wrong sum bill bill = 0 if size == 'S': bill += 15 elif size == 'M': bill += 20 else: bill += 25 if add_pepperoni == 'Y': if size == 'S': bill += 2 else: bill += 3 if extra_cheese == 'Y': bill += 1 print(f"your final bill is ${bill}")
true
70c1be0fa061a29d265589d2fc8390769d219330
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_03/001.flow-if-else-conditional.py
277
4.28125
4
print("Can you the rollercoaster!?") height = int(input("What is your height in cm? ")) ''' #pseudo code if condition: do this else: do this ''' if height >= 125: print("Get on board and ridet he rollercoaster!!!") else: print("sorry not good enough kid!")
true
a8d94cc1c75e67f5f965b11f2ae74973f4147c6a
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_04/04.1-day-4-2-exercise-solution.py
1,817
4.3125
4
# https://repl.it/@thakopian/day-4-2-exercise#main.py # write a program which will select a random name from a list of names # name selected will pay for everyone's bill # cannot use choice() function # inputs for the names - Angela, Ben, Jenny, Michael, Chloe # import modules import random # set varialbles for input and another to modify the input to divide strings by comma names_string = input("Give me everybody's names, separated by a comma. ") names = names_string.split(", ") # get name at index of list (example) print(names[0]) # you can also print len of the names to get their range print(len(names)) # set random module for the index values # > this is standard format > random.randint(0, x) # using the len as a substitute for x in the randint example with a variable set to len(names) num_items = len(names) # num_items - 1 in place of x to get the offset of the len length to match a starting 0 position on the index values # set the function to a variable choice = random.randint(0, num_items - 1) # assign the mutable name variable with an index of the choice variable to another variable for storing the index value of the name based on the index vaule person_who_pays = names[choice] # print that stored named variable out with a message print(person_who_pays + " is going to buy the meal today") ####### # This exercise isn't a practical application of random choice since it doesn't use the .choice() function # the idea is to replace variables, learn by retention and problem solve # create your own random choice function to understand how the code can facilitate that withouth the .choice() function # that way you learn how to go through problem challenges and how to create your own workaround in case the out of the box content isn't everything you need for a given problem
true
3c77f361ce4c9e5622fce0236a73fff1cfedd73b
thakopian/100-DAYS-OF-PYTHON-PROJECT
/BEGIN/DAY_04/03-lists.py
1,199
4.25
4
# list exercise replit https://repl.it/@thakopian/day-4-list-practice#main.py states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland", "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island", "Vermont", "Kentucky", "Tennessee", "Ohio", "Louisiana", "Indiana", "Mississippi", "Illinois", "Alabama", "Maine", "Missouri", "Arkansas", "Michigan", "Florida", "Texas", "Iowa", "Wisconsin", "California", "Minnesota", "Oregon", "Kansas", "West Virginia", "Nevada", "Nebraska", "Colorado", "North Dakota", "South Dakota", "Montana", "Washington", "Idaho", "Wyoming", "Utah", "Oklahoma", "New Mexico", "Arizona", "Alaska", "Hawaii"] # print any value from 0-49 index avilable in the 50 states list print(states_of_america[1]) # modify any value by choosing the index value and assigning it a new value states_of_america[1] = "PencilTown" # append a value to the end of the list states_of_america.append("ThunderDome") # extend the list with a new list states_of_america.extend(["LegoLand", "DisneyLand", "JurassicPark"]) # print the list with the new values print(states_of_america)
false
71ed0dcfdfe584e915b41a7bbbc197c3609d97e6
chupin10/KodeKonnectPyClass
/rockpaperscissors.py
812
4.125
4
import random computerchoice = random.randint(0, 2) if computerchoice == 0: computerchoice = 'rock' if computerchoice == 1: computerchoice = 'paper' if computerchoice == 2: computerchoice = 'scissors' print(computerchoice) yourchoice = input('Enter rock, paper, or scissors: ') if yourchoice == computerchoice: print("It's a tie! Try again.") if yourchoice == 'rock': if computerchoice == 'paper': print('You lose!') if computerchoice == 'scissors': print('You win!') if yourchoice == 'paper': if computerchoice == 'scissors': print('You lose!') if computerchoice == 'rock': print('You win!') if yourchoice == 'scissors': if computerchoice == 'rock': print('You lose!') if computerchoice == 'paper': print('You win!')
false
ae31c6cde30707ffccaf9bc0ed9eb70756f11514
xc13AK/python_sample
/week_v2.0.py
655
4.46875
4
#!/usr/bin/python3.4 #-*- coding:UTF-8 -*- import datetime #get the feature day from input year=int(input("enter the year:")) month=int(input("enter the month:")) day=int(input("enter the day:")) new=datetime.date(year,month,day) print("the day is %s-%s-%s"%(new.year,new.month,new.day)) weekday=int(new.weekday()) if weekday==0: print("it is MONDAY!") elif weekday==1: print("it is TUSDAY!") elif weekday==2: print("it is WENDAY!") elif weekday==3: print("it is THSDAY!") elif weekday==4: print("it is FRIDAY!") elif weekday==5: print("it is SARTDAY!") elif weekday==6: print("it is SUNDAY!") else: print("UNKNOWN")
true
586b29249cd0af8bad4d2622fca3846faa5626d1
RandomStudentA/cp1404_prac
/prac_05/hex_colours.py
446
4.34375
4
COLOR_TO_NAME = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "aquamarine1": "#7fffd4", "azure1": "#f0ffff", "beige": "#f5f5dc", "bisque1": " #ffe4c4", "black": "#000000"} color_name = input("Enter color name: ") while color_name != "": if color_name in COLOR_TO_NAME: print(color_name, "is", COLOR_TO_NAME[color_name]) else: print("Invalid color name") color_name = input("Enter color name: ")
false
3b105b43f202b9ca5f35fe8a65a3e5ce7ca4815c
RandomStudentA/cp1404_prac
/prac_04/lists_warmup.py
984
4.34375
4
numbers = [3, 1, 4, 1, 5, 9, 2] # What I thought it would print: 3 # What it printed: 3 print(numbers[0]) # What I thought it would print: 2 # What it printed: 2 print(numbers[-1]) # What I thought it would print: 1 # What it printed: 1 print(numbers[3]) # What I thought it would print: 2 # What it printed: [3, 1, 4, 1, 5, 9] print(numbers[:-1]) # What I thought it would print: 1, 5 # What it printed: 1 print(numbers[3:4]) # What I thought it would print: True # What it printed: True print(5 in numbers) # What I thought it would print: False # What it printed: False print(7 in numbers) # What I thought it would print: False # What it printed: 0 print("3" in numbers) # What I thought it would print: 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 # What it printed: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] print(numbers + [6, 5, 3]) # Question 1 numbers[0] = "ten" print(numbers) # Question 2 numbers[-1] = 1 print(numbers) # Question 3 print(numbers[2:7]) # Question 4 print(9 in numbers)
true
c67eee77631f9ef0d3a325eadeaab4039f3d8b1b
Systematiik/Python-The-Hard-Way
/ex15_1.py
429
4.21875
4
# reading textfiles by user input # open() opens file when in same directory # read() reads file from sys import argv # takes argument and puts under variable txt and function open, opens filename filename = input("Give me a text file to read (.txt): ") txt = open(filename) print(f"Here's your file {filename}: ") print(txt.read()) # prints contents of file into terminal txt.close() # closes file after reading
true
ad8927d675907b661391b785026adaae2f33d3bd
Systematiik/Python-The-Hard-Way
/ex15.py
702
4.15625
4
#reading textfiles by passing args and user input #open() opens file when in same directory #read() reads file from sys import argv script, filename = argv #takes argument and puts under variable txt and function open, opens filename txt = open(filename) print(f"Here's your file {filename}: ") print(txt.read()) #prints contents of file into terminal txt.close() print("Type the filename again: ") file_again = input("> ") #asks for the name of the file again #sets the file_again as a parameter for the open function in the variable txt_again txt_again = open(file_again) #reads and prints the file txt_again into terminal print(txt_again.read()) txt_again.close()
true
ea77221764e592bae48f42e9a6b5d512744f505c
Systematiik/Python-The-Hard-Way
/ex29.py
654
4.1875
4
people = 20 cats = 30 dogs = 15 #20 < 30 #print if people < cats: print("Too many cats! The world is doomed!") #20 !> 30 #no print if people > cats: print("Not many cats! The world is saved!") #20 !< 15 #no print if people < dogs: print("The world is drooled on!") #20 > 15 #print if people > dogs: print("The world is dry!") #dogs now equals 20 #dogs == people #all statements below print dogs += 5 if people >= dogs: print("People are greater than or equal to dogs.") if people <= dogs: print("People are less than or equal to dogs.") if people == dogs: print("People are dogs.")
false
107b0bb56f9a83d4f3ef6bb8c0d218b85757c96f
tranxuanduc1501/Homework-16-7-2019
/Bài 4 ngày 16-7-2019.py
704
4.25
4
a= float(input("Input a to solve equation: ax^2+bx+c=0 ")) b= float(input("Input b to solve equation: ax^2+bx+c=0 ")) c= float(input("Input c to solve equation: ax^2+bx+c=0 ")) if a==0 and b==0 and c==0: print('This equation has infinity solution') elif a==0 and b==0 and c!=0: print('This equation has no solution') elif a==0 and b!=0 and c!=0: x= -c/b print('This equation has one soultion',x) else: if b**2-4*a*c<0: print('This equation has no real root') elif b**2-4*a*c>=0: t=(b**2-4*a*c)**(1/2) print(t) x1= (-b+t)/(2*a) x2= (-b-t)/(2*a) print('This equation has two real root',x1,x2)
false
9c738875350bec148a14096eec94605fe89c99b0
vibhorsingh11/hackerrank-python
/04_Sets/02_SymmetricDifference.py
467
4.3125
4
# Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates # those values that exist in either M or N but do not exist in both. # Enter your code here. Read input from STDIN. Print output to STDOUT a, b = (int(input()), input().split()) c, d = (int(input()), input().split()) x = set(b) y = set(d) p = y.difference(x) q = x.difference(y) r = p.union(q) print('\n'.join(sorted(r, key=int)))
true
7276c10f1e342e0f6ca8170a299fc4471cd955a6
menasheep/CodingDojo
/Python/compare_arrays.py
1,165
4.15625
4
list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = [1,2,5,6,5] list_two = [1,2,5,6,5,3] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # ***** list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','cream'] if list_one == list_two: print True print "These arrays are the same!" else: print False print "These arrays are different. Womp womp." # **Output** # C:\Users\Mal\Desktop\Coding Dojo\Python>python compare_arrays.py # True # These arrays are the same! # These arrays are different. Womp womp. # These arrays are different. Womp womp. # These arrays are different. Womp womp. # C:\Users\Mal\Desktop\Coding Dojo\Python>
true
0dfe39b515dc391753d29b540d6af13abefd8269
yshshadow/Leetcode
/201-250/211.py
2,515
4.1875
4
# Design a data structure that supports the following two operations: # # void addWord(word) # bool search(word) # search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. # # Example: # # addWord("bad") # addWord("dad") # addWord("mad") # search("pad") -> false # search("bad") -> true # search(".ad") -> true # search("b..") -> true # Note: # You may assume that all words are consist of lowercase letters a-z. class TrieNode: def __init__(self): self.is_word = False self.children = dict() class WordDictionary: 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: void """ root = self.root for ch in word: if ch not in root.children: root.children[ch] = TrieNode() root = root.children[ch] root.is_word = 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 """ root = self.root return self.dfs(root, word, 0) def dfs(self, node, word, index): if index == len(word) - 1: if word[index] != '.' and word[index] in node.children and node.children[word[index]].is_word: return True elif word[index] == '.' and any(node.children[child].is_word for child in node.children): return True else: return False else: if word[index] == '.': return any(self.dfs(node.children[child], word, index + 1) for child in node.children) elif word[index] in node.children: return self.dfs(node.children[word[index]], word, index + 1) else: return False # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word) s = WordDictionary() s.addWord('bad') s.addWord('dad') s.addWord('mad') print(s.search('pad')) print(s.search('bad')) print(s.search('.ad')) print(s.search('b..')) print(s.search('c..')) print(s.search('...'))
true
9137c399473cded62f26e36e512433eb4faaa00f
yshshadow/Leetcode
/1-50/48.py
1,614
4.125
4
# You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Note: # # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. # # Example 1: # # Given input matrix = # [ # [1,2,3], # [4,5,6], # [7,8,9] # ], # # rotate the input matrix in-place such that it becomes: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] # Example 2: # # Given input matrix = # [ # [ 5, 1, 9,11], # [ 2, 4, 8,10], # [13, 3, 6, 7], # [15,14,12,16] # ], # # rotate the input matrix in-place such that it becomes: # [ # [15,13, 2, 5], # [14, 3, 4, 1], # [12, 6, 8, 9], # [16, 7,10,11] # ] class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ # length = len(matrix) # for x in range(int(length / 2)): # for y in range(x, length - x - 1): # a1, b1 = x, y # a2, b2 = b1, length - a1 - 1 # a3, b3 = b2, length - a2 - 1 # a4, b4 = b3, length - a3 - 1 # temp = matrix[a4][b4] # matrix[a4][b4] = matrix[a3][b3] # matrix[a3][b3] = matrix[a2][b2] # matrix[a2][b2] = matrix[a1][b1] # matrix[a1][b1] = temp matrix[::] = zip(*matrix[::-1]) s = Solution() m = [ [5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16] ] s.rotate(m) print(m)
true
b99592d95dcd3f2ce168808da0f08c2b5a83da5d
yshshadow/Leetcode
/51-100/94.py
1,376
4.125
4
# Given a binary tree, return the inorder traversal of its nodes' values. # # For example: # Given binary tree [1,null,2,3], # 1 # \ # 2 # / # 3 # return [1,3,2]. # # Note: Recursive solution is trivial, could you do it iteratively? # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] self.iterative(root, res) # self.recursive(root, res) return res def recursive(self, root, res): if not root: return self.recursive(root.left, res) res.append(root.val) self.recursive(root.right, res) def iterative(self, root, res): if not root: return stack = [] top = root while top or len(stack) != 0: while top: stack.append(top) top = top.left if len(stack) != 0: top = stack[len(stack) - 1] res.append(top.val) stack.pop() top = top.right s = Solution() root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) s.inorderTraversal(root)
true
c73e65896ce89c0ae540e9330a0214a0a5ba5a93
yshshadow/Leetcode
/51-100/88.py
1,074
4.21875
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. # class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ nums1[m: m + n] = nums2 # copy nums2 into nums1 slow, fast = 0, m if m == 0 or n == 0: return while fast < m + n: if nums1[slow] > nums1[fast]: temp = nums1[slow] nums1[slow] = nums1[fast] nums1[fast] = temp slow += 1 if slow == fast: fast += 1 s = Solution() nums1 = [4,5,6,0,0,0] m = 3 nums2 = [1,2,3] n = 3 s.merge(nums1, m, nums2, n) print(nums1)
true
310b99e9b68a2f81323c619977371e3638fc66b1
yshshadow/Leetcode
/300-/572.py
1,583
4.21875
4
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. # # Example 1: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # Given tree t: # 4 # / \ # 1 2 # Return true, because t has the same structure and node values with a subtree of s. # Example 2: # Given tree s: # # 3 # / \ # 4 5 # / \ # 1 2 # / # 0 # Given tree t: # 4 # / \ # 1 2 # Return false. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ return self.traverse(s, t) def traverse(self, s, t): return s is not None and (self.equal(s, t) or self.traverse(s.left, t) or self.traverse(s.right, t)) def equal(self, s, t): if not s and not t: return True elif not s or not t: return False else: return s.val == t.val and self.equal(s.left, t.left) and self.equal(s.right, t.right) so = Solution() s = TreeNode(3) s.left = TreeNode(4) s.right = TreeNode(5) s.left.left = TreeNode(1) s.right.left = TreeNode(2) t = TreeNode(3) t.left = TreeNode(1) t.right = TreeNode(2) print(so.isSubtree(s, t))
true