blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4d68472475d80f98b64756de3cca5e8f90e85241 | DanCowden/PyBites | /19/simple_property.py | 775 | 4.1875 | 4 | """
Write a simple Promo class. Its constructor receives two variables:
name (which must be a string) and expires (which must be a datetime object)
Add a property called expired which returns a boolean value indicating whether
the promo has expired or not.
"""
from datetime import datetime
NOW = datetime.now()
class Promo:
def __init__(self, name, expires):
self.name = name
self.expires = expires
@property
def expired(self):
if self.expires < NOW:
return True
else:
return False
if __name__ == '__main__':
bread1 = Promo('bread', datetime(year=2016, month=12, day=19))
print(bread1.expired)
bread2 = Promo('bread', datetime(year=2021, month=12, day=19))
print(bread2.expired)
| true |
a94d66b0405ab15bf992ff22fc8d72d5983d9828 | denis-trofimov/challenges | /leetcode/interview/strings/Valid Palindrome.py | 781 | 4.1875 | 4 | # You are here!
# Your runtime beats 76.88 % of python3 submissions.
# Valid Palindrome
# Solution
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Output: false
# Constraints:
# s consists only of printable ASCII characters.
class Solution:
def isPalindrome(self, s: str) -> bool:
alphanumeric = [l for l in s.lower() if l.isalnum()]
n = len(alphanumeric) - 1
for i, l in enumerate(alphanumeric):
if l != alphanumeric[n - i]:
return False
return True | true |
7e18ee8ce20624b5ac6dfc36b9ddf245c5fbc043 | derekdeibert/derekdeibert.github.io | /Python Projects/RollDice.py | 1,025 | 4.25 | 4 | """This program will roll a dice and allow a user to guess the number."""
from random import randint
from time import sleep
def get_user_guess():
"""Collects the guess from user"""
user_guess=int(raw_input("Guess which number I rolled!:"))
return user_guess
def roll_dice(number_of_sides):
first_roll=randint(1,number_of_sides)
second_roll=randint(1, number_of_sides)
max_val=number_of_sides*2
print "The maximum possible value is:" + str(max_val)
sleep(1)
user_guess=get_user_guess()
if user_guess>max_value:
print "Guess is outside possible range!"
elif user_guess<=max_value:
print "Rolling..."
sleep(2)
print "The first value is: %d" % first_roll
sleep(1)
print "The second value is: %d" % second_roll
total_roll=first_roll+second_roll
sleep(1)
print "Resutl...: %d" % total_roll
if user_guess>total_roll:
print "You won!"
return
else:
if user_guess<total_roll:
print "Sorry, you lost."
return
roll_dice(6) | true |
40b2e7bc13c6dc1ef9c10a5e782f5310e0ef577c | rpw1/351-Final-Project | /src/queue.py | 2,099 | 4.28125 | 4 |
class ItemQueue:
"""
A class to store distances in a priority queue and labels in a list with maching indices with the distances.
Methods
-------
insert(item : int, label : str)
This function inserts the distance from least to greatest in order in the items list and
places the label in the same index in the labels list.
getItemLabel(index : int)
This function takes in a index and returns the matching distance from the items list and
a label from the labels list.
getMultiple(x : int)
This function is used to get the first x distances from the items list and
labels from the labels list.
"""
items : list = None
labels : list = None
def __init__(self):
self.items = []
self.labels = []
def insert(self, item : int, label : str):
"""
This function inserts the distance from least to greatest in order in the items list and
places the label in the same index in the labels list.
"""
if len(self.items) == 0:
self.items.append(item)
self.labels.append(label)
for x in range(len(self.items)):
if item < self.items[x]:
self.items.insert(x, item)
self.labels.insert(x, label)
break
if x == len(self.items) - 1:
self.items.append(item)
self.labels.append(label)
def getItemLabel(self, index : int):
"""
This function takes in a index and returns the matching distance from the items list and
a label from the labels list.
"""
if index >= len(self.items) or index < 0:
raise IndexError
return self.items[index], self.labels[index]
def getMultiple(self, x : int):
"""
This function is used to get the first x distances from the items list and
labels from the labels list.
"""
if x >= len(self.items) or x < 0:
raise IndexError
return self.items[0:x], self.labels[0:x] | true |
c3613d1209e07c7f4c04d43d3159b530c884dbc7 | jaadyyah/APSCP | /2017_jaadyyahshearrion_4.02a.py | 984 | 4.5 | 4 | # description of function goes here
# input: user sees list of not plural fruit
# output: the function returns the plural of the fruits
def fruit_pluralizer(list_of_strings):
new_fruits = []
for item in list_of_strings:
if item == '':
item = 'No item'
new_fruits.append(item)
elif item[-1] == 'y':
item = item[:-1] + 'ies'
new_fruits.append(item)
elif item[-1] == 'e':
item1 = item + 's'
new_fruits.append(item1)
elif item[-2:] == 'ch':
item2 = item + 'es'
new_fruits.append(item2)
else:
item3 = item + 's'
new_fruits.append(item3)
return new_fruits
fruit_list = ['apple', 'berry', 'melon', 'peach']
print("Single Fruit: " + str(fruit_list))
new_fruits_list = fruit_pluralizer(fruit_list)
print("Plural Fruit: " + str(new_fruits_list))
# claire checked me based on the asssaignements she said I did a gud
| true |
e1c83664bbc031c2c53516d7aac44ad4acb500b4 | BiplabG/python_tutorial | /Session II/problem_5.py | 374 | 4.34375 | 4 | """5. Write a python program to check if a three digit number is palindrome or not.
Hint: Palindrome is a number which is same when read from either left hand side or right hand side. For example: 101 or 141 or 656 etc.
"""
num = int(input("Enter the number: \n"))
if (num % 10) == (num // 100):
print("Palindrome Number.")
else:
print("Not a Palindrome Number.")
| true |
7b3b9d90b2dd4d27ac2875a2471791308d647ac3 | BiplabG/python_tutorial | /Session I/problem_3.py | 445 | 4.34375 | 4 | """
Ask a user his name, address and his hobby. Then print a statement as follows:
You are <name>. You live in <address>. You like to do <> in your spare time.
"""
name = input("Name:\n")
address = input("Address:\n")
hobby = input("Hobby:\n")
print("You are %s. You live in %s. You like to do %s in your spare time." %(name, address, hobby))
print(f"You are {name}. You live in {address}. You like to do {hobby} in your spare time.")
| true |
ab1ae9f26453fdee0d0e5ee8a0c0b604bc193d83 | BiplabG/python_tutorial | /Session II/practice_4.py | 240 | 4.1875 | 4 | """4. Write a python program which prints cube numbers less than a certain number provided by the user.
"""
num = int(input("Enter the number:"))
counter = 0
while (counter ** 3 <= num):
print(counter ** 3)
counter = counter + 1
| true |
220e17a0bce87d84f2dbea107b63531dfe601043 | HLNN/leetcode | /src/0662-maximum-width-of-binary-tree/maximum-width-of-binary-tree.py | 1,816 | 4.25 | 4 | # Given the root of a binary tree, return the maximum width of the given tree.
#
# The maximum width of a tree is the maximum width among all levels.
#
# The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
#
# It is guaranteed that the answer will in the range of a 32-bit signed integer.
#
#
# Example 1:
#
#
# Input: root = [1,3,2,5,3,null,9]
# Output: 4
# Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
#
#
# Example 2:
#
#
# Input: root = [1,3,2,5,null,null,9,6,null,7]
# Output: 7
# Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
#
#
# Example 3:
#
#
# Input: root = [1,3,2,5]
# Output: 2
# Explanation: The maximum width exists in the second level with length 2 (3,2).
#
#
#
# Constraints:
#
#
# The number of nodes in the tree is in the range [1, 3000].
# -100 <= Node.val <= 100
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
queue = [(root, 0, 0)]
cur_depth = left = ans = 0
for node, depth, pos in queue:
if node:
queue.append((node.left, depth+1, pos*2))
queue.append((node.right, depth+1, pos*2 + 1))
if cur_depth != depth:
cur_depth = depth
left = pos
ans = max(pos - left + 1, ans)
return ans
| true |
bde099ab0828e59824a392ce9115533e2a3f0b08 | HLNN/leetcode | /src/0332-reconstruct-itinerary/reconstruct-itinerary.py | 1,866 | 4.15625 | 4 | # You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
#
# All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
#
#
# For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
#
#
# You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
#
#
# Example 1:
#
#
# Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
# Output: ["JFK","MUC","LHR","SFO","SJC"]
#
#
# Example 2:
#
#
# Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
# Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
# Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.
#
#
#
# Constraints:
#
#
# 1 <= tickets.length <= 300
# tickets[i].length == 2
# fromi.length == 3
# toi.length == 3
# fromi and toi consist of uppercase English letters.
# fromi != toi
#
#
class Solution:
def dfs(self, airport):
while self.adj_list[airport]:
candidate = self.adj_list[airport].pop()
self.dfs(candidate)
self.route.append(airport)
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
self.route = []
self.adj_list = defaultdict(list)
for i, j in tickets:
self.adj_list[i].append(j)
for key in self.adj_list:
self.adj_list[key] = sorted(self.adj_list[key], reverse=True)
self.dfs("JFK")
return self.route[::-1]
| true |
e4d43d82683865b78715159309da5fd4256a5d63 | HLNN/leetcode | /src/1464-reduce-array-size-to-the-half/reduce-array-size-to-the-half.py | 1,211 | 4.15625 | 4 | # You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
#
# Return the minimum size of the set so that at least half of the integers of the array are removed.
#
#
# Example 1:
#
#
# Input: arr = [3,3,3,3,5,5,5,2,2,7]
# Output: 2
# Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
# Possible sets of size 2 are {3,5},{3,2},{5,2}.
# Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
#
#
# Example 2:
#
#
# Input: arr = [7,7,7,7,7,7]
# Output: 1
# Explanation: The only possible set you can choose is {7}. This will make the new array empty.
#
#
#
# Constraints:
#
#
# 2 <= arr.length <= 105
# arr.length is even.
# 1 <= arr[i] <= 105
#
#
class Solution:
def minSetSize(self, arr: List[int]) -> int:
freq_max = sorted(Counter(arr).values(), reverse=True)
n = len(arr) // 2
ans = 0
for i in range(len(freq_max)):
ans += freq_max[i]
if ans >= n:
return i + 1
| true |
d1a9f49300eb997d4b2cb1da84b514dff6801a7f | HLNN/leetcode | /src/0006-zigzag-conversion/zigzag-conversion.py | 1,495 | 4.125 | 4 | # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
#
# P A H N
# A P L S I I G
# Y I R
#
#
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
#
# string convert(string s, int numRows);
#
#
#
# Example 1:
#
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
#
#
# Example 2:
#
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
# P I N
# A L S I G
# Y A H R
# P I
#
#
# Example 3:
#
#
# Input: s = "A", numRows = 1
# Output: "A"
#
#
#
# Constraints:
#
#
# 1 <= s.length <= 1000
# s consists of English letters (lower-case and upper-case), ',' and '.'.
# 1 <= numRows <= 1000
#
#
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
zig = [""] * numRows
loc = self.location(numRows - 1)
for c, l in zip(s, loc):
zig[l] += c
return "".join(zig)
def location(self, bound):
index, inc = 0, 1
while True:
yield index;
if index == bound:
inc = -1
elif index == 0:
inc = 1
index += inc
| true |
f09cc935dafa2b61cff7ed80ace981be72c79775 | HLNN/leetcode | /src/2304-cells-in-a-range-on-an-excel-sheet/cells-in-a-range-on-an-excel-sheet.py | 1,817 | 4.125 | 4 | # A cell (r, c) of an excel sheet is represented as a string "<col><row>" where:
#
#
# <col> denotes the column number c of the cell. It is represented by alphabetical letters.
#
#
# For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.
#
#
# <row> is the row number r of the cell. The rth row is represented by the integer r.
#
#
# You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2.
#
# Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
#
#
# Example 1:
#
#
# Input: s = "K1:L2"
# Output: ["K1","K2","L1","L2"]
# Explanation:
# The above diagram shows the cells which should be present in the list.
# The red arrows denote the order in which the cells should be presented.
#
#
# Example 2:
#
#
# Input: s = "A1:F1"
# Output: ["A1","B1","C1","D1","E1","F1"]
# Explanation:
# The above diagram shows the cells which should be present in the list.
# The red arrow denotes the order in which the cells should be presented.
#
#
#
# Constraints:
#
#
# s.length == 5
# 'A' <= s[0] <= s[3] <= 'Z'
# '1' <= s[1] <= s[4] <= '9'
# s consists of uppercase English letters, digits and ':'.
#
#
class Solution:
def cellsInRange(self, s: str) -> List[str]:
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
c1, r1, _, c2, r2 = s
c1, c2 = ord(c1) - 65, ord(c2) - 65
r1, r2 = int(r1), int(r2)
return [f'{c}{r}' for c, r in product(alphabet[c1: c2 + 1], range(r1, r2 + 1))]
| true |
1d3f298d55c7ce39420752fa25a1dc4409feffe9 | HLNN/leetcode | /src/0899-binary-gap/binary-gap.py | 1,395 | 4.125 | 4 | # Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
#
# Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.
#
#
# Example 1:
#
#
# Input: n = 22
# Output: 2
# Explanation: 22 in binary is "10110".
# The first adjacent pair of 1's is "10110" with a distance of 2.
# The second adjacent pair of 1's is "10110" with a distance of 1.
# The answer is the largest of these two distances, which is 2.
# Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
#
#
# Example 2:
#
#
# Input: n = 8
# Output: 0
# Explanation: 8 in binary is "1000".
# There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
#
#
# Example 3:
#
#
# Input: n = 5
# Output: 2
# Explanation: 5 in binary is "101".
#
#
#
# Constraints:
#
#
# 1 <= n <= 109
#
#
class Solution:
def binaryGap(self, n: int) -> int:
b = str(bin(n))[3:]
res, gap = 0, 1
for c in b:
if c == '1':
res = max(res, gap)
gap = 1
else:
gap += 1
return res
| true |
2e15c9101d8471d05afe671d74b46a488ef0edcd | HLNN/leetcode | /src/1888-find-nearest-point-that-has-the-same-x-or-y-coordinate/find-nearest-point-that-has-the-same-x-or-y-coordinate.py | 1,769 | 4.125 | 4 | # You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
#
# Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.
#
# The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
#
#
# Example 1:
#
#
# Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
# Output: 2
# Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.
#
# Example 2:
#
#
# Input: x = 3, y = 4, points = [[3,4]]
# Output: 0
# Explanation: The answer is allowed to be on the same location as your current location.
#
# Example 3:
#
#
# Input: x = 3, y = 4, points = [[2,3]]
# Output: -1
# Explanation: There are no valid points.
#
#
# Constraints:
#
#
# 1 <= points.length <= 104
# points[i].length == 2
# 1 <= x, y, ai, bi <= 104
#
#
class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
idx, dist = -1, 100000000.
for i, (a, b) in enumerate(points):
if x == a and y == b: return i
if x == a or y == b:
d = ((x - a) ** 2 + (y - b) ** 2) ** .5
if d < dist:
idx, dist = i, d
return idx
| true |
8c3a922fa3cd65184efdcaeb3fb5e936f70edcf7 | HLNN/leetcode | /src/1874-form-array-by-concatenating-subarrays-of-another-array/form-array-by-concatenating-subarrays-of-another-array.py | 2,057 | 4.25 | 4 | # You are given a 2D integer array groups of length n. You are also given an integer array nums.
#
# You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).
#
# Return true if you can do this task, and false otherwise.
#
# Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
#
#
# Example 1:
#
#
# Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]
# Output: true
# Explanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].
# These subarrays are disjoint as they share no common nums[k] element.
#
#
# Example 2:
#
#
# Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]
# Output: false
# Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.
# [10,-2] must come before [1,2,3,4].
#
#
# Example 3:
#
#
# Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]
# Output: false
# Explanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.
# They share a common elements nums[4] (0-indexed).
#
#
#
# Constraints:
#
#
# groups.length == n
# 1 <= n <= 103
# 1 <= groups[i].length, sum(groups[i].length) <= 103
# 1 <= nums.length <= 103
# -107 <= groups[i][j], nums[k] <= 107
#
#
class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
k = 0
for g in groups:
while k + len(g) <= len(nums):
if nums[k: k + len(g)] == g:
k += len(g)
break
k += 1
else:
return False
return True
| true |
e725c199c6fa75ca2f9aa7c85f349c3e71fd249d | HLNN/leetcode | /src/2433-best-poker-hand/best-poker-hand.py | 1,984 | 4.125 | 4 | # You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].
#
# The following are the types of poker hands you can make from best to worst:
#
#
# "Flush": Five cards of the same suit.
# "Three of a Kind": Three cards of the same rank.
# "Pair": Two cards of the same rank.
# "High Card": Any single card.
#
#
# Return a string representing the best type of poker hand you can make with the given cards.
#
# Note that the return values are case-sensitive.
#
#
# Example 1:
#
#
# Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]
# Output: "Flush"
# Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".
#
#
# Example 2:
#
#
# Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"]
# Output: "Three of a Kind"
# Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind".
# Note that we could also make a "Pair" hand but "Three of a Kind" is a better hand.
# Also note that other cards could be used to make the "Three of a Kind" hand.
#
# Example 3:
#
#
# Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"]
# Output: "Pair"
# Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair".
# Note that we cannot make a "Flush" or a "Three of a Kind".
#
#
#
# Constraints:
#
#
# ranks.length == suits.length == 5
# 1 <= ranks[i] <= 13
# 'a' <= suits[i] <= 'd'
# No two cards have the same rank and suit.
#
#
class Solution:
def bestHand(self, ranks: List[int], suits: List[str]) -> str:
if all(s == suits[0] for s in suits):
return 'Flush'
cnt = Counter(ranks)
m = max(cnt.values())
if m > 2:
return 'Three of a Kind'
elif m == 2:
return 'Pair'
else:
return 'High Card'
| true |
523e1a35af3a9356d503c6fd313bf9c0f8a899af | HLNN/leetcode | /src/0868-push-dominoes/push-dominoes.py | 1,885 | 4.15625 | 4 | # There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
#
# After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
#
# When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
#
# For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
#
# You are given a string dominoes representing the initial state where:
#
#
# dominoes[i] = 'L', if the ith domino has been pushed to the left,
# dominoes[i] = 'R', if the ith domino has been pushed to the right, and
# dominoes[i] = '.', if the ith domino has not been pushed.
#
#
# Return a string representing the final state.
#
#
# Example 1:
#
#
# Input: dominoes = "RR.L"
# Output: "RR.L"
# Explanation: The first domino expends no additional force on the second domino.
#
#
# Example 2:
#
#
# Input: dominoes = ".L.R...LR..L.."
# Output: "LL.RR.LLRRLL.."
#
#
#
# Constraints:
#
#
# n == dominoes.length
# 1 <= n <= 105
# dominoes[i] is either 'L', 'R', or '.'.
#
#
class Solution:
def pushDominoes(self, dominoes: str) -> str:
symbols = [(-1, 'L'),] + [(i, x) for i, x in enumerate(dominoes) if x != '.'] + [(len(dominoes), 'R'),]
ans = list(dominoes)
for (i, x), (j, y) in pairwise(symbols):
if x == y:
for k in range(i + 1, j):
ans[k] = x
elif x > y: # RL
for k in range(i + 1, j):
ans[k] = '.LR'[0 if k-i == j-k else (1 if k-i > j-k else -1)]
return ''.join(ans)
| true |
4082c4c22dce52ccef9ff68ecd1f8e9ffeb1ec28 | HLNN/leetcode | /src/0009-palindrome-number/palindrome-number.py | 878 | 4.28125 | 4 | # Given an integer x, return true if x is a palindrome, and false otherwise.
#
#
# Example 1:
#
#
# Input: x = 121
# Output: true
# Explanation: 121 reads as 121 from left to right and from right to left.
#
#
# Example 2:
#
#
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
#
#
# Example 3:
#
#
# Input: x = 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
#
#
#
# Constraints:
#
#
# -231 <= x <= 231 - 1
#
#
#
# Follow up: Could you solve it without converting the integer to a string?
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x >= 0 and x == int(str(x)[::-1]):
return True
else:
return False
| true |
9325a332de0902d4ec6c122a4a30c91b6f57e820 | HLNN/leetcode | /src/0031-next-permutation/next-permutation.py | 2,168 | 4.3125 | 4 | # A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
#
#
# For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
#
#
# The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
#
#
# For example, the next permutation of arr = [1,2,3] is [1,3,2].
# Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
# While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
#
#
# Given an array of integers nums, find the next permutation of nums.
#
# The replacement must be in place and use only constant extra memory.
#
#
# Example 1:
#
#
# Input: nums = [1,2,3]
# Output: [1,3,2]
#
#
# Example 2:
#
#
# Input: nums = [3,2,1]
# Output: [1,2,3]
#
#
# Example 3:
#
#
# Input: nums = [1,1,5]
# Output: [1,5,1]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 100
# 0 <= nums[i] <= 100
#
#
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
while i >= 0 and nums[i + 1] <= nums[i]:
i -= 1
if i < 0:
self.reverse(nums, 0)
return
j = len(nums) - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
self.reverse(nums, i + 1)
def reverse(self, nums, start):
i = start
j = len(nums) - 1
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
| true |
42c47c2470efbde7d9a3446fe9dd2930ab317dc7 | HLNN/leetcode | /src/0225-implement-stack-using-queues/implement-stack-using-queues.py | 2,179 | 4.15625 | 4 | # Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
#
# Implement the MyStack class:
#
#
# void push(int x) Pushes element x to the top of the stack.
# int pop() Removes the element on the top of the stack and returns it.
# int top() Returns the element on the top of the stack.
# boolean empty() Returns true if the stack is empty, false otherwise.
#
#
# Notes:
#
#
# You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
# Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
#
#
#
# Example 1:
#
#
# Input
# ["MyStack", "push", "push", "top", "pop", "empty"]
# [[], [1], [2], [], [], []]
# Output
# [null, null, null, 2, 2, false]
#
# Explanation
# MyStack myStack = new MyStack();
# myStack.push(1);
# myStack.push(2);
# myStack.top(); // return 2
# myStack.pop(); // return 2
# myStack.empty(); // return False
#
#
#
# Constraints:
#
#
# 1 <= x <= 9
# At most 100 calls will be made to push, pop, top, and empty.
# All the calls to pop and top are valid.
#
#
#
# Follow-up: Can you implement the stack using only one queue?
#
from queue import Queue
class MyStack:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
self.t = None
def push(self, x: int) -> None:
self.q1.put(x)
self.t = x
def pop(self) -> int:
self.t = None
while self.q1.qsize() > 1:
x = self.q1.get()
self.q2.put(x)
self.t = x
res = self.q1.get()
self.q1, self.q2 = self.q2, self.q1
return res
def top(self) -> int:
return self.t
def empty(self) -> bool:
return True if self.q1.empty() else False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
| true |
7d20a7486e2a83d8cafb24a29844276eabf246c0 | dexterneutron/pybootcamp | /level_1/removefromtuple.py | 431 | 4.25 | 4 | """Exercise 8: Write a Python function to remove an item from a tuple.
"""
def remove_from_tuple(input_tuple,element_index):
new_tuple = tuple(el for i, el in enumerate(input_tuple) if i != element_index)
return new_tuple
input_tuple = ("red", "blue", "orange", "magenta", "yellow")
output_tuple = remove_from_tuple(input_tuple, 3)
print(f"Input tuple is: {input_tuple}")
print(f"Output tuple is: {output_tuple}")
| true |
24fd71a9007cdc5fddb57447486c2544a907f8f0 | dexterneutron/pybootcamp | /level_3/listofwords.py | 607 | 4.375 | 4 | """Exercise 4: Write a Python function using list comprehension
that receives a list of words and returns a list that contains:
-The number of characters in each word if the word has 3 or more characters
-The string “x” if the word has fewer than 3 characters
"""
def list_of_words(wordlist):
output = [len(word) if len(word) >= 3 else "x" for word in wordlist]
return output
#Test case
words = ["foo", "bar", "baz", "qux", "quux", "corge", "gr",
"garply", "waldo", "f", "plugh", "x", "thud"]
words_output = list_of_words(words)
print(f"""Input List: {words}
Output List {words_output}""") | true |
3adf5c398a96c0d3355d0e3d0204867538aada7b | ryanfmurphy/AustinCodingAcademy | /warmups/fizzbuzz2.py | 1,341 | 4.3125 | 4 | '''
Tue Nov 4 Warmup: Fizz Buzz Deluxe
Remember the Fizz Buzz problem we worked on in the earlier Homework?
Create a python program that loops through the numbers 1 to 100, prints each number out.
In addition to printing the number, print "fizz" if the number is divisible by 3, and "buzz" if the number is divisible by 5.
If the number is divisible by both 3 and 5, print both "fizz" and "buzz".
We will be recreating the Fizz Buzz program again, but this time making it customizable: What message does the user want to see instead of "fizz" and "buzz"? What numbers should it check divisibility by? Ask the user these questions using raw_input(). If the user doesn't enter anything, use the defaults of "fizz", "buzz", 3 and 5.
'''
fizzword = raw_input('What word shall I show instead of "fizz"? ')
if fizzword == "": fizzword = 'fizz'
buzzword = raw_input('And what word shall I show instead of "buzz"? ')
if buzzword == "": buzzword = 'buzz'
mod1 = raw_input('Print ' + fizzword + ' when divisible by what? ')
if mod1 == "":
mod1 = 3
else:
mod1 = int(mod1)
mod2 = raw_input('Print ' + buzzword + ' when divisible by what? ')
if mod2 == "":
mod2 = 5
else:
mod2 = int(mod2)
for i in xrange(1,101):
print i,
if i % mod1 == 0: print fizzword,
if i % mod2 == 0: print buzzword,
print # leave a newline
| true |
cc45bf62aa11e67b85a2a9203d4eda8ef01be826 | Dahrio-Francois/ICS3U-Unit3-04-Python | /integers.py | 531 | 4.34375 | 4 | #!/usr/bin/env python 3
#
# Created by: Dahrio Francois
# Created on: December 2020
# this program identifies if the number is a positive or negative
# with user input
integer = 0
def main():
# this function identifies a positive or negative number
# input
number = int(input("Enter your number value: "))
print("")
# process
if number == integer:
print(" 0 ")
elif number < integer:
print(" - ")
elif number > integer:
print(" + ")
if __name__ == "__main__":
main()
| true |
fbc8a6cb7144d879af77af67baa5f18797b8ad9e | laithtareq/Intro2CS | /ex1/math_print.py | 1,046 | 4.53125 | 5 | #############################################################
# FILE : math_print.py
# WRITER : shay margolis , shaymar , 211831136
# EXERCISE : intro2cs1 ex1 2018-2019
# DESCRIPTION : A set of function relating to math
#############################################################
import math
def golden_ratio():
""" calculates and prints the golden ratio """
print((1 + math.pow(5, 0.5)) / 2)
def six_cubed():
""" calculates the result of 6 cubed. """
print(math.pow(6, 3))
def hypotenuse():
""" calculates the length of the hypotenuse in
a right triangular with cathuses 5,3 """
print(math.sqrt(math.pow(5, 2) + math.pow(3, 2)))
def pi():
""" returns the value of the constant PI """
print(math.pi)
def e():
""" returns the value of the constant E """
print(math.e)
def triangular_area():
""" prints the areas of the right triangulars with
equals cathuses with lengths from 1 to 10 """
print(1*1/2, 2*2/2, 3*3/2, 4*4/2, 5*5/2,
6*6/2, 7*7/2, 8*8/2, 9*9/2, 10*10/2) | true |
a8501491eda940dd2bc3083dfe185f9e5616ede4 | laithtareq/Intro2CS | /ex10/ship.py | 1,166 | 4.3125 | 4 | ############################################################
# FILE : ship.py
# WRITER : shay margolis , roy amir
# EXERCISE : intro2cs1 ex10 2018-2019
# DESCRIPTION : A class representing the ship
#############################################################
from element import Element
class Ship(Element):
"""
Ship element that contains function
for special properties of Ship.
"""
SHIP_RADIUS = 1
def __init__(self, position, velocity, angle,life):
"""
Creates a ship class instance
:param position: position vector (x,y)
:param velocity: velocity vector (v_x, v_y)
:param angle: angle in degrees
:return:
"""
self.__life = life
Element.__init__(self, position, velocity, angle)
def decrease_life(self):
"""
Decreases life of ship by 1
:return:
"""
self.__life -= 1
def get_life(self):
"""
Returns total life of ship
:return:
"""
return self.__life
def get_radius(self):
"""
Returns radius of ship
:return:
"""
return self.SHIP_RADIUS
| true |
faa5a5c24df378ff14b80d8c1553b1167a93323b | spgetter/W2Day_3 | /shopping_cart.py | 1,329 | 4.15625 | 4 |
groceries = {
'milk (1gal)': 4.95,
'hamburger (1lb)': 3.99,
'tomatoes (ea.)': .35,
'asparagus (12lbs)': 7.25,
'water (1oz)': .01,
'single use plastic bag': 3.00,
}
# cart_total = 0
sub_total = 0
# cart = [["Total =", cart_total]]
cart = []
def shopping_cart():
print("\n")
response = input("Would you like to 'show'/'add'/'delete' or 'quit'?:")
# return response, cart, cart_total, sub_total
return response, cart
def add_items():
for key,value in groceries.items():
print(f"{key} : ${value}")
choice = input("Select from these items:")
try:
sub_total = groceries[choice]
# cart_total += sub_total
cart.append([choice, sub_total])
# cart[len(cart)-1][1] = [[cart_total]]
except:
print("Please only select an item in the list, typed EXACTLY as it appears")
def delete_items():
for i in cart:
print(f"{i[0]} : ${i[1]}")
choice = input("Select from these items:")
try:
sub_total = groceries[choice]
# cart_total -= sub_total
cart.remove([choice, sub_total])
# cart[len(cart)-1][1] = [[cart_total]]
except:
print("Please only select an item in the list, typed EXACTLY as it appears")
def show_cart():
for i in cart:
print(f"{i[0]} : ${i[1]}")
| true |
18fa77116d86476f37241b8f3682afb906ea3c40 | OrevaElmer/myProject | /passwordGenerator.py | 416 | 4.25 | 4 | #This program generate list of password:
import random
userInput = int(input("Enter the lenght of the password: "))
passWord = "abcdefghijklmnopqrstuv"
selectedText = random.sample(passWord, userInput)
passwordText = "".join(selectedText)
'''
#Here is another method:
passwordText =""
for i in range(userInput):
passwordText += random.choice(passWord)
'''
print(f"Your password is {passwordText}")
| true |
1531e56c78f0d73e0ba7a1236dac4e9054462c1b | Zadams1989/programming-GitHub | /Ch 7 Initials CM.py | 603 | 4.1875 | 4 | username = input('Enter you first, middle and last name:\n')
while username != 'abort':
if ' ' not in username:
print('Error. Enter first, middle and last name separated by spaces.\n')
username = input('Enter you first, middle and last name:\n')
elif username.count(' ') < 2:
print('Error. Less than three names detected.\n')
username = input('Enter you first, middle and last name:\n')
else:
split_names = username.split(' ')
username = 'abort'
for name in split_names:
name = name.strip()
print('%s. ' % name[0], end='')
| true |
d05c196b7e124b78cc0dcfa026d8f53d96f181e5 | SumanKhdka/python-experiments | /cw1/hw.py | 1,152 | 4.71875 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward
# UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
a = 0
b = 0
while True:
r = input("enter the direction step: ")
if not r:
break
try:
dire, steps = r.split(' ')
except IndentationError:
print("Sorry! Something went wrong. Try again.")
if dire == "left":
a = a - int(steps)
elif dire == "right":
a = a + int(steps)
elif dire == "up":
b = b + int(steps)
elif dire == "down":
b = b - int(steps)
else:
pass
distance = (a ** 2 + b ** 2) ** (1 / 2)
print("the output is: ", int(distance))
| true |
67600d998c1be6668871eccbfc4da808f48ac26f | ferraopam/pamela_py_ws | /tripcost.py | 435 | 4.34375 | 4 | #program to calculate trip cost for the given number of people
no_of_persons=int(input("Enter the no of persons:"))
distance_km=int(input("Enter the distance in KM:"))
milage_km=int(input("Enter the milage in KM:"))
fuel_price=int(input("Enter the fuel price:"))
no_liters_used=distance_km / milage_km
total_cost=no_liters_used*fuel_price
price_per_head=total_cost / no_of_persons
print(f"Total cost per person is:{price_per_head}")
| true |
26d65d7914765a8da1cec881f76638bc1de233c6 | DrBanana419/oldconfigs | /cobra/test1.py | 356 | 4.21875 | 4 | def squareroot(x):
import random
import math
g=random.randint(int(x-x**2),int(x+x**2))
while abs(x-g**2)>0.00000000000001:
g=(g+x/g)/2
return abs(g)
print("This programme gives you the sum of a number and its square root, and then takes the square root of the sum")
v=float(input("Number: "))
print(squareroot(v+squareroot(v)))
| true |
8a8063438376e796c015c4ad69f3cf5c1d331665 | Alessia-Barlascini/coursera- | /Getting-Started/week-7/ex_5.1.py | 417 | 4.15625 | 4 | # repeat asking for a number until the word done is entered
# print done
# print the total
# print the count
# print the average at the end
somma=0
num=0
while True:
val=input('Enter a number: ')
if val == 'done':
break
try:
fval=float(val)
except:
print ('Enter a valid number')
continue
num += 1
somma += fval
print('all done')
print(somma,num,somma/num) | true |
251990ff68cadf74f694bab1d8f57c1e90a02322 | taishan-143/Macro_Calculator | /src/main/functions/body_fat_percentage_calc.py | 1,466 | 4.125 | 4 | import numpy as np
### Be more specific with measurement guides!
# Print a message to the user if this calculator is selected.
# male and female body fat percentage equations
def male_body_fat_percentage(neck, abdomen, height):
return (86.010 * np.log10(abdomen - neck)) - (70.041 * np.log10(height)) + 36.76
def female_body_fat_percentage(neck, waist, hips, height):
return (163.205 * np.log10(waist + hips - neck)) - (97.684 * np.log10(height)) - 78.387
def body_fat_percentage_calc(user_data):
# define user sex and height
sex = user_data["Sex"]
height = user_data["Height"] * 0.393701 ### => conversion to inches
# determine which equation applies to the user
try:
if sex[0].lower() == 'm':
neck = float(input("\nInput the measure of your neck (inches): "))
abdomen = float(input("Input the measure of your abdomen (inches): "))
body_fat_perc = male_body_fat_percentage(neck, abdomen, height)
return round(body_fat_perc, 2)
elif sex[0].lower() == 'f':
neck = float(input("\nInput the measure of your neck (inches): "))
waist = float(input("Input the measure of your waist (inches): "))
hips = float(input("Input the measure of your hips (inches): "))
body_fat_perc = female_body_fat_percentage(neck, waist, hips, height)
return round(body_fat_perc, 2)
except KeyError:
print("That is an unspecified sex.")
| true |
9d2228ba173c8db9df7f373ce6c56929c729d5d5 | esthergoldman/100-days-of-code | /day1/day1.py | 915 | 4.15625 | 4 | # print("day 1 - Python print Function\nThe function is declared like this\nprint('whay to print')")
# print("hello\nhello\nhello")
#input() will get user input in console then print() will print "hello" and the user input
#print('hello ' + input('what is your name\n') + '!')
# print(len(input("whats your name\n")))
# Instructions
#Write a program that switches the values stored in the variables a and b.
#**Warning.** Do not change the code on lines 1-4 and 12-18. Your program should work for different inputs. e.g. any value of a and b.
# 🚨 Don't change the code below 👇
a = input("a: ")
b = input("b: ")
# 🚨 Don't change the code above 👆
####################################
#Write your code below this line 👇
a1= a
b2= b
a=a1
b=b2
#Write your code above this line 👆
####################################
# 🚨 Don't change the code below 👇
print("a: " + a)
print("b: " + b)
| true |
90ef3c860db2956cf54ce04a97c75e4580d420c5 | saurabhsisodia/Articles_cppsecrets.com | /Root_Node_Path.py | 1,702 | 4.3125 | 4 | # Python program to print path from root to a given node in a binary tree
# to print path from root to a given node
# first we append a node in array ,if it lies in the path
# and print the array at last
# creating a new node
class new_node(object):
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class Root_To_Node(object):
def __init__(self,root):
self.root=root
# function to check if current node in traversal
# lies in path from root to a given node
# if yes then add this node to path_array
def check_path(self,root,key,path_array):
#base case
if root==None:
return False
# append current node in path_array
# if it does not lie in path then we will remove it.
path_array.append(root.value)
if root.value==key:
return True
if (root.left!=None and self.check_path(root.left,key,path_array)) or (root.right!=None and self.check_path(root.right,key,path_array)):
return True
# if given key does not present in left or right subtree rooted at current node
# then delete current node from array
# and return false
path_array.pop()
return False
def Print_Path(self,key):
path_array=[]
check=self.check_path(self.root,key,path_array)
if check:
return path_array
else:
return -1
if __name__=="__main__":
root=new_node(5)
root.left=new_node(2)
root.right=new_node(12)
root.left.left=new_node(1)
root.left.right=new_node(3)
root.right.left=new_node(9)
root.right.right=new_node(21)
root.right.right.left=new_node(19)
root.right.right.right=new_node(25)
obj=Root_To_Node(root)
key=int(input())
x=obj.Print_Path(key)
if x==-1:
print("node is not present in given tree")
else:
print(*x)
| true |
f7146dbc32a1fa35574a429f605df0c5b84e99c9 | saurabhsisodia/Articles_cppsecrets.com | /Distance_root_to_node.py | 2,044 | 4.28125 | 4 | #Python program to find distance from root to given node in a binary tree
# to find the distance between a node from root node
# we simply traverse the tree and check ,is current node lie in the path from root to the given node,
# if yes then we just increment the length by one and follow the same procedure.
class new_node(object):
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class Root_To_Node(object):
def __init__(self,root):
self.root=root
# initializing the value of counter by -1
self.count=-1
# function which will calculate distance
def Distance(self,root,key):
# base case
if root==None:
return False
# increment counter by one,as it can lie in path from root to node
# if it will not then we will decrement counter
self.count+=1
# if current node's value is same as given node's value
# then we are done,we find the given node
if root.value==key:
return True
# check if the given node lie in left subtree or right subtree rooted at current node
# if given node does not lie then this current node does not lie in path from root to given node
# so decrement counter by one
if (root.left!=None and self.Distance(root.left,key)) or ( root.right!=None and self.Distance(root.right,key)):
return True
self.count-=1
return False
# function which will return distance
def Print_Distance(self,key):
check=self.Distance(root,key)
if check==False:
print("key is not present in the tree")
else:
print(" distance of %d from root node is %d " %(key,self.count))
if __name__=="__main__":
root=new_node(1)
root.left=new_node(2)
root.right=new_node(3)
root.left.left=new_node(4)
root.left.right=new_node(5)
root.right.left=new_node(6)
root.right.right=new_node(7)
root.right.left.right=new_node(9)
root.right.left.right.left=new_node(10)
obj=Root_To_Node(root)
key=int(input())
obj.Print_Distance(key)
'''
as we are going at each node only ones so time complexity of above algorithm is
O(n),n=no of nodes in the tree'''
| true |
fe35826debe37f105f93785fad827baa3b1a0954 | hanwenzhang123/python-note | /basics/16-dictionaries.py | 2,727 | 4.625 | 5 | # A dictionary is a set of key value pairs and contain ',' separated values
# In dictionary, each of its values has a label called the key, and they are not ordered
# Dictionaries do not have numerical indexing, they are indexed by keys.
# [lists]
# {dictionaries}
# {key:value, key:value, key:value} - dictionary
# key is a label for associated values
# {'name':'Hanwen', 'profession':'social worker'}
# store data in dictionary allows you to group related data together and keep it organized
# unlike a list or a tuple, the order of the key value pairs does not matter, but keys have to be unique
# if you add a key value pair to your dictionary that uses a duplicate key, the original one will be forgotten
# key can be any immutable typles. values can be any type.
# dictionaries can be grow or shrink as needed, key value pairs can always be added or deleted.
course = {'teacher': 'ashley', 'title': 'dictionaries', 'level': 'beginner'}
print(course['teacher'])
course.keys() #access to every keys in the dictionary
course.values() #access to every values in the dictionary
#sorting by the alphabetic order
sorted(course.keys())
sorted(course.values())
#update and mutate dictionaries
#assign it a new value using =, override in the dictionary
course['teacher'] = 'treasure'
course['level'] = 'intermediate'
#create a new key-value pair inside the dictionary because no match at the original one
course['stages'] = 2
#del - the value you want to remove, delete
del(course['stages'])
#iterating - iterate over using for loop
for item in course:
print(item) #only the keys
print(couse[item]) #only the values
# .items() method to list tuples that represent key value pairs
print(course.items())
#[('teacher': 'ashley'), ('title': 'dictionaries'), ('level': 'beginner')]
for key, value in course.items(): #first element assigned to key, second element assigned to value
print(key)
print(value)
#one to print the key and one to print the value of the current item.
pets = {'name':'Ernie', 'animal':'dog', 'breed':'Pug', 'age':2}
for key, value in pets.items():
print(key)
print(value)
# exercises
# iterate over all the key:value pairs in the student dictionary.
student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}
for key, val in student.items():
print(key)
print(value)
# iterate over only the keys in the student dictionary.
student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}
for key in student.keys():
print(key)
# iterates over only the values in the student dictionary.
student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}
for val in student.values():
print(val)
| true |
06d495ba3b49eadafdc696e0d71852bd140932d9 | hanwenzhang123/python-note | /basics/09-multidimensional.py | 1,335 | 4.15625 | 4 | travel_expenses = [
[5.00, 2.75, 22.00, 0.00, 0.00],
[24.75, 5.50, 15.00, 22.00, 8.00],
[2.75, 5.50, 0.00, 29.00, 5.00],
]
print("Travel Expenses: ")
week_number = 1
for week in travel_expenses:
print("* week #{}: ${}".format(week_number, sum(week)))
week_number += 1
# console
lens(travel_expenses) # 3
travel_expenses[0]
# [5.00, 2.75, 22.00, 0.00, 0.00]
travel_expenses[0][1]
# 2.75
# exercise
bradys = [
["Marsha", "Carol", "Greg"],
["Jan", "Alice", "Peter"],
["Cindy", "Mike", "Bobby"],
]
# Which of the following options would return "Alice"?
# bradys[1][1] # it is zero based
# The first dimension is group, the second is group members.
# Loop through each group and output the members joined together with a ", " comma space as a separator
# Then print out see only groups that are trios, you know 3 members.
musical_groups = [
["Ad Rock", "MCA", "Mike D."],
["John Lennon", "Paul McCartney", "Ringo Starr", "George Harrison"],
["Salt", "Peppa", "Spinderella"],
["Rivers Cuomo", "Patrick Wilson", "Brian Bell", "Scott Shriner"],
["Chuck D.", "Flavor Flav", "Professor Griff", "Khari Winn", "DJ Lord"],
["Axl Rose", "Slash", "Duff McKagan", "Steven Adler"],
["Run", "DMC", "Jam Master Jay"],
]
for group in musical_groups:
print(", ".join(group))
break
for tri in musical_groups:
if len(tri) == 3:
print(", ".join(tri))
| true |
0dc96256d6a7aad684d99fd4e8cfcc126f084484 | hanwenzhang123/python-note | /oop-python/26-construction.py | 1,652 | 4.4375 | 4 | # @classmethod - Constructors, as most classmethods would be considered
# A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
# Decorators are usually called before the definition of a function you want to decorate.
# @classmethod - The factory design pattern is mostly associated with which method type in Python?
# __new__ - override to control the construction of an immutable object
# type() - it will give me the class of an instance
# books.py
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return '{} by {}'.format(self.title, self.author)
class Bookcase:
def __init__(self, books = None): #default value
self.books = books
@classmethod #marks the method as belonging to the class and makes the method assessable from the class
def create_bookcase(cls, book_list):
books = []
for title, author in book_list:
books.append(Book(title, author))
return cls(books)
# exercise
# Below is a class called DreamVacation that holds a location and list of activities.
# Create a @classmethod called rome that will return a new DreamVacation instance with cls() with the following arguments: location = 'Rome' and activities list = ['visit the Colosseum', 'Eat gelato'].
class DreamVacation:
def __init__(self, location, activities):
self.location = location
self.activities = activities
@classmethod
def rome(cls):
return cls('Rome', ['visit the Colosseum', 'Eat gelato'])
| true |
5c3fdbafac312e38a471b9f62bd03d3c440fdab8 | hanwenzhang123/python-note | /file-system/02-creating-paths.py | 1,037 | 4.28125 | 4 | >>> import os
>>> os.getcwd()
>>> os.path.join(os.getcwd(), 'backups') #join to a new directory called backups
>>> os.path.join(os.getcwd(), '...', 'backups')
>>> import pathlib
>>> path = pathlib.PurePath(os.getcwd())
>>> path2 = path / 'examples' / 'paths.txt' # a txt in the example directory of current path
>>> path2.parts #gets all the tuples
>>> path2.root #'/'
>>> path2.parents[2] #PurePosixPath('/~~/~~/~~') the first three
>>> path2.name # the final name here is paths.txt
>>> path2.suffix # the final extension here is .txt
#exercise
If I'm using os.path.join(), do I need to provide the separator between path pieces?
Nope
Complete the following code snippet to get to the examples/python/ directory inside of the current directory:
os.path.join(os.getcwd(), "examples", "python")
When using Pathlib, is this a valid way to make a path? Yes
partial_path / "examples" / "pathlib.txt"
I need to get to the directory above the one I'm currently in. Finish this code snippet for me:
os.path.join(os.getcwd(), "..")
| true |
b9041a9ed771bec9e539f893a62dff904db0b6bb | hanwenzhang123/python-note | /basics/06-lists.py | 2,117 | 4.34375 | 4 | # lists are a data structure that allow you to group multiple values together in a single container.
# lists are mutable, we can change them, data type not matter
# empty string literal - ""
# empty list literal - []
# .append() - append items, modify exsiting list
# .extend() - combine lists
# ~ = ~ + ~ - combine and make a new list, not affecting the original one
# indexing in Python is 0-based
# python -i ~.py - -i: makes python docs interactive
# .insert(#, '~') - Insert adds elements to a specific location, and the first element is 0.
# .insert(0, '~') - insert to the beginning of the list
# You can access a specific character on a String by using an index, but you cannot change it.
# '\N{~}' - add Unicode in python
# del - delete, only the label not the value, you can still use and access the value
#.pop() - delete the last item and you can also put in an index number
# meeting.py
attendees = ['Ken', 'Alena', 'Treasure']
attendees.append('Ashley')
attendees.extent(['James', 'Guil'])
optional_invitees = ['Ben', 'Dave']
potential_attendees = attendees + optional_invitees
print('there are', len(potential_attendees), 'attendees currently') #8
# wishlist.py
books = [
"Learning Python: Powerful Object-Oriented Programming - Mark Lutz",
"Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart",
"Python for Data Analysis - Wes McKinney",
"Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho",
"Python for Kids: A Playful Introduction To Programming - Jason R. Briggs",
"Hello Web App: Learn How to Build a Web App - Tracy Osborn",
]
print("suggested_gift: {}".format(books[0]))
python -i wishlist.py # -i: makes python docs interactive
books[0] #first element
books[-1] #last element
books[len(books) -1] #last element
books.insert(0, 'learning Python: powerful object-oriented programming')
books[0] += ' - Mark Lutz'
# What is stored in the variable advisor? - "Rasputin"
surname = "Rasputin"
advisor = surname
del surname
# del just deletes the label, not the value. surname is no longer available, but advisor still is.
| true |
0137094b13ee42c90786874c681db1d6066ea92e | hanwenzhang123/python-note | /basics/46-comprehensions.py | 1,680 | 4.625 | 5 | Comprehensions let you skip the for loop and start creating lists, dicts, and sets straight from your iterables.
Comprehensions also let you emulate functional programming aspects like map() and filter() in a more accessible way.
number range (5, 101) # we have numbers 5 to 100
#loop
halves = []
for num in nums:
halves.append(num/2)
#comprehension
halves = [num/2 for num in nums] # result returns same as the loop
#examples
print([num for nums in range(1, 101) if num % 3 == 0])
rows = range(4)
cols = range(10)
[(x, y) for y in rows for x in cols]
[(letter, number) for number in range (1, 5) for letter in 'abc']
#zip takes two or more iterables and gives back one item from each iterable at the same index position
#we can loop through that zip to get these two items or three items or four items, however iterables put in to it at a time
{number: letter for letter, number in zip('abcdefghijklmnopqrstuvwxyz', range(1, 27))} # {1: 'a', 2: 'b' ~~~~}
{student: point for student, points in zip(['Kenneth', 'Dave', 'Joy'], [123, 456, 789])} # {'Kenneth': 123, ~~~~~}
#fizzbuzz game
total_nums = range(1, 101)
fizzbuzzes = {
'fizz': [n for n in total nums if n % 3 == 0],
'buzz': [n for n in total nums if n % 7 == 0]
}
fizzbuzzes = {key: set(values) for key, value in fizzbuzzes.item()} #we come out sets {}
fizzbuzzes['fizzbuzz'] = {n for n in fizzbuzzes['fizz'].intersection(fizzbuzzes['buzz'])}
fizzbuzzes['fizzbuzz'] #{42, 84, 21, 63}
{round(x/y) for y in range (1, 11) for x in range (2, 21)} #set - output is unique
[ound(x/y) for y in range (1, 11) for x in range (2, 21)] #list - more number/repeat, much more bigger than set
| true |
f22d3f4e04543a28fb334a96c30727f1b6ff025f | jackyho30/Python-Assignments | /BMI calculator Jacky Ho.py | 236 | 4.21875 | 4 | weight = input ("Please enter your weight (kg): ")
height = input ("Please enter your height (cm): ")
height2 = float (height) / 100
bmi = weight / height2 ** 2
print "Your Body Mass Index (BMI) is = %.1f" % bmi, "kg/m^2"
| true |
06d139b1861e7da522b21caade0f44db78270ffe | jackyho30/Python-Assignments | /Computer guessing random number.py | 2,937 | 4.21875 | 4 | """ Author: Jacky Ho
Date: November 10th, 2016
Description: You think of a number between 1-100 and the computer guesses your number, while you tell him if it's higher or lower"""
import random
def main():
"""The computer attempts to guess the number that you guess and you tell it if its low, correct, or high"""
while True:
try:
print "Hello! Think of a number between 1 and 100 and I will guess it! "
guess = 50
low=0
high=100
while True:
try:
print "My guess is", guess
print "Am I?\n1. Too low\n2. Correct\n3. Too high"
ans = int(raw_input ("Which one? "))
ans = int(ans)
if ans != 1 and ans != 2 and ans != 3:
print "That is an invalid option."
continue
elif ans == 1:
if guess > low:
low = guess
if high - low == 1:
low = guess
guess = toolow(low,high)
print "The number you are thinking of must be", guess
else:
toolow(low,high)
guess = toolow(low,high)
elif ans == 2:
print "Yay I win!"
break
elif ans == 3:
if guess < high:
high = guess
if high - low == 1:
high = guess
guess = toohigh(low,high)
print "The number you are thinking of must be", guess
else:
toohigh(low,high)
guess = toohigh(low,high)
except ValueError:
print "That's not a number!"
continue
except ValueError:
print "That's not a number!"
continue
break
def toolow(low,high):
"""The parameters are the lowest and highest values that you have indicated
and the computer generates a new guess based on your requirements and returns
the new guess as the return value"""
newguess= random.randint (low+1,high-1)
return newguess
def toohigh(low,high):
"""The parameters are the lowest and highest values that you have indicated
and the computer generates a new guess based on your requirements and returns
the new guess as the return value"""
newguess= random.randint (low+1,high-1)
return newguess
main()
| true |
1aa47746192b62188458fbe1192a203bd15f8532 | rajkamal-v/PythonLessons1 | /dictonary_data_type.py | 1,445 | 4.1875 | 4 | #A dictionary is a collection which is unordered, changeable and indexed.
#In Python dictionaries are written with curly brackets, and they have keys and values.
#{1,3,4} - set
#doesnt take duplicate keys, if duplicate is given, it will take the latest
dict_1 = {"name":"kamal","age":36}
print(len(dict_1))
print(dict_1)
print(dict_1["name"])
print(dict_1["age"])
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily["child3"]["name"])
print(myfamily.get("child3"))
print(myfamily.get("child3").get("year"))
dict_1["age"] = 20
print(dict_1)
for k in dict_1:
print(dict_1.get(k))
for key in dict_1:
print(key)
for key in dict_1:
print(key,":",dict_1.get(key))
for value in dict_1.values():
print(value)
for key in dict_1.keys():
print(key)
print(dict_1.items())
for key,value in dict_1.items():
print(key,value)
dict_1.pop('age')
print(dict_1)
tuple_1 = ('name','age','sal')
values = 0
dict_2 = dict.fromkeys(tuple_1,values)
print(dict_2)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
print(id(1964))
print(id("year"))
print(id({
"brand": "Ford",
"model": "Mustang",
"year": 1964
}))
a =1964
print(id(a)) | true |
5561bffdc226cb929ee05f74bcbc184f36bb6d32 | MaxMcF/data_structures_and_algorithms | /challenges/repeated_word/repeated_word.py | 823 | 4.21875 | 4 | from hash_table import HashTable
def repeated_word(string):
"""This function will detect the first repeated word in a string.
Currently, there is no handling for punctuation, meaning that if the word
is capitalized, or at the end of a senctence, it will be stored as a different word.
If the string contains no repeats, it return 'No Duplicate'
ARGS:
A string of words
RETURN:
The first duplicated word in the input string.
"""
ht = HashTable()
dup_bool = True
while dup_bool:
word = string.split(' ', 1)
try:
success = ht.set(word[0], None)
except:
return word[0]
if success is False:
return word[0]
try:
string = word[1]
except:
return 'No Duplicate'
| true |
a9f772545af1ba2fb1e4ca48c4b8ad390d600794 | laurieskelly/lrs-bin | /euler/euler_4.py | 1,078 | 4.25 | 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.
digits = 3
def largest_palindromic_product(ndigits):
largest = 10**ndigits - 1
if is_palindrome(largest**2):
return largest**2
f1 = largest - 1
largest_palindrome = 0
while f1 > 10**(ndigits-1):
# print 'New f1: ',f1
# for each integer (f2) from largest down to f1
for f2 in xrange(largest,f1,-1):
# print f1, f2, f1*f2
# check if f1 * f2 is a palindrome
if is_palindrome(f1*f2):
if f1 * f2 > largest_palindrome:
largest_palindrome = f1*f2
f1 -= 1
return largest_palindrome
def is_palindrome(n):
strn = str(n)
i = 0
while i <= len(strn)/2:
if strn[i] != strn[-(i+1)]:
return False
i += 1
return True
largest = largest_palindromic_product(digits)
print 'answer:', largest | true |
d3f0a250349a42802aa835e9683dd7fe51d3ac6e | trent-hodgins-01/ICS3U-Unit6-04-Python | /2d_average.py | 1,351 | 4.53125 | 5 | # !/user/bin/env python3
# Created by Trent Hodgins
# Created on 10/26/2021
# This is the 2D Average program
# The program asks the user how many rows and cloumns they want
# The program generates random numbers between 1-50 to fill the rows/columns
# The program then figures out and displays the average of all the numbers
import random
def sum_of_numbers(passed_in_2D_list):
# this function adds up all the elements in a 2D array
total = 0
for row_value in passed_in_2D_list:
for single_element in row_value:
total += single_element
return total
def main():
# this function uses a 2D array
a_2d_list = []
# input
rows = int(input("How many rows would you like: "))
columns = int(input("How many columns would you like: "))
print("")
for loop_counter_rows in range(0, rows):
temp_column = []
for loop_counter_columns in range(0, columns):
a_random_number = random.randint(0, 50)
temp_column.append(a_random_number)
print("{0} ".format(a_random_number), end="")
a_2d_list.append(temp_column)
print("")
divide = rows * columns
average = sum_of_numbers(a_2d_list) / divide
print("\nThe average of all the numbers is: {0} ".format(average))
print("\nDone")
if __name__ == "__main__":
main()
| true |
c838693c51ae2847566c0e635f80f05db7a215c1 | Romny468/FHICT | /Course/3.2.1.9.py | 282 | 4.21875 | 4 |
word = input("enter a word: ")
while word != 0:
if word == "chupacabra":
print("You've successfully left the loop.")
break
else:
print("Ha! You're in a loop till you find the secret word")
word = input("\ntry again, enter another word: ") | true |
02d6002df846e2f11ee5a5e7345f9df1343db18e | Romny468/FHICT | /Course/3.2.1.6.py | 394 | 4.15625 | 4 | import time
# Write a for loop that counts to five.
# Body of the loop - print the loop iteration number and the word "Mississippi".
# Body of the loop - use: time.sleep(1)
# Write a print function with the final message.
for i in range(6):
print(i, "Mississippi")
time.sleep(1)
if i == 5:
print("Ready or not, here I come!")
i = 0
| true |
cf86dabe4955604b47ccc0b7e3881978291827f1 | JonathanGamaS/hackerrank-questions | /python/find_angle_mbc.py | 372 | 4.21875 | 4 | """
Point M is the midpoint of hypotenuse AC.
You are given the lengths AB and BC.
Your task is to find <MBC (angle 0°, as shown in the figure) in degrees.
"""
import math
def angle_finder():
AB = int(input())
BC = int(input())
MBC = math.degrees(math.atan(AB/BC))
answer = str(int(round(MBC)))+'°'
print(answer)
return answer
angle_finder() | true |
d0fb9d8752231bc0728a0572e1045eb7694af8c1 | JonathanGamaS/hackerrank-questions | /python/string_formatting.py | 462 | 4.15625 | 4 | """
Given an integer, N, print the following values for each integer I from 1 to N:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
"""
def print_formatted(number):
b = len(str(bin(number)[2:]))
for i in range(1,number+1):
print("{0}{1}{2}{3}".format(str(i).rjust(b),str(oct(i)[2:]).rjust(b+1),str(hex(i)[2:].upper()).rjust(b+1),str(bin(i)[2:]).rjust(b+1)))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
| true |
ec7ba04208c18b82e5f1b1924183b5a0c5ab2166 | ekeydar/python_kids | /lists/rand_list_ex.py | 637 | 4.125 | 4 | import random
def rand_list3():
"""
return list of 3 random items between 1 to 10 (include 1 and include 10)
"""
# write your code here
# verify that your function returns
# 3 numbers
# not all items of the list are the same always
# numbers are in 1,2,3,4,5,6,7,8,9,10
def main():
assert len(rand_list3()) == 3, 'list should be in size 3'
items = set()
for x in range(1000):
items |= set(rand_list3())
assert items == set(range(1, 11)), 'Probably something wrong with your call to random.randint'
print('Everything OK, well done!')
if __name__ == '__main__':
main()
| true |
69edca7bcdea35c28a3917d545dcbcab80e18661 | MugenZeta/PythonCoding | /BirthdayApp/Program.py | 1,260 | 4.4375 | 4 | #Birthday Program
import datetime
def printH():
User_Name = input("Hello. Welcome to the Birthday Tracker Application. Please enter your name: ")
def GetBirthDay():
#User Inputes Birthday
print()
DateY = input("Please put the year you where born [YYYY]: ")
DateM = input("Please put the year you where born [MM]: ")
DateD = input("Please put the year you where born [DD]: ")
#tranform string to int.
year = int(DateY)
month = int(DateM)
day = int(DateD)
bday = datetime.date(year,month,day)
return bday
#calculate days till birthday from today pass in 2 days
def CalDaysinDates(Original_Year,Target_Year):
This_Year = datetime.date(Target_Year.year,Original_Year.month, Original_Year.day)
dt = This_Year - Target_Year
return dt.days
def printBday(days):
if days > 0:
print("You have {} days until your birthday!".format(-days))
elif days < 0:
print("Your Birthday passed {} days ago!".format(days))
else:
print("Happy Birthday")
#Ties all functions together in execution oder
def main():
printH()
bday = GetBirthDay()
today = datetime.date.today()
Number_of_days = CalDaysinDates(bday, today)
printBday(Number_of_days)
main()
| true |
40a210b5eba4a886a5056ce573276175196e98b1 | anatulea/PythonDataStructures | /src/Stacks and Queues/01_balanced_check.py | 1,475 | 4.3125 | 4 | '''
Problem Statement
Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these, no spaces words or numbers. As a reminder, balanced parentheses require every opening parenthesis to be closed in the reverse order opened. For example ‘([])’ is balanced but ‘([)]’ is not.
You can assume the input string has no spaces.
'''
def balance_check(s):
if len(s)%2 != 0:
return False
opening = set('({[')
matches = ([ ('(',')'), ('[',']'), ('{','}')])
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (last_open, paren) not in matches:
return False
return len(stack) == 0 # returns true if all mached
print(balance_check('[]'))
print(balance_check('[](){([[[]]])}'))
print(balance_check('()(){]}'))
def balance_check2(s):
chars = []
matches = {')':'(',']':'[','}':'{'}
for c in s:
if c in matches:
if chars.pop() != matches[c]:
return False
else:
chars.append(c)
return chars == []
print(balance_check2('[]'))
print(balance_check2('[](){([[[]]])}'))
print(balance_check2('()(){]}')) | true |
c07bef00e1f0ea19ca1f09e5de220f5e6ff2e3df | kuba777/sql | /cars7.py | 1,688 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Using the COUNT() function, calculate the total number of orders for each make and
# model.
# Output the car’s make and model on one line, the quantity on another line, and then
# the order count on the next line.
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("SELECT make, model FROM orders")
rows1 = c.fetchall()
#print type(rows)
make = []
model = []
for r in rows1:
make.append(r[0])
model.append(r[1])
a = list(set(model))
a.sort()
c.execute("SELECT DISTINCT orders.make, inventory.quantity, inventory.molde from orders, inventory WHERE inventory.molde = orders.model ORDER BY inventory.molde ASC")
row = c.fetchall()
#print row[1]
count = 0
#print a
for r in a:
c.execute("SELECT DISTINCT count(order_date) FROM orders WHERE model =" + "'" + r + "'" + "")
row2 = c.fetchone()
print "Make and model: ", row[count][0], row[count][2]
print "Qty: ", row[count][1]
print "# of orders: ", row2[0]
print
count = count + 1
# for r in list(set(model)):
# c.execute("SELECT count(order_date) FROM orders WHERE model = " + "'" + r + "'")
# row2 = c.fetchone()
# print "make and model: ", row[0], row[2]
# print "qty: ", row[1]
# print "order count: ", row2[0]
# print
# for r in list(set(make)):
# c.execute("SELECT count(order_date) FROM orders WHERE make = " + "'" + r + "'")
# results = c.fetchone()
# print r, results[0]
| true |
16e12a8c252bc7e83eebe5e13864b871cc9451d7 | taylorhcarroll/PythonIntro | /debug.py | 901 | 4.15625 | 4 | import random
msg = "Hello Worldf"
# practice writing if else
# if msg == "Hello World":
# print(msg)
# else:
# print("I don't know the message")
# # I made a function
# def friendlyMsg(name):
# return f'Hello, {name}! Have a great day!'
# print(friendlyMsg("james").upper())
# print(friendlyMsg("clayton"))
# accepting user input
print("What's your name")
name = str(input())
# Random Number Guessing Game
rand = random.randint(1, 10)
print(f"Alright {name}, Guess a number between 1 and 10")
x = 0
while x < 3:
numberGuessed = int(input())
if numberGuessed == rand:
print(f"YOU GOT IT. THE NUMBAH WAS {rand}")
break
elif numberGuessed < rand:
print(f"Guess a higher number than {numberGuessed}")
x += 1
elif numberGuessed > rand:
print(f"guess a lower number {numberGuessed}")
x += 1
if x == 3:
print("You've lost!")
| true |
df249f359269c4357e81b95506316c4481928da6 | mani67484/FunWithPython | /calculate_taxi_fare_2.py | 2,437 | 4.40625 | 4 | """
After a lengthy meeting, the company's director decided to order a taxi to take the staff home. He ordered N cars
exactly as many employees as he had. However, when taxi drivers arrived,
it turned out that each taxi driver has a different fare for
1 kilometer.The director knows the distance from work to home for each employee (unfortunately,
all employees live in different directions, so it is impossible to send two employees in one car).
Now the director wants to select a taxi for each employee.
Obviously, the director wants to pay as little as possible.
Input format: The first line contains N numbers through a space
specifying distances in kilometers from work to the homes of employees.
The second line contains N fares for one kilometer in a taxi.
All distances are unique and all rates are unique too.
Output format: Give taxi cars integer indexes starting from zero.
For each employee print the index of the taxi they should choose.
Note: Loops, iterations, and list comprehensions are forbidden in this task.
------------------------
Input data:
10 20 30
50 20 30
Program output:
0 2 1
------------------------
Input data:
10 20 1 30 35
1 3 5 2 4
Program output:
4 1 2 3 0
"""
def calculate_original_index_of_taxi_fare():
result_index_list = list(map(get_original_index, list_of_employees_total_home_distance_in_km))
print(*result_index_list, sep=" ")
def get_original_index(employees_total_home_distance_in_km):
return list_of_tax_fare_per_km.index(zipped_dictionary[employees_total_home_distance_in_km])
def collect_data():
global sorted_list_of_employees_total_home_distance_in_km, \
sorted_list_of_taxi_fares_per_km, \
list_of_tax_fare_per_km,\
list_of_employees_total_home_distance_in_km,\
zipped_dictionary
user_input1 = input()
user_input2 = input()
list_of_employees_total_home_distance_in_km = list(map(int, user_input1.split()))
sorted_list_of_employees_total_home_distance_in_km = sorted(list_of_employees_total_home_distance_in_km,
reverse=True)
list_of_tax_fare_per_km = list(map(int, user_input2.split()))
sorted_list_of_taxi_fares_per_km = sorted(list_of_tax_fare_per_km)
zipped_dictionary = dict(zip(sorted_list_of_employees_total_home_distance_in_km, sorted_list_of_taxi_fares_per_km))
calculate_original_index_of_taxi_fare()
collect_data()
| true |
d8445e9f19318af7b9afc98acde565443f2e7713 | SindriTh/DataStructures | /PA2/my_linked_list.py | 2,601 | 4.21875 | 4 | class Node():
def __init__(self,data = None,next = None):
self.data = data
self.next = next # Would it not be better to call it something other than next, which is an inbuilt function?
class LinkedList:
def __init__(self):
self._head = None
self._tail = None
self._size = 0
# O(1)
def push_back(self, data):
''' Appends the data to the linked list '''
new_node = Node(data)
if self._size == 0:
self._head = new_node
self._tail = new_node
else:
self._tail.next = new_node
self._tail = self._tail.next
self._size +=1
return
# O(1)
def push_front(self,data):
''' Prepends the data to the linked list '''
new_node = Node(data,self._head)
self._head = new_node
if self._size == 0:
self._tail = self._head
self._size += 1
# O(1)
def get_size(self):
''' Returns the size of the linked list '''
return self._size
# O(1)
def pop_front(self):
''' Removes the first node of the linked list and returns it '''
if self._head == None:
return
node = self._head
self._head = self._head.next
self._size -= 1
return node.data
# O(n)
def pop_back(self):
''' Removes the last node of the linked list and returns it '''
returnnode = self._tail
if self._tail == self._head:
self._head, self._tail = None,None
else:
node = self._head
while node.next != self._tail:
node = node.next
node.next = None
self._tail = node
self._size -=1
return returnnode.data
# O(n)
def __str__(self):
''' Handles printing of the linked list '''
node = self._head
returnstring = ""
while node != None:
returnstring += str(node.data) + " "
node = node.next
return returnstring[:-1]
if __name__ == "__main__":
listi = LinkedList()
listi.push_back("1")
listi.push_back("2")
listi.push_front("0")
listi.push_back("3")
listi.push_back("4")
print(listi)
print(f"oh boi I popped one! {listi.pop_front()}")
print(listi)
print(f"Popped one from the back {listi.pop_back()}")
print(listi)
print(f"Popped one from the back {listi.pop_back()}")
print(f"Popped one from the back {listi.pop_back()}")
print(f"Popped one from the back {listi.pop_back()}")
print(listi) | true |
c3b0de9516118a12593fdb1c33288105f5720caf | Heena3093/Python-Assignment | /Assignment 1/Assignment1_7.py | 558 | 4.25 | 4 | #7.Write a program which contains one function that accept one number from user and returns true if number is divisible by 5 otherwise return false.
#Input : 8 Output : False
#Input : 25 Output : True
def DivBy5(value):
if value % 5 == 0:
return True
else:
return False
def main():
print ("Enter number ")
no=int(input())
ret=DivBy5(no)
if no % 5 == 0:
print("Number is divisible by 5")
else:
print("Number is not divisible by 5 ")
if __name__=="__main__":
main() | true |
f7cbd0159a129526f623685f9edb077d805eefd3 | Heena3093/Python-Assignment | /Assignment 3/Assignment3_4.py | 836 | 4.125 | 4 | #4.Write a program which accept N numbers from user and store it into List. Accept one another number from user and return frequency of that number from List.
#Input : Number of elements : 11
#Input Elements : 13 5 45 7 4 56 5 34 2 5 65
#Element to search : 5
#Output : 3
def DisplayCount(LIST,x):
cnt = 0
for i in range(len(LIST)):
if LIST[i]==x:
cnt=cnt+1
return cnt
def main():
arr=[]
print("Enter the number of elements:")
size=int(input())
for i in range(size):
print("The elemnts are :",i+1)
no=int(input())
arr.append(no)
print("Display the Elements are:",arr)
print("Elemnt to the search")
no=int(input())
ret=DisplayCount(arr,no)
print("Number of count is :",ret)
if __name__=="__main__":
main() | true |
e11d7e50b4adf445696bea2e2bbd2623c89e3af9 | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Digits of a number.py | 1,664 | 4.25 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To analyze positive integers and present their characteristics.
#------------------------------------------------------------------------------#
again = "Y"
while again == "y" or again == "Y":
number = int(input("Please enter a positive integer: "))
while number <= 0:
number = int(input("Please re-enter a positive, non-zero, number: "))
count = 0
breakdown = number
leftover = 0
reverse = 0
Sum = 0
digitalroot = 0
maximum = 0
while breakdown != 0:
leftover = breakdown % 10
reverse = reverse * 10 + leftover
Sum = Sum + leftover
breakdown = breakdown // 10
count = count + 1
digitalroot = Sum
leftover = 0
for maximum in range(1, 21):
while digitalroot != 0:
leftover = leftover + (digitalroot % 10)
digitalroot = digitalroot // 10
digitalroot = leftover
leftover = 0
if digitalroot >= 0 and digitalroot <= 9:
maximum = 21
print("Your number has",count,"digits.")
print("The sum of these digits is",Sum,".")
print("The reverse of this number is",reverse,".")
print("The digital root of this number is",digitalroot,".")
if reverse == number:
print("This number also happens to be a palindrome!")
again = input("Would you like to analyse another number? (Y/N) ")
while not(again == "Y" or again == "N" or again == "y" or again == "n"):
again = input("Please enter if you would like to analyse another number. (Y/N) ")
print()
print()
print("Have a nice day!")
| true |
bdb7d0ff8b7c439147fc677ac68a71ec851d2f2c | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Parking Garage.py | 2,142 | 4.15625 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To create a program that will calculate the cost of parking
# at a parking garage.
#------------------------------------------------------------------------------#
again = "Y"
while again == "Y" or again == "y":
minutes = int(input("Please enter the amount of minutes you have parked for: "))
while minutes <= 0:
minutes = int(input("Please re-enter the amount of minutes you have parked for: "))
timeEntered = int(input("Now, please enter the time you have entered , in 24 hour format. (HHMM): "))
while timeEntered <= 0 or timeEntered > 2359 or timeEntered % 100 > 59:
timeEntered = int(input("Please enter a valid time you have entered at, in 24 hour format. (HHMM): "))
parkingPass = str(input("Finally, do you have a staff parking pass? (Y/N) "))
while not(parkingPass == "Y" or parkingPass == "N" or parkingPass == "y" or parkingPass == "n"):
parkingPass = str(input("Please re-enter if you have a parking pass or not. (Y/N) "))\
minutesEntered = (timeEntered // 100) * 60 + (timeEntered % 100)
price = 0
finalTime = minutesEntered + minutes
if finalTime >= 1080:
if minutesEntered > 1080:
price = 5
elif (1080 - minutesEntered) % 20 > 0:
price = ((((1080 - minutesEntered) // 20) + 1) * 3) + 5
else:
price = (((1080 - minutesEntered) // 20) * 3) + 5
elif minutes % 20 > 0:
price = ((minutes // 20) + 1) * 3
else:
price = (minutes // 20) * 3
if price > 28:
price = 28
if parkingPass == "Y" or parkingPass == "y":
if price > 8.5:
price = 8.5
print(" ")
print(" ")
print("The total cost of your parking visit is $%.2f" %price)
print(" ")
print(" ")
again = input("Would you like to calculate another time? (Y/N): ")
while not(again == "Y" or again == "N" or again == "y" or again == "n"):
again = input("Please re-enter if you want to calculate again. (Y/N): ")
print(" ")
print(" ")
print("Have a nice day!")
| true |
3a9bfeb8bf331298b613dc10f85cadd41199e5fb | 1sdc0d3r/code_practice | /leetcode/Python/backspace_compare.py | 968 | 4.15625 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# Note that after backspacing an empty text, the text will continue empty.
def backSpaceCompare(S, T):
def back(x):
newString = list()
for l in x:
if l is not "#":
newString.append(l)
elif l is "#" and len(newString) > 0:
newString.pop()
return "".join(newString)
if back(S) == back(T):
return True
return False
s1 = "ab#c"
t1 = "ad#c"
s2 = "ab##"
t2 = "c#d#"
s3 = "a##c"
t3 = "#a#c"
s4 = "a#c"
t4 = "b"
s5 = "y#fo##f"
t5 = "y#f#o##f"
s6 = "hd#dp#czsp#####"
t6 = "hd#dp#czsp#######"
print(backSpaceCompare(s1, t1)) # True
# print(backSpaceCompare(s2, t2)) # True
# print(backSpaceCompare(s3, t3)) # True
# print(backSpaceCompare(s4, t4)) # False
# print(backSpaceCompare(s5, t5)) # True
# print(backSpaceCompare(s6, t6)) # True
| true |
889195f0a205ab24f651a68ae067d356518c4eef | wellesleygwc/2016 | /mf/Sign-in-and-Add-user/app/db.py | 1,406 | 4.15625 | 4 | import sqlite3
database_file = "static/example.db"
def create_db():
# All your initialization code
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Create a table and add a record to it
cursor.execute("create table if not exists users(username text primary key not null, password text not null)")
cursor.execute("insert or ignore into users values ('Meghan', 'Flack')")
# Save (commit) the changes
connection.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
connection.close()
def check_password(username, password):
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Try to retrieve a record from the users table that matches the usename and password
cursor.execute("select * from users where username='%s' and password='%s'" % (username, password))
rows = cursor.fetchall()
connection.close()
return len(rows) > 0
def create_user(username, password):
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Try to retrieve a record from the users table that matches the usename and password
cursor.execute("insert or ignore into users values ('%s', '%s')" % (username, password))
connection.commit()
connection.close()
| true |
b9b89f34dc087eb641cda31afde4da5022d41968 | RakeshNain/TF-IDF | /TF-IDF/task4_30750008.py | 591 | 4.1875 | 4 | """
This function is finding most suitable document for a given term(word)
"""
import pandas as pd
def choice(term, documents):
# finding IDF of given term(word)
idf = documents.get_IDF(term)
# creating a new DataFrame of the term which contain TF-IDF instead of frequencies
tf_idf_df = documents.data[term]*idf
# finding the maximum value is the new Data Frame
max_v = tf_idf_df.max()
# finding the row name(book name) corresponding to the highest value
book_choice = tf_idf_df[tf_idf_df == max_v].index[0]
return book_choice
| true |
669d633b331c32363512ee50b23e414edece7277 | ElliottKasoar/algorithms | /bubblesort.py | 1,259 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 17:48:06 2020
@author: Elliott
"""
# Bubble sort algorithm
import numpy as np
import time
# Bubble sort function.
# Compares adjacent pairs of elements and swaps if first element is larger
# Repeats this (length of array - 1) times, each time one fewer element must be
# considered.
def bubble_sort(arr):
length = len(arr)
for i in range(length - 1):
for j in range(length - i - 1):
if (arr[j] > arr[j+1]):
temp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = temp
# print(arr)
# Main
def main():
ol = np.linspace(1,1000,1000) #Ordered list to compare with at end.
ul = ol.copy() #Copy else just renames ol as ul and will still be shuffled
np.random.shuffle(ul) #Shuffle to create unodered list
# print("ol: ", ol)
# print("ul: ", ul)
#Run main code
t1= time.time()
bubble_sort(ul)
t2= time.time()
dt = t2 - t1
# print("Final list: ", ul)
if (np.array_equal(ol, ul)):
print("Sorted!")
print("Time taken = ", dt)
else:
print("Not sorted.")
#Run code
main() | true |
1d2ace87d805ecaa811e860f29f163a26c85c429 | padmacho/pythontutorial | /collections/dict/dict_demo.py | 1,585 | 4.6875 | 5 | capitals = {"india":"delhi", "america":"washington"}
print("Access values using key: ", capitals["india"])
name_age = [('dora', 5), ('mario', 10)]
d = dict(name_age)
print("Dict", d)
d = dict(a=1, b=2, c=3)
print("Dict", d)
# copying method 1
e = d.copy()
print("Copied dictionary e: ", e)
# copying method 2
f = dict(d)
print("Copied dictionary f: ", f)
# updating dict
g = dict(a=-1, b=-2)
print("d", d)
print("g", g)
d.update(g)
print("Updated dictionary d with g", d)
# Iterating through dictionary
d = dict(a=1, b=2, c=3)
# Note key are retrieved in arbitrary order
for key in d:
print(d[key])
# iterate through values
# There is no efficient way to get keys from values
print("Get values for dictionary with out keys")
for value in d.values():
print(value)
print("Get items for dictionary")
# Each key-value pair in a dictionary is called an item, and we can get ahold of an iterable view of the items using the items() dictionary method.
for key, value in d.items():
print(key, value)
# member ship operator works only on keys
d = dict(a=1, b=2, c=3)
print("a" in d)
print("e" in d)
# Remove an item from the dictionary
d = dict(a=1, b=2, c=3)
print("d", d)
print("Removing item c from dictionary")
del d['c']
print(d)
# Keys are immutable and values can be modified
d = dict(a=1, b=2, c=3)
print("d", d)
print("Modify element value of item a")
d["a"] = -1
print("d", d)
# Pretty printing
print("Pretty printing")
from pprint import pprint as pp
d = dict(a=1, b=2, c=3)
pp(d)
| true |
679d78cde339c2ab96b05a34b983f9530404d4fa | padmacho/pythontutorial | /scopes/assignment_operator.py | 311 | 4.15625 | 4 | a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
| true |
e14df3b6a6de916386a171b5095f282f2a2885be | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /23. Python File IO Basics.py | 755 | 4.28125 | 4 | ########### Python File IO Basics #########
# Two types of memory
# 1. Volatile Memory : Data cleared as System Shut Down
# Example : RAM
# 2. Non-Volatile Memory : Data remains saved always.
# Example : Hard Disk
# File : In Non-Volatile Memory we store Data as File
# File may be text file,binary file(Ex - Image,mp3),etc.
# Different Modes of Opening files in Python
"""
"r" - Open file for reading - Default mode
"w" - Open a file for writing
"x" - Create file if not exists
"a" - Add more content to a file/ append at end in file
"t" - open file in text mode - Default mode
"b" - open file in binary mode
"+" - for update (read and write both)
"""
# Question of the tutorial:
# How to print docstring of func1()
# Answer : print(func1.__doc__) | true |
9892c365ccbe67416408836343251224372f854f | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /15. While Loops In Python.py | 506 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# Assuming code inside for and while loop is same
# Both While and for loop takes almost equal time
# As both converted into same machine code
# So you can use any thing which is convenient | true |
658bf19caa15b39086e4166c6bd43b8f026939e4 | evlevel/lab_6_starting_repo | /lab_6_starting/wordstats.py | 794 | 4.28125 | 4 | #
# wordstats.py:
#
# Starting code for Lab 6-4
#
# we'll learn more about reading from text files in HTT11...
FILENAME = 'words.txt'
fvar = open(FILENAME, 'r') # open file for reading
bigline = fvar.read() # read ENTIRE file into single string
# what happens when you print such a big line?
# try it, by uncommenting next line
# print (bigline)
# the following print illustrates the printf-formatting approach in Python
# # this is the "old way", and not discussed in our book...
# [L6-4a] total number of characters, including newlines
print("Number of characters is: %d" % len(bigline))
# [L6-4b] total number of words in the file
# hint: each word ends with a newline
# [L6-4c] average length of a word
# [L6-4d] count of 'e' in all words
# [L6-4e]
fvar.close()
| true |
015b5f6887cc692ae30fdef44d1fa87e8b74ae6b | toma-ungureanu/FII-Python | /lab1/ex1.py | 1,142 | 4.3125 | 4 | class Error(Exception):
"""Exception"""
pass
class NegativeValueError(Error):
"""Raised when the input value is negative"""
pass
class FloatError(Error):
"""Raised when the input value is negative"""
pass
def find_gcd_2numbers(num1, num2):
try:
if num1 < 0 or num2 < 0:
raise NegativeValueError
if isinstance(num1, float) or isinstance(num2, float):
raise FloatError
while num2:
num1, num2 = num2, num1 % num2
return num1
except (NegativeValueError, FloatError):
print("You didn't enter a positive integer")
def main():
numbers = []
while True:
try:
num = int(input("Enter an integer: "))
numbers.append(num)
except ValueError:
break
if len(numbers) < 2:
print("Please enter more values")
return 1
print(numbers)
main_num1 = numbers[0]
main_num2 = numbers[1]
gcd = find_gcd_2numbers(main_num1, main_num2)
for i in range(2, len(numbers)):
gcd = find_gcd_2numbers(gcd, numbers[i])
print(gcd)
return 0
main()
| true |
dc276b879b3045f27a3ae01b0984e82cf831f970 | toma-ungureanu/FII-Python | /lab5/ex5.py | 816 | 4.1875 | 4 | import os
def writePaths(dirname,filename):
file_to_write = open(filename, "w+", encoding='utf-8')
for root, dirs, files in os.walk(dirname):
path = root.split(os.sep)
file_to_write.write((len(path) - 1) * '---')
file_to_write.write(os.path.basename(root))
file_to_write.write("\n")
for file in files:
file_to_write.write(len(path) * '---')
file_to_write.write(os.path.basename(file))
file_to_write.write("\n")
def main():
try:
path = input(" Enter the desired path: ")
file_to_write_in = input(" Enter the file you want to write in: ")
if not os.path.isdir(path):
raise OSError
writePaths(path, file_to_write_in)
except OSError:
print(" Enter a directory!")
main()
| true |
f7fba7853ba6cd086384d43014fae831e5597215 | Dhruvish09/PYTHON_TUT | /Loops/function with argument.py | 1,111 | 4.5 | 4 | #Information can be passed into functions as arguments.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
#You can also send arguments with the key = value syntax.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
#If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
#You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
#To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
| true |
6d260adeec1de35945ff49f6cf3507881b93e724 | RavikrianGoru/py_durga | /byte_of_python/py_flowcontrol_func_modules/10_while_else.py | 674 | 4.125 | 4 | # while-else
# input() is builtin function. we supply input as string. Once we enter something and press kbd[enter] key.
# input() function returns what we entered as string.
# then we can convert into any format what we required.
pass_mark = 45
running = True
print('Process is started')
while running:
marks = int(input("Enter marks:"))
if marks == pass_mark:
print('you just passed')
elif marks < pass_mark:
print('you failed')
running = bool(int(input("Enter your option(1/0)")))
print(type(running), running)
else:
print("you passed")
else:
print("While is is completed")
print('Process is completed')
| true |
3f26b2ccfc2e70402b275e09a4aa6b9a7a4a7b8a | emma-ola/calc | /codechallenge.py | 1,015 | 4.40625 | 4 | # Days in Month
# convert this function is_leap(), so that instead of printing "Leap year." or "Not leap year." it
# should return True if it is a leap year and return False if it is not a leap year.
# create a function called days_in_month() which will take a year and a month as inputs
def is_leap(year):
""" The function takes a year and returns True if it is a leap year or False if it is not"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year, month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month > 12 or month < 1:
return "Invalid month entered."
if month == 2 and is_leap(year):
return 29
return month_days[month - 1]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
| true |
545f2e6bbc59b938c2e23b1c0a4ffbda28b5f2a9 | viveksyngh/Algorithms-and-Data-Structure | /Data Structure/Queue.py | 792 | 4.21875 | 4 | class Queue :
def __init__(self) :
"""
Initialises an empty Queue
"""
self.items = []
def is_empty(self) :
"""
Returns 'True' if Queue is empty otherwise 'False'
"""
return self.items == []
def enqueue(self, item) :
"""
Insert an item to the end of the Queue and Returns None
"""
self.items.append(0, item)
def dequeue(self) :
"""
Removes an item from the front end of Queue and Returns it
"""
return self.items.pop()
def size(self) :
"""
Returns the size (number of items) of the Queue
"""
return len(self.items)
#Tester Code
q = Queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
q.dequeue()
| true |
40cc7c6d18482056565687650ad8f77cf15208fd | AmitKulkarni23/OpenCV | /Official_OpenCV_Docs/Core_Operations/place_image_over_another_using_roi.py | 1,942 | 4.15625 | 4 | # Placing image over another image using ROI
# Use of bitwise operations and image thresholding
# API used
# cv2.threshold
# 1st arg -> gray scale image
# 2nd arg -> threshold value used to classify the images
# 3rd arg -> Value to be given if pixel value is more than threshold value
# 4th arg -> different styles of thresholding
###################################
import cv2
# File names for images
messi_file_name = "messi_barca.jpg"
opencv_logo_file_name = "opencv-logo.png"
# Read the images
messi_image = cv2.imread(messi_file_name)
opencv_image = cv2.imread(opencv_logo_file_name)
# Get the rows, columns and channels for opencv image
rows, columns, channels = opencv_image.shape
# Now create a region of interest in teh first image
# Top left corner
roi = messi_image[0:rows, 0:columns]
# Now perform image thresholding
# Image thresholding requires a gray scale image
opencv_image_gray = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2GRAY)
# Show opencv_image_gray
# cv2.imshow("OpenCV Gray Wimdow", opencv_image_gray)
# Actual image thresholding
ret, mask = cv2.threshold(opencv_image_gray, 10, 255, cv2.THRESH_BINARY)
# Calculate the inverse of mask as well
mask_inv = cv2.bitwise_not(mask)
# Lets display the thresholded image
# cv2.imshow("Thresholded Image", mask)
# print(roi)
# lets show teh region of interest
# cv2.imshow("ROI Window", roi)
# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
# cv2.imshow("img1_bg Window", img1_bg)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(opencv_image,opencv_image,mask = mask)
# cv2.imshow("img2_fg Window", img2_fg)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
messi_image[0:rows, 0:columns] = dst
# Final Dipslay
cv2.imshow("Mesi Image After Operation", messi_image)
# Wait for user input from keyboard
cv2.waitKey(0)
# Destroy all windows
cv2.destroyAllWindows()
| true |
9a7f222209e105a33d45217efb1e1f26656a4a87 | AndreasArne/python-examination | /test/python/me/kmom01/plane/plane.py | 877 | 4.5 | 4 | #!/usr/bin/evn python3
"""
Program som tar emot värden av en enhetstyp och omvandlar till motsvarande
värde av en annan.
"""
# raise ValueError("hejhejhej")
# raise StopIteration("hejhejhej")
print("Hello and welcome to the unit converter!")
hight = float(input("Enter current hight in meters over sea, and press enter: "))
speed = float(input("Enter current velocity in km/h, and press enter: "))
temp = float(input("Enter current outside temperature in °C, and press enter: "))
# temp = float(input("Enter current outside temperature in °C, and press enter: "))
h = str(round(hight * 3.28084, 2))
s = str(round(speed * 0.62137, 2))
t = str(round(temp * 9 / 5 + 32, 2))
print(str(hight) + " meters over sea is equivalent to " + h + " feet over sea.")
print(str(speed) + " km/h is equivalent to " + s + " mph")
print(str(temp) + " °C is equivalent to " + t + " °F")
| true |
ab77e72fabb93382bb3f009069465def1d6c3368 | suraj-thadarai/Learning-python-from-Scracth | /findingFactorial.py | 263 | 4.375 | 4 | #finding the factorial of a given number
def findingFactorial(num):
for i in range(1,num):
num = num*i
return num
number = int(input("Enter an Integer: "))
factorial = findingFactorial(number)
print("Factorial of a number is:",factorial)
| true |
6b1883815e71b89b42642fb84a893a599e69496e | cseshahriar/The-python-mega-course-practice-repo | /advance_python/map.py | 407 | 4.28125 | 4 | """
The map() function executes a specified function for
each item in an iterable. The item is sent to the function as a parameter.
"""
def square(n):
return n * n
my_list = [2, 3, 4, 5, 6, 7, 8, 9]
map_list = map(square, my_list)
print(map_list)
print(list(map_list))
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'),
('orange', 'lemon', 'pineapple'))
| true |
ae867fa7bd813de8cc06c1d30a7390eb8201e7fd | cseshahriar/The-python-mega-course-practice-repo | /random/random_example.py | 939 | 4.625 | 5 | # Program to generate a random number between 0 and 9
# importing the random module
import random
""" return random int in range """
print(random.randint(0, 9))
""" return random int in range"""
print(random.randrange(1, 10))
""" return random float in range """
print(random.uniform(20, 30))
"""
To pick a random element from a non-empty sequence (like a list or a tuple),
you can use random.choice(). There is also random.choices() for choosing
multiple elements from a sequence with replacement (duplicates are possible):
"""
items = ['one', 'two', 'three', 'four', 'five']
print(random.choice(items))
print(random.choices(items, k=2)) # two val return
print(random.choices(items, k=3)) # three val return
"""
You can randomize a sequence in-place using random.shuffle().
This will modify the sequence object and randomize the order of elements:
"""
print(items) # before
random.shuffle(items)
print(items) # after shuffle
| true |
414024ec189b3b448632b6743408ca1235df3b7c | Darja-p/python-fundamentals-master | /Labs/06_functions/06_02_stats.py | 455 | 4.125 | 4 | '''
Write a script that takes in a list and finds the max, min, average and sum.
'''
inp1 = input("Enter a list of numbers: ")
def MinMax(a):
listN = a.split()
listN = [float(i) for i in listN]
max_value = max(listN)
min_Value = min(listN)
avg_Value = sum(listN) / len(listN)
sum_Value = sum(listN)
print(f"Maximum value is {max_value}, minimum value is {min_Value}, average is {avg_Value}, sum is {sum_Value}")
MinMax(inp1) | true |
700b4701729713ce93c836709beef9b393dd6327 | Darja-p/python-fundamentals-master | /Labs/08_file_io/08_01_words_analysis.py | 646 | 4.3125 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
from itertools import count
list1 = []
with open("words.txt",'r') as fin:
for w in fin.readlines():
w = w.rstrip()
list1.append(w)
print(list1)
print(f"shortest word is: {min((word for word in list1), key=len)}")
print(f"longest word is: {max((word for word in list1), key=len)}")
print(len(list1))
"""count1 = 0
for i in list1:
count1 += 1
print(count1)"""
| true |
6a8ba495dd00b7a9bd3d40098780799e4bb5d03d | Darja-p/python-fundamentals-master | /Labs/07_classes_objects_methods/07_05_freeform_inheritance.py | 2,115 | 4.21875 | 4 | '''
Build on your previous freeform exercise.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in the previous exercises.
If you cannot think of a way to build on your freeform exercise,
you can start from scratch here.
We encourage you to be creative and try to think of an example of
your own for this exercise but if you are stuck, some ideas include:
- A Vehicle superclass, with Truck and Motorcycle subclasses.
- A Restaurant superclass, with Gourmet and FastFood subclasses.
'''
class Movie():
list_to_see = []
def __init__(self, title, year, seen='have not seen'):
"""title should be a string"""
self.title = title
self.year = year
assert (type(self.year) == int), "year must be an integer"
self.seen = seen
def __str__(self):
return f"this is a movie called {self.title}, from {self.year}, which you {self.seen}"
def watch(self):
self.seen = "watched already"
return f" you watched {self.title}"
def watch_list(self):
if self.seen == "watched already":
print(f"you have seen this movie already")
else:
Movie.list_to_see.append(self.title)
return Movie.list_to_see
class RomCom(Movie):
pass
class newRomCom(RomCom):
"""class for Rom Com movies from the last two years"""
pass
class ActionMovie(Movie):
def __init__(self, title, year, seen, pg =13):
print(f"this is a pg {pg}")
self.pg = pg
super().__init__(title,year,seen)
def __str__(self):
return f"{self.title} from the year {self.year} with the rating {self.pg} which you {self.seen}"
pretty = Movie("Pretty woman", 1990)
print(pretty)
pretty.watch_list()
print(Movie.list_to_see)
la = RomCom("Love Actually", 1995)
print(la)
la.watch()
print(la)
ist = newRomCom("Isn't it romantic", 2019)
print(ist)
ist.watch()
ist.watch_list()
mm = ActionMovie("Mad Max", 2015,"not seen")
print(mm)
mm.watch_list()
print(Movie.list_to_see) | true |
8b84cae134528d332b0cf3e998c873697381a45e | Darja-p/python-fundamentals-master | /Labs/03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 485 | 4.1875 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list1 = list(input_dict.items())
print(list1)
def takeSecond(elem):
return elem[1]
sortedList = sorted(list1, key=takeSecond)
sortedList1 = sorted(list1, key=lambda elem: elem[-1])
print(sortedList)
print((sortedList1)) | true |
4d0e725efd60894619a1274d24eeb1d823966a72 | Darja-p/python-fundamentals-master | /Labs/02_basic_datatypes/02_05_convert.py | 731 | 4.5 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
a = 2
print (a)
a = float (a)
print(a)
b = 3.4 #the decimal part of the number will be lost
b = int (b)
print (b)
print (10 // 3) #the decimal part of the result will be lost
# just to test standard division print (10 / 3)
print (10 // 3.5) #the decimal part of the result will be lost
# just to test standard division print (10 / 3.5)
c ,d = input("Please insert two numbers: ").split()
c = float (c)
d = float (d)
print( c * d)
| true |
0ac789041795f5876f64b57d894d57cba7182993 | OrNaishtat/Python---Magic-Number | /TheMagicNumber.py | 2,032 | 4.1875 | 4 | ########################################################################################################################################
### NewLight - The Magic Number.
### The magic number generates a random number between 1 and 10, the user needs to guess the number.
### The user has a limited number of lives (NB_LIVES)
### If the user input is greater or lower than magic number terminal output will notify the user.
########################################################################################################################################
import random
###### ask_number function is responsible for the user for input - converting to int, and managing exceptions #####
def ask_number(nb_min, nb_max):
#number_str = input("What is the Magic Number between " + nb_min + "and " + nb_max) ## this gives concatination error, why?
number_int = 0
while number_int == 0:
number_str = input(f"What is the magic number (between {nb_min} and {nb_max}?) ")
try:
number_int = int(number_str)
except:
print("Must be a number!")
if number_int < nb_min or number_int > 10:
print("Error, you must enter a number between 1 and 10")
number_int = 0
return number_int
##### Variables #####
MIN_NUMBER = 1
MAX_NUMBER = 10
MAGIC_NUMBER = random.randint(MIN_NUMBER, MAX_NUMBER)
NB_LIVES = 5
number = 0
lives = NB_LIVES
##### Main loop is responsible for updating user with the number of lives left, greater/lower status, and if he won/lost #####
while not number == MAGIC_NUMBER and lives > 0:
print(f"You have {lives} lives!")
number = ask_number(MIN_NUMBER, MAX_NUMBER)
if number < MAGIC_NUMBER:
print("The Magic Number is GREATER")
lives -= 1
elif number > MAGIC_NUMBER:
print("The Magic number is LOWER")
lives -= 1
else:
print("You Won!")
if lives == 0:
print("You lost!")
print(f"The magic number was {MAGIC_NUMBER}") | true |
6836f4e8fada111cc10e3da114f6139277b1312f | nooknic/MyScript | /var.py | 277 | 4.25 | 4 | #Initialize a variable with an integer value.
var = 8
print(var)
#Assign a float value to the variable.
var = 3.142
print(var)
#Assign a string value to the variable.
var="Python in easy steps"
print(var)
#Assign a boolean value to the variable.
var = True
print(var)
| true |
5f26386ef1362913cba95ad2ec17ae5869fc90e3 | jagrutipyth/Restaurant | /Inheritance_polymorphism.py | 807 | 4.125 | 4 | class Restaurant:
def __init__(self,customer,money):
self.customer = customer
self.__money = money
def coupan(self):
print(f"Hello, {self.customer},please pay {self.__money} and take your coupan")
class IcecreamStand(Restaurant):
'''Using this class to show inheritence & polymorphism'''
def __init__(self,customer,money):
super().__init__(customer,money)
def coupan(self):
#self.coupan = coupan
#coupan = self.coupan
answer = (input("Do you have coupan?('Yes/No'): ").title())
if answer == 'Yes':
print(f"Hi {self.customer},please give your coupan.")
else:
super().coupan() #here calling coupan method from parent class - Restaurant
z = IcecreamStand('Jagruti',20)
print(z.coupan())
| true |
120762fb80c0df66a6102d87d0bac74ea94dbb4c | Ridwanullahi-code/python-list-data-type | /assignment.py | 961 | 4.25 | 4 | # base from the given list below create a python function using the following condition as specified below
# (a) create a seperated lists of string and numbers
# (b) sort the strings list in ascending order
# (c) sort the string list in descending order
# (d) sort the number list from the lowest to high
# (e) sort the number list from highest to lowest
gadget = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00,
"Televison", 1000, "Laptop Case", "Camera Lens",
]
string_list = []
number_list = []
for string in gadget:
if type(string) == str:
string_list.append(string)
else:
number_list.append(string)
print("Question a answer")
print(string_list)
print(number_list)
print("Question b answer")
sort_string = sorted(string_list)
print(sort_string)
print("Question c answer")
print(sort_string[::-1])
print("Question d answer")
sort_number = sorted(number_list)
print(sort_number)
print("Question e answer")
print(sort_number[::-1])
| true |
c7a76e6560b621b5e0c8b51a17685d016f46e4d2 | lowks/levelup | /hackerrank/staircase/staircase.py | 404 | 4.21875 | 4 | #!/bin/python
import sys
def staircase(total, number):
# Complete this function
hash_number = ""
for space in range(0, total - number):
hash_number += " "
for hash in range(0, number):
hash_number = hash_number + "#"
return hash_number
if __name__ == "__main__":
n = int(raw_input().strip())
for number in range(1, n+1):
print staircase(n, number)
| true |
9964e05b7c8fd3ee6588d476fa2cbe240c7b921d | jacealan/eulernet | /level2/38-Pandigital multiples.py | 1,240 | 4.1875 | 4 | #!/usr/local/bin/python3
'''
Problem 38 : Pandigital multiples
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5,
giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed
as the concatenated product of an integer with (1,2, ... , n) where n > 1?
https://projecteuler.net/problem=38
---
프로그래머 Programmer : 제이스 Jace (https://jacealan.github.io)
사용언어 Language : 파이썬 Python 3.6.4
OS : macOS High Sierra 10.13.3
에디터 Editor : Visual Studio Code
'''
def solution():
for i in range(1, 10000):
multiple = ''
for j in range(1, 10):
multiple += str(i * j)
if len(multiple) > 9 or '0' in multiple:
break
if len(multiple) == 9 and len(set(multiple)) == len(multiple):
print(i, j, multiple)
break
if __name__ == '__main__':
solution()
| true |
d1304b21ceb527d863c16c297877ae04b5405962 | daredtech/lambda-python-1 | /src/14_cal.py | 1,756 | 4.53125 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
"""
import sys
import calendar
from datetime import datetime
def user_calendar():
print('enter month and year: ')
user_input_value = input()
if user_input_value == '':
current_month = calendar.month(2019, 8, w=0, l=0)
print(current_month)
user_input_list = user_input_value.split(' ')
if len(user_input_value) == 1 and int(user_input_list[0])<=12:
current_month = calendar.month(2019, (int(user_input_list[0])), w=0, l=0)
print(current_month)
if len(user_input_list) == 2 and (int(user_input_list[0])) <=12:
current_month = calendar.month((int(user_input_list[1])), (int(user_input_list[0])), w=0, l=0)
print(current_month)
if len(user_input_list) == 2 and (int(user_input_list[1])) <=12:
current_month = calendar.month((int(user_input_list[0])), (int(user_input_list[1])), w=0, l=0)
print(current_month)
else:
return print('The expected format is : MM, YYYY')
user_calendar() | true |
a5924b232af9c4c761d7093cce952507ba9341a8 | gopikrishnansa/weather_in_your_location | /weather app.py | 1,417 | 4.15625 | 4 | import requests
class weather:
def get(self):
try:
#gets data from openweathermap api
#converting that info to json
#accessing json files
#printing the info here
global city,api_address,mainweather,descriptio,wind,name
name = input("enter your name: ")
city = input("enter the city you want to know: ")
api_address = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=0c42f7f6b53b244c78a418f4f181282a".format(city)
json_data = requests.get(api_address).json()
mainweather = json_data["weather"][0]["main"]
descriptio = json_data["weather"][0]["description"]
wind = json_data["wind"]["speed"]
print(" ")
except KeyError as wea:
#most common error is adding a location which is invalid (only valid input from user is location)
print("""
---------------------------------------------
| invalid city name, please give a valid one |
---------------------------------------------
""")
else:
print(""" hi {}, It is nice to see you. your selected location is {} and according to my observation I
can see {} ({}) there, wind speed is {} km/hr.""".format(name,city,mainweather,descriptio,wind))
b=weather()
b.get()
| true |
a7cd28c10d88473e318bf9daa1192d408d78f54a | sulleyi/CSC-120 | /Project1/card.py | 474 | 4.15625 | 4 | class card:
"""
Class for the card object
"""
def __init__(self, value, suit):
"""
initializes card object
:param self: instance of card
:param value: cards number or face value
:param suit: suit value of card (heart,diamond, club, or spade)
:return:
"""
self.value = value
self.suit = suit
def printCard(self):
print("[" + str(self.value) + " , " + self.suit + "]")
| true |
c2a75a3e85541ad15cba57dbc6488e4532082b22 | shayansaha85/python_basic_loops_functions | /Factorial.py | 307 | 4.25 | 4 | # Python Program to Find the Factorial of a Number
def findFactorial(number):
if number==0:
return 1
elif number==1:
return 1
else:
return number * findFactorial(number-1)
number = int(input("Enter a number = "))
print("{0}! = {1}".format(number,findFactorial(number))) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.