blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2b7714e2eb4e8e55cbb62612eb1a8c37b42b0c69 | VikingOfValhalla/PY4E_Python_4_Everybody | /excercise_03_02/excercise_03_02_assignment.py | 499 | 4.21875 | 4 | score = input("Enter Score: ")
# gives the command to try the if statement for letter_grade
try:
letter_grade = float(score)
# if the try command above does not work, it will print the below
except:
print("Error with your score input")
# Possible inputs
if letter_grade >= float(0.9):
print('A')
elif letter_grade >= float(0.8):
print('B')
elif letter_grade >= float(0.7):
print('C')
elif letter_grade >= float(0.6):
print('D')
elif letter_grade > float(0.6):
print('F')
| true |
ce8b58f3c70574491db63b3fd64cd067e42a8849 | yumi2198-cmis/yumi2198-cmis-cs2 | /cs2quiz2.py | 2,114 | 4.21875 | 4 | import math
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#q1 a) 2 == 3
#q2 b) a > b and b == c
#q3 c) x == c or a > x
#
#q4 2) What does 'return' do?
# In python programming, return has the job of taking an argument and giving out the result. It basically shows what argument a certain "def" does.
#
#
#
#3) What are 2 ways indentation is important in python code?
#q5 a) Indentation is important because some values of a definition can go in as a sub value such as using "if:" and then having another indentation provides the identification of the argument belonging in the if section.
#q6 b)When something in your programming goes wrong you can easily go back to where you were struggling to debug.
#
#
#PART 2: Reading
#Type the values for 12 of the 16 of the variables below.
#
#q7 problem1_a) -36
#q8 problem1_b) -square root of 3
#q9 problem1_c) 0
#q10 problem1_d) -5
#
#q11 problem2_a)True
#q12 problem2_b)False
#q13 problem2_c)True
#q14 problem2_d)False
#
#q15 problem3_a) 0.3
#q16 problem3_b) 0.5
#q17 problem3_c) 0.5
#q18 problem3_d) 0.5
#
#q19 problem4_a) 7
#q20 problem4_b) 5
#q21 problem4_c) 0.125
#q22 problem4_d) 5
#
#PART 3: Programming
#Write a script that asks the user to type in 3 different numbers.
#If the user types 3 different numbers the script should then print out the
#largest of the 3 numbers.
#If they don't, it should print a message telling them they didn't follow
#the directions.
#Be sure to use the program structure you've learned (main function, processing function, output function)
def choosebiggest(a, b, c):
if a > b and a > c:
return a
if b > a and b > c:
return b
if c > a and c > b:
return c
def samenumbers(a, b, c):
if a == b and b == c and c == a:
return False
else:
return True
def main ():
print "Please type three different numbers in"
A = float(raw_input("A: "))
B = float(raw_input("B: "))
C = float(raw_input("C: "))
if samenumbers (A, B, C):
result = choosebiggest(A, B, C)
print "The largest number of your three numbers was {}".format(result)
else:
print "You did not follow the directions"
main()
| true |
9581a123e0f718e4b46fbabf4289ae5b94bdd4af | RajathT/dsa | /python/Linked_List/flatten_doubly_list.py | 1,734 | 4.25 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example:
Input:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
Output:
1-2-3-7-8-11-12-9-10-4-5-6-NULL
"""
if not head:
return head
def func(root):
while True:
if root.child != None:
new = func(root.child)
temp = root.next
root.child.prev = root
root.next = root.child
root.child = None
new.next = temp
if temp:
temp.prev = new
root = temp
else:
return new
elif root.next:
root = root.next
else:
return root
root = head
temp=func(root)
return head
| true |
ab60756eb584ef0085c519439de82ba9ef1a365a | RajathT/dsa | /python/Trees/tree_right_side_view.py | 1,011 | 4.21875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
'''
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
ans = []
def helper(root, ht):
if not root:
return
if len(ans) <= ht:
ans.append([])
ans[ht].append(root.val)
helper(root.left, ht+1)
helper(root.right, ht+1)
helper(root,0)
return [x[-1] for x in ans]
| true |
8e6cab1789c39d0ec5520e7dddb384f9f3e56682 | gautam199429/pythoncodes | /os.py | 2,784 | 4.3125 | 4 | import os
# Create empty dictionary
player_dict = {}
# Create an empty string
enter_player = ''
# Enter a loop to enter inforation from keyboard
while enter_player.upper() != 'X':
print 'Sports Team Administration App'
# If the file exists, then allow us to manage it, otherwise force creation.
if os.path.isfile('players.txt'):
enter_player = raw_input("Would you like to create a team or manage an existing team?\n (Enter 'C' for create, 'M' for manage, 'X' to exit) ")
else:
# Force creation of file if it does not yet exist.
enter_player = 'C'
# Check to determine which action to take. C = create, M = manage, X = Exit and Save
if enter_player.upper() == 'C':
# Enter a player for the team
print 'Enter a list of players on our team along with their position'
enter_cont = 'Y'
# While continuing to enter new player's, perform the following
while enter_cont.upper() == 'Y':
# Capture keyboard entry into name variable
name = raw_input('Enter players first name: ')
# Capture keyboard entry into position variable
position = raw_input('Enter players position: ')
# Assign position to a dictionary key of the player name
player_dict[name] = position
enter_cont = raw_input("Enter another player? (Press 'N' to exit or 'Y' to continue)")
else:
enter_player = 'X'
# Manage player.txt entries
elif enter_player.upper() == 'M':
# Read values from the external file into a dictionary object
print
print 'Manage the Team'
# Open file and assign to playerfile
playerfile = open('players.txt','r')
# Use the for-loop to iterate over the entries in the file
for player in playerfile:
# Split entries into key/value pairs and add to list
playerList = player.split(':')
# Build dictionary using list values from file
player_dict[playerList[0]] = playerList[1]
# Close the file
playerfile.close()
print 'Team Listing'
print '++++++++++++'
# Iterate over dictionary values and print key/value pairs
for i, player in enumerate(player_dict):
print 'Player %s Name: %s -- Position: %s' %(i, player, player_dict[player])
else:
# Save the external file and close resources
if player_dict:
print 'Saving Team Data...'
# Open the file
playerfile = open('players.txt','w')
# Write each dictionary element to the file
for player in player_dict:
playerfile.write('%s:%s\n' % (player.strip(),player_dict[player].strip()))
# Close file
playerfile.close()
| true |
742e8b0dbf3966fed15d40dc3eee899f3fedb59d | nnagwek/python_Examples | /pycharm/flowcontrolstatements/gradingSystem.py | 466 | 4.25 | 4 | maths = float(input('Enter marks in maths : '))
physics = float(input('Enter marks in physics : '))
chemistry = float(input('Enter marks in chemistry : '))
if maths < 35 or physics < 35 or chemistry < 35:
print('Student has failed!!!')
else:
print('Student has Passed!!!')
average = (maths + physics + chemistry) / 3
if average <= 59:
print('Grade : C')
elif average <= 69:
print('Grade : B')
else:
print('Grade : A')
| true |
9e86bd62c745472931f6a27de0e60e1f4646b9df | sridevisriramu/pythonSamples | /raw_input_If_Else.py | 225 | 4.25 | 4 | print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("enter a word = ")
print "User entered word is = " + str(original)
if(len(original)>0):
print original
else:
print "empty string" | true |
58c0349c83d605f31d2cef274793b26355aa25ff | DaniMarek/pythonexercises13 | /lstodic.py | 1,010 | 4.25 | 4 | # Create a function that takes in two lists and creates a single dictionary. The first list contains keys and the second list contains the values. Assume the lists will be of equal length.
# Your first function will take in two lists containing some strings.
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def make_dict(name, animal):
new_dict = zip(name, animal)
print new_dict
make_dict(["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"], ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"])
# Hacker Challenge:
# If the lists are of unequal length, the longer list should be used for the keys, the shorter for the values.
def make_dict(name, animal):
new_dict = zip(animal, name)
print new_dict
make_dict(["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"], ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]) | true |
48fe2fbb091316a82c366f567aef9c089e73a574 | TejasviniK/Python-Practice-Codes | /getCaptitals.py | 255 | 4.125 | 4 | def get_capitals(the_string):
capStr = ""
for s in the_string :
if ord(s) >= 67 and ord(s) <= 90:
capStr += s
return capStr
print(get_capitals("CS1301"))
print(get_capitals("Georgia Institute of Technology"))
| true |
5890fca781ca1ccec74571a9c5d962cad956b352 | changediyasunny/Challenges | /leetcode_2018/7_reverse_integer.py | 873 | 4.125 | 4 | """
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:
[−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
rev = 0
tmp = x
if x < 0:
x = x * (-1)
while x != 0:
rev = (rev * 10) + (x%10)
x = x // 10
if tmp < 0:
rev = rev * (-1)
# Handling overflow
if -2 ** 31 <= rev <= 2 ** 31 - 1:
return rev
return 0
| true |
fae854c0275661ef01a70a10a9befdd4e35a3756 | changediyasunny/Challenges | /leetcode_2018/655_print_2D_binary_tree.py | 2,209 | 4.125 | 4 | """
655. Print Binary Tree
Print a binary tree in an m*n 2D string array following these rules:
The row number m should be equal to the height of the given binary tree.
The column number n should always be an odd number.
Example 1:
Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]
Example 2:
Input:
1
/ \
2 3
\
4
Output:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
depth = height(root)
width = 2 ** depth - 1
output = [[''] * width for i in range(depth)]
stack = [(root, 0, 0, width-1)]
while stack:
node, row, left, right = stack.pop(0)
mid = (left + right)//2
output[row][mid] = str(node.val)
if node.left:
stack.append((node.left, row+1, left, mid-1))
if node.right:
stack.append((node.right, row+1, mid+1, right))
return output
class Solution(object):
def printTree(self, root):
"""
:type root: TreeNode
:rtype: List[List[str]]
"""
def height(node):
return 0 if not node else 1 + max(height(node.left), height(node.right))
def update_output(node, row, left, right):
if not node:
return
mid = (left + right) // 2
self.output[row][mid] = str(node.val)
update_output(node.left, row + 1 , left, mid - 1)
update_output(node.right, row + 1 , mid + 1, right)
depth = height(root)
width = 2 ** depth - 1
self.output = [[''] * width for i in range(depth)]
update_output(node=root, row=0, left=0, right=width - 1)
return self.output
| true |
3cbbdba5fccc9957370774c31a727840c2bd90f3 | changediyasunny/Challenges | /leetcode_2018/208_implement_trie.py | 2,173 | 4.21875 | 4 | """
208. Implement Trie (prefix tree)
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
Input:
["Trie","insert","search","search","startsWith","insert","search"]
[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]
Output:
[null,null,true,false,true,null,true]
"""
class Node():
def __init__(self):
self.children = {}
self.flag = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
current = self.root
for w in word:
temp_node = current.children.get(w, None)
if temp_node is None:
temp_node = Node()
current.children[w] = temp_node
current = temp_node
current.flag = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
current = self.root
for char in word:
current = current.children.get(char, None)
if current is None:
return False
return current.flag
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
current = self.root
for w in prefix:
current = current.children.get(w, None)
if current is None:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
664c7738c1e235d552343733bd98b7239e3f4213 | changediyasunny/Challenges | /leetcode_2018/150_eval_reverse_polish_notation.py | 2,130 | 4.15625 | 4 | """
150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and
there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
"""
import operator
class Solution(object):
def evalRPN_ops(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
ops = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul
}
for token in tokens:
if token in ops:
y = stack.pop()
x = stack.pop()
stack.append(int(ops[token](x, y)))
else:
stack.append(int(token))
return stack.pop()
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
ops = ['+', '-', '*', '/']
for t in tokens:
if t in ops:
n1 = stack.pop()
n2 = stack.pop()
if t == '+':
stack.append(n1+n2)
elif t == '-':
stack.append(n2-n1)
elif t == '/':
stack.append(int(n2/float(n1)))
elif t == '*':
stack.append(n1*n2)
else:
stack.append(int(t))
return stack.pop()
| true |
9a18f7c85ecd1a54178e39c4058f63f6be85edfa | changediyasunny/Challenges | /leetcode_2018/207_course_schedule.py | 2,261 | 4.1875 | 4 | """
207. Course Schedule
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first
take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible
for you to finish all courses?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
"""
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
graph = collections.defaultdict(set)
degree = [0] * numCourses
for i, j in prerequisites:
graph[j].add(i)
degree[i] += 1
bfs = [k for k in range(numCourses) if degree[k] == 0]
for k in bfs:
for j in graph[k]:
degree[j] -= 1
if degree[j] == 0:
bfs.append(j)
return len(bfs) == numCourses
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
graph = collections.defaultdict(set)
for i, j in prerequisites:
graph[j].add(i)
color = [0] * numCourses
def dfs(idx):
color[idx] = 1
if idx in graph:
for j in graph[idx]:
if color[j] == 0:
if not dfs(j):
return False
elif color[j] == 1:
return False
color[idx] = 2
return True
for k in range(numCourses):
if color[k] == 0:
if not dfs(k):
return False
return True
| true |
c9fdcf043b9a4fdd46f51714328b1c829df41b82 | RuslanIhnatenko/Python-Enchantress | /lectures/tests/asserts_practice.py | 446 | 4.125 | 4 | def is_prime(number):
"""Return True if *number* is prime."""
if number <= 1:
return False
for element in range(2, number):
if number % element == 0:
return False
return True
assert is_prime(7) is True, "7 is prime number"
assert is_prime(10) is False, "10 is not a prime number"
# corner case test, which will catch error in is_prime function
assert is_prime(1) is False, "1 is not a prime number"
| true |
6d3f6c4facea5db2d699029b8773651fd77a55eb | dabay/LeetCodePython | /MaximumSubarray.py | 1,067 | 4.28125 | 4 | # -*- coding: utf8 -*-
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach,
which is more subtle.
该问题最初由布朗大学的Ulf Grenander教授于1977年提出,当初他为了展示数字图像中一个简单的最
大然似然估计模型。不久之后卡内基梅隆大学的Jay Kadane提出了该问题的线性算法。(Bentley 1984)。
'''
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):
max_to_here = A[0]
max_so_far = A[0]
for x in A[1:]:
max_to_here = max(x, max_to_here + x)
max_so_far = max(max_so_far, max_to_here)
return max_so_far
if __name__ == "__main__":
s = Solution()
print s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
| true |
b50acc9bb4d87dc26c8798a05e025cbcd275b70e | dabay/LeetCodePython | /172FactorialTrailingZeroes.py | 573 | 4.15625 | 4 | # -*- coding: utf8 -*-
'''
https://oj.leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
'''
class Solution:
# @return an integer
def trailingZeroes(self, n):
result = 0
temp = n
while temp >= 5:
temp = temp / 5
result = result + temp
return result
if __name__ == "__main__":
s = Solution()
n = 30
print s.trailingZeroes(n)
#import math
#print math.factorial(n) | true |
6338838f56dc97b6dbfc227a5693fdc9e0eb4d50 | dabay/LeetCodePython | /FlattenBinaryTreeToLinkedList.py | 2,012 | 4.5 | 4 | # -*- coding: utf8 -*-
'''
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
def flatten2(node):
if node is None:
return None
if node.left is None and node.right is None:
return node
tail_left_side = flatten2(node.left)
tail_right_side = flatten2(node.right)
head_left_side = node.left
head_right_side = node.right
node.left = None
if head_left_side is not None:
node.right = head_left_side
if head_right_side is None:
return tail_left_side
else:
tail_left_side.right = head_right_side
else:
node.right = head_right_side
return tail_right_side
if root is None:
return
tail_left_side = flatten2(root.left)
tail_right_side = flatten2(root.right)
head_left_side = root.left
head_right_side = root.right
root.left = None
if head_left_side is not None:
root.right = head_left_side
tail_left_side.right = head_right_side
else:
root.right = head_right_side
if __name__ == "__main__":
tn1 = TreeNode(1)
tn2 = TreeNode(2)
tn3 = TreeNode(3)
tn1.left = tn2
tn2.left = tn3
s = Solution()
s.flatten(tn1)
n = tn1
while n:
print str(n.val) + "->",
n = n.right
print "None"
| true |
6f564d7d1802a29f5151d709e96b40232d01ebb7 | dabay/LeetCodePython | /SetMatrixZeroes.py | 1,482 | 4.25 | 4 | # -*- coding: utf8 -*-
'''
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
哎,这道题有点巧妙呐~
'''
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
row_count = len(matrix)
column_count = len(matrix[0])
first_row_zero = False
for c in xrange(column_count):
if matrix[0][c] == 0:
first_row_zero = True
break
first_column_zero = False
for r in xrange(row_count):
if matrix[r][0] == 0:
first_column_zero = True
break
for r in xrange(1, row_count):
for c in xrange(1, column_count):
if matrix[r][c] == 0:
matrix[0][c] = 0
matrix[r][0] = 0
for r in xrange(1, row_count):
for c in xrange(1, column_count):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if first_row_zero is True:
for c in xrange(column_count):
matrix[0][c] = 0
if first_column_zero is True:
for r in xrange(row_count):
matrix[r][0] = 0
if __name__ == "__main__":
s = Solution()
matrix = [
[1,1,1],
[1,0,1],
[1,1,1]
]
print s.setZeroes(matrix)
print matrix
| true |
a8b91d51f0cff6f909b3a88f94d3c35f04f455cd | dabay/LeetCodePython | /PartitionList.py | 1,753 | 4.15625 | 4 | # -*- coding: utf8 -*-
'''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
'''
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
new_head = ListNode(-1)
new_head.next = head
pointer = new_head
less_end = new_head
while pointer.next is not None:
if pointer.next.val < x:
if less_end == pointer:
pointer = pointer.next
less_end = pointer
else:
to_insert = pointer.next
pointer.next = pointer.next.next
to_insert.next = less_end.next
less_end.next = to_insert
less_end = to_insert
else:
pointer = pointer.next
return new_head.next
if __name__ == "__main__":
s = Solution()
ln1 = ListNode(1)
ln2 = ListNode(4)
ln3 = ListNode(3)
ln4 = ListNode(2)
ln5 = ListNode(5)
ln6 = ListNode(2)
ln1.next = ln2
ln2.next = ln3
ln3.next = ln4
ln4.next = ln5
ln5.next = ln6
ln = ln1
while ln is not None:
print "%s ->" % ln.val,
ln = ln.next
print "None"
ln = s.partition(ln1, 3)
while ln is not None:
print "%s ->" % ln.val,
ln = ln.next
print "None"
| true |
cf2cf2ff16a4c6f209b47c69fdc4ea88164dc0aa | jingriver/testPython | /python_language/filter_words/filter_words.py | 700 | 4.21875 | 4 | """
Filter Words
------------
Print out only words that start with "o", ignoring case::
lyrics = '''My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh bring back my Bonnie to me.
'''
Bonus points: print out words only once.
See :ref:`filter-words-solution`.
"""
lyrics = '''My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh bring back my Bonnie to me.
'''
arr = map(lambda x: x.strip(), lyrics.split(" "))
print arr
for w in arr:
if (w.startswith('O') or w.startswith('o')):
print w | true |
1f2aae3ca06df9c0835afed1a77bdda03f9207ec | jingriver/testPython | /numpy/mothers_day/mothers_day_solution.py | 859 | 4.125 | 4 | """
Mother's day
============
In the USA and Canada, Mother's Day is the second Sunday of May. Use
NumPy's datetime64 data type and datetime64 utilities to compute the date of
Mother's Day for the current year.
Note: NumPy datetime64 values can be created from a string with the format
YYYY-MM-DD HH:MM:SS.sss where everything after the year designation is
optional.
Bonus
~~~~~
Extract the current year programmatically using the datetime module from the
standard library.
"""
from numpy import busday_offset, datetime64
from datetime import datetime
year_str = "2014"
# Bonus:
# To automatically extract the current year:
year_str = str(datetime.now().year)
date_str = year_str + "-05"
may = datetime64(date_str)
second_sunday = busday_offset(may, 1, roll="forward", weekmask="Sun")
print("Second sunday of May this year is {}".format(second_sunday))
| true |
240916cbc51c8858649a8d39d9663aeb542482cd | richiede/my_algos | /01_my_sorting_algo.py | 1,316 | 4.4375 | 4 | # This is a program that will take multiple string inputs from a user to create a list
# The algo will then sort the list in alphabetical order.
# 3 lists are initialised
my_list = []
my_temp_list = []
sorted_list = []
# Input is taken from the user and added to the "my_list" list
print('Welcome! Please create a list one word at a time.')
print('Please enter a word or press "q" to quit!')
word = input()
while word != 'q':
my_list.append(word)
print('Please enter another word or press "q" to quit!')
word = input()
# The list is copied to a list called "my_temp_list" in order to preserve the state of the original list
my_temp_list = my_list.copy()
# The algo goes through and gets the lowest alphabetical word from the "my_temp_list"
# Assigns it to the a variable called "the_value"
# Adds the value to the next position in the "sorted_list" and deletes the value from the "my_temp_list"
while len(sorted_list) < len(my_list):
for i, v in enumerate(my_temp_list):
if i == 0:
the_value = v
the_index = i
else:
if v < the_value:
the_value = v
the_index = i
del my_temp_list[the_index]
sorted_list.append(the_value)
print(f'FINAL!! My list was {my_list}.')
print(f'FINAL!! My interim list is now {my_temp_list} (empty).')
print(f'FINAL!! My sorted list is {sorted_list}.')
| true |
9b06eb2c5458ee0268a5ed2b8e86e02d15ca9ae7 | stoicamirela/PythonScriptingLanguagesProjects | /Project4/main.py | 1,148 | 4.40625 | 4 | #simple exercise with dictionary: we have a dictionary with phone numbers and names, and we show first the names and ask user
#what number phone he wants, based on that we show the value of the key name. Bonus things are changing k to value as shown in
#inverted_dict variable. I also sorted the dictionary in a for
#Last task was to count frequencies
my_dictionary = {
"Robinson": "0756 366 897",
"Mirela": "0756 322 469",
"Tom": "932328",
"Jerry": "7394372",
"Chloe": "8970798"
}
print(my_dictionary.keys())
name_input = input("name? ")
name = my_dictionary.get(name_input)
print("Number is:", name)
print("\r")
print("Sorted dictionary: ")
for key in sorted(my_dictionary):
print("%s: %s" % (key, my_dictionary[key]))
print("\r")
inverted_dict = {v: k for k, v in my_dictionary.items()}
print("Inverted dict:", inverted_dict)
print("\r")
file = open('sample.txt', 'r')
text = file.read()
words = text.split()
frequencies = []
for word in words:
frequencies.append(words.count(word))
print("Frecventele cuvintelor:", dict(list(zip(words, frequencies))))
file.close()
| true |
2d4d0e8a2f72334ed27e9cb5855afac242f90897 | Arfa-uroz/practice_program | /tuple.py | 600 | 4.375 | 4 | """Given an integer,n, and n space-separated integers as input, create a tuple ,t , of those n integers.
Then compute and print the result of hash(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported."""
if __name__ == '__main__':
n = int(input()) #n number of elements in tuple
integer_list = map(int, input().split()) #n spaced integer elements in tuple
t = tuple(integer_list)
print(t) #converts the list into a tuple
print(hash(t)) #hash() encodes the given argument | true |
d3feee4d25dba244579179657ce2005908a7aa1e | Arfa-uroz/practice_program | /swap_case.py | 233 | 4.21875 | 4 | def swap_case(s):
new_string = s.swapcase() #swaps the case of all the letters
return(new_string)
if __name__ == '__main__':
s = input("Enter your string here ")
result = swap_case(s)
print(result) | true |
3f6d19203aedf5b9156817db55db27f471fb0950 | LambdaSchool-forks/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/northwind.py | 2,296 | 4.21875 | 4 | import sqlite3
# create connection
sl_conn = sqlite3.connect('/Users/Elizabeth/sql/northwind_small.sqlite3')
curs = sl_conn.cursor()
# table names
# [('Category',), ('Customer',), ('CustomerCustomerDemo',),
# ('CustomerDemographic',), ('Employee',), ('EmployeeTerritory',), ('Order',),
# ('OrderDetail',), ('Product',), ('Region',), ('Shipper',), ('Supplier',),
# ('Territory',)]
# PART 2
# What are the ten most expensive items (per unit price) in the database?
query = """
SELECT ProductName
FROM Product
ORDER BY UnitPrice
LIMIT 10;
"""
answer = curs.execute(query).fetchall()
print('\nPART 2')
print('The ten most expensive items per unit price are:')
for i in answer:
print(' {}'.format(i[0]))
# What is the average age of an employee at the time of their hiring?
query = """
SELECT AVG(HireDate - BirthDate)
FROM Employee;
"""
answer = curs.execute(query).fetchall()[0][0]
print('The avg age of an employee at the time of hiring is:', round(answer,2))
# (Stretch) How does the average age of employee at hire vary by city?
query = """
SELECT City, AVG(HireDate - BirthDate)
FROM Employee
GROUP BY City;
"""
answer = curs.execute(query).fetchall()
print('The avg age of an employee in each city is:')
for i in answer:
print(' {} : {}'.format(i[0],i[1]))
# PART 3
# What are the ten most expensive items (per unit price) in the database and their suppliers?
query = """
SELECT Product.ProductName, Supplier.CompanyName
FROM Product
JOIN Supplier ON Product.SupplierID = Supplier.ID
ORDER BY Product.UnitPrice
LIMIT 10;
"""
answer = curs.execute(query).fetchall()
print('\nPART 3')
print('The ten most expensive items per unit price and their suppliers are:')
for i in answer:
print(' {} : {}'.format(i[0],i[1]))
# What is the largest category (by number of unique products in it)?
query = """
SELECT Category.CategoryName
FROM Product
JOIN Category ON Product.CategoryID = Category.ID
GROUP BY Product.CategoryID
ORDER BY COUNT(DISTINCT Product.ID) DESC
LIMIT 1;
"""
answer = curs.execute(query).fetchall()[0][0]
print('The largest category is:', answer)
| true |
a23aedd69fd4ec2d6500ba5a8bb05b0efbc67a1b | Allen-1242/Python-Prorgrams | /Python Programs/Python Programs/SQL_python/sql2.py | 954 | 4.1875 | 4 | import sqlite3
con = sqlite3.connect('my_data.db')
cur = con.cursor()
while(True):
print("Welcome to the database")
print("1.Insert the row\t2.View the table\n3.Update the table\t 4.Drop the table\n5.Exit")
imp = int(input("Enter the operation needed"))
if imp == 1:
print("Welcome to insertion \n")
f = int(input("enter the id\n"))
k = input("enter the name")
cur.execute('''INSERT INTO Student10 VALUES(?,?);''',[f,k])
if imp == 2:
print("Welcome to viewing the table\n")
r = cur.execute('''SELECT * FROM Student10''')
p = r.fetchall();
print(p)
if imp == 3:
print("Welcome to updating the table\n")
k = input("enter the name to be changed")
f = int(input("enter the id to be changed\n"))
cur.execute('''UPDATE Student10 SET id=? WHERE name=? ''',[f,k])
if imp == 4:
print("Welcome to deleting the table\n")
cur.execute('''DROP TABLE Student10''')
if imp == 5:
print("Exited the program")
break
| true |
5758d2fbfde70ce6058f703bd003826a748dc63e | joco1026/Python-Challenge | /4/dynamic_url.py | 757 | 4.125 | 4 | #!/usr/bin/python
#http://www.iainbenson.com/programming/Python/Challenge/solution4.php
#This is an example of using a linked list to dynamically open HTML pages.
#It will parse an HTML page for a number and then dynamically open the next page.
import urllib, re
url="http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
#starting number
#page="12345"
page="46059"
counter=0
while counter < 400: #limit tries to 400 based on a hint
#grep the entire page
everything = urllib.urlopen(url+page).read()
page = ''.join(re.findall("and the next nothing is ([0-9]+)", everything))
if page == '': #stop if no number is found
break
else:
print counter,"next ",page, "):", everything
counter+=1
print everything
| true |
4f42a130f24a8159a696bd2ea33712e5e79b5750 | FranzSchubert92/cw | /python/best_travel.py | 1,976 | 4.21875 | 4 | #! /usr/bin/env python3
"""
John and Mary want to travel between a few towns A, B, C ... Mary has on a
sheet of paper a list of distances between these towns.
ls = [50, 55, 57, 58, 60].
John is tired of driving and he says to Mary that he doesn't want to drive more
than t = 174 miles and he will visit only 3 towns.
Which distances, hence which towns, they will choose so that the sum of the
distances is the biggest possible
to please Mary - but less than t - to please John- ?
Example:
With list ls and 3 towns to visit they can make a choice between:
[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],
[55,57,58],[55,57,60],[55,58,60],[57,58,60]
The sums of distances are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175.
The biggest possible sum taking a limit of 174 into account is then 173 and the
distances of the 3 corresponding towns is [55, 58, 60].
The function chooseBestSum (or choose_best_sum or ... depending on the language)
will take as parameters t (maximum sum of distances, integer >= 0), k (number of
towns to visit, k >= 1) and ls (list of distances, all distances are positive or
null integers and this list has at least one element). The function returns the
"best" sum ie the biggest possible sum of k distances less than or equal to the
given limit t, if that sum exists, or otherwise nil, null, None, Nothing,
depending on the language. With C++, C, Rust, Swift, Go return -1.
>> DocTests >>
>>> ts = [50, 55, 56, 57, 58]; choose_best_sum(163, 3, ts)
163
>>> ts = [50]; choose_best_sum(163, 3, ts)
-1
>>> ts = [91, 74, 73, 85, 73, 81, 87]; choose_best_sum(230, 3, ts)
228
"""
from itertools import combinations
def choose_best_sum(t, k, ls):
best_route = -1
for route in combinations(ls, k):
length = sum(route)
if best_route < length <= t:
best_route = length
return best_route
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
c57415dc01430b0d3b9824290a5c6828673cb2be | kiba0510/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 329 | 4.21875 | 4 | #!/usr/bin/python3
"""
Square Module - Use when you need to print a square
"""
class Square:
"""
Class defining the size of a square
"""
def __init__(self, size=0):
"""
Initialization of instanced attribute
Args:
size: The size of a square
"""
self.__size = size
| true |
6abd13360b2e330db9bc328d479d248713960d95 | natallia-bonadia/dev-studies | /Lets Code/Coding Tank - Python/Python/Lets Code/Aula 2 - Scripts em Python.py | 2,091 | 4.25 | 4 | ### EXERCÍCIOS AULA 2 - SCRIPTS EM PYTHON ###
'''
1) Faça um script que mostra a média de duas notas.
A = int(input("Digite a média 1:"))
B = int(input("Digite a média 2:"))
resultado = (A + B) / 2
print(resultado)
----------
2) Faça um script para somar dois números e multiplicar o resultado
pelo primeiro número.
A = int(input("Digite um número:"))
B = int(input("Digite um número:"))
resultado = (A + B) * A
print(resultado)
----------
3) Escreva um script para ler um valor (do teclado) e escrever
(na tela) o seu antecessor.
A = int(input("Digite um número:"))
resultado = A - 1
print(resultado)
----------
4) Escreva um script para ler o salário mensal atual de um funcionário
e o percentual de reajuste. Calcular e escrever o valor do novo salário.
A = float(input("Digite o salário mensal:"))
B = float(input("Digite o percentual de reajuste:"))
reajuste = (B / 100) + 1
resultado = A * reajuste
print(resultado)
----------
5) Escreva um script que armazene o valor 10 em uma variável A e o
valor 20 em uma variável B. A seguir (utilizando apenas atribuições
entre variáveis) troque os seus conteúdos fazendo com que o valor que
está em A passe para B e vice-versa. Ao final, escrever os valores que
ficaram armazenados nas variáveis.
A = 10
B = 20
aux = A
A = B
B = aux
print(A)
print(B)
----------
6) Faça um script que peça um nome e uma idade. Ao final, informe o
ano de nascimento dessa pessoa.
from datetime import date
data_atual = date.today()
ano_atual = data_atual.year
nome = input("Digite seu nome:")
idade = int(input("Digite sua idade:"))
ano_nascimento = ano_atual-idade
print(ano_nascimento)
----------
7) Faça um script que receba um número e informe:
O dobro desse número
O número ao quadrado
O número ao cubo
A = int(input("Digite um número:"))
dobro = A*2
print(dobro)
quadrado = A**2
print(quadrado)
cubo = A**3
print(cubo)
----------
8) Faça um script que converta graus Fahrenheit para Celsius.
Dica: C = (5 * (F-32) / 9)
A = float(input("Digite a temperatura em Fahrenheit:"))
C = 5 * (A - 32) / 9
print(C)
''' | false |
ace00dd2e10aefdd23c28b0222f91b6e109374ee | microsoft/python-course | /pycourse.py | 1,413 | 4.125 | 4 | # Functions for Introduction to Python Course
## Turtle Graphics
import jturtle as turtle
def square(x):
"""
Draw a square with side x
"""
for t in range(4):
turtle.forward(x)
turtle.right(90)
def house(size):
"""
Draw a house of specified size
"""
square(size)
turtle.forward(size)
turtle.right(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(30)
turtle.penup()
turtle.forward(2*size/3)
turtle.right(90)
turtle.forward(size/3)
turtle.pendown()
square(size/3)
turtle.penup()
turtle.forward(2*size/3)
turtle.left(90)
turtle.forward(size/3)
turtle.left(180)
turtle.pendown()
# Quadratic Equations
import math
import random
def solve(a,b,c):
d = b*b-4*a*c
if d>=0:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
return (x1,x2)
else:
return None
def coef(a,x):
if a==0:
return ""
elif a==1:
return "+"+x
elif a==-1:
return "-"+x
elif a<0:
return "-"+str(-a)+x
else:
return "+"+str(a)+x
def equation(a,b,c):
s = coef(a,"x^2")+coef(b,"x")+coef(c,"")
if s[0] == "+":
return s[1:]
else:
return s
def random_equation():
a = random.randint(1,5)*random.choice([-1,1])
b = random.randint(-10,10)
c = random.randint(-20,20)
return (a,b,c)
| true |
b350082c8536e3b80dd2ac9dd8badd9114f5630b | uncamy/Games | /pigLatin.py | 611 | 4.15625 | 4 | pyg = 'ay'# piece of code for use later
original = raw_input('Enter a word:') #user input word to be translated
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first =word[0]
#for words that start with a vowel
if first == "a" or first=="e" or first=="i" or first=="u":
new_word = word + pyg
print new_word
else: # for words that start with consonant
new_word = word[1:] + first + pyg
#this syntax word[1:] splits off the first letter
print new_word
else: # for inappropriate user input
print 'empty'
| true |
e869611625c651a76222ef709319cd7917eb7a30 | raxxar1024/code_snippet | /leetcode 051-100/95. Unique Binary Search Trees II.py | 1,412 | 4.1875 | 4 | """
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
return self.generateTreesRecu(1, n)
def generateTreesRecu(self, low, high):
result = []
if low > high:
result.append(None)
for i in xrange(low, high + 1):
left = self.generateTreesRecu(low, i - 1)
right = self.generateTreesRecu(i + 1, high)
for j in left:
for k in right:
curr = TreeNode(i)
curr.left = j
curr.right = k
result.append(curr)
return result
if __name__ == "__main__":
print Solution().generateTrees(0)
print Solution().generateTrees(3)
| true |
72ef48d15fdf5d8d3df74a38dd1438f7148f8a33 | raxxar1024/code_snippet | /leetcode 051-100/53. Maximum Subarray.py | 893 | 4.21875 | 4 | """
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sub_sum, tmp = nums[0], 0
for i in xrange(len(nums)):
tmp += nums[i]
max_sub_sum = max(tmp, max_sub_sum)
tmp = max(tmp, 0)
return max_sub_sum
if __name__ == "__main__":
assert Solution().maxSubArray([-1]) == -1
assert Solution().maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
| true |
c09c07c9c0234ee00371ec41b11e847df9aa775c | MichaelLenghel/Python-Algorithm-Problems | /recursive_reverse_string/recursive_reverse_string.py | 373 | 4.4375 | 4 | # Program to recursively reverse a string
def reverse(s):
# Base Case
if s == "":
return s
# Recursive calls
else:
return reverse(s[1:]) + s[0]
# return s[-1:] + reverse(s[:len(s) - 1])
# return s[len(s) - 1] + reverse(s[:len(s) - 1])
if __name__ == "__main__":
print(reverse("Hello, world!"))
# Normal approach: print("Hello, world"[::-1])
| true |
a3e8e1b1798d035a0297d479b785cdaf42589c02 | MichaelLenghel/Python-Algorithm-Problems | /anagram_check/anagram_check.py | 1,745 | 4.28125 | 4 | # Program that will check if two strings are anagrams, not including captials or spaces
# Has a time complexity of O(N), ideal for small data sets, but space complexity is of O(26). As 26 references are made from hashmap.
def anagram_check(s1, s2):
# Declare the dictionary
ana_li = {}
# Removes spaces in both strings
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
# If length isn't the same, then no way to be an anagram
if len(s1) != len(s2):
return False
# Increment by one for each dictionary letter key every time a letter is incurred
for letter in s1:
if letter in ana_li:
ana_li[letter] += 1
else:
ana_li[letter] = 1
# Decrement respective keys incremented previously, return False if we have past zero.
for letter in s2:
if letter in s2:
ana_li[letter] -= 1
else:
ana_li[letter] = 1
# If all values have not eached 0, return False, as imbalance of letters
for x in ana_li:
if ana_li[x] != 0:
return False
# Will return True if all checks pass
return True
def default_value():
return 0
# Has a time complexity of O(log n) since we use pythons built in timsort to arrange letters
def anagram_check_sorted(s1, s2):
# Removes spaces in both strings
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
return sorted(s1) == sorted(s2)
def anagram_check_exor(s1, s2):
result = 0
for letter in s1 + s2:
result ^= ord(letter)
if result == 0:
return True
else:
return False
if __name__ == '__main__':
s1 = "tram"
s2 = "mart"
if anagram_check_exor(s1, s2):
print("{} and {} are anagrams!".format(s1, s2))
else:
print("{} and {} are not anagrams!".format(s1, s2))
| true |
bfe78fd78d5f1335f46f8b2ecd4d0b6ffa8fb05e | saulosantiago/AutomatosExemplo1 | /exercicio1.py | 2,356 | 4.1875 | 4 | """
Linguagem pipoca
Letras possíveis: +, -, *, /, imprima, recebe, entrada
Gramatica:
Toda sentença tem que terminar em !
Variaveis tem @ no inicio do nome
exemplo de codigo:
@nomedavariavel recebe 50!
@variavel2 recebe entrada!
imprima @variavel2 + @nomedavariavel!
"""
"""
Automato1:
Finito e deterministico:
Estado inicial:
Recebe uma letra
Estado do meio:
Testa se a letra está no alfabeto
Estado final:
Retorna um resultado booleano
Resposável por verificar a estrutura das palavras.
"""
def automato1(letra):
alfabeto = ['+', '-', '*', '/', 'imprima', 'recebe', 'entrada']
if letra.startswith('@'):
return True
elif(letra.isnumeric()):
return True
elif(letra in alfabeto):
return True
else:
return False
"""
Automato2:
Finito e não deterministico:
Estado inicial:
Recebe uma sentenca
Estado 2:
divide a sentanca e envia cada letra para o automato1
Estado 3:
se o automato 1 retornar falso, passa para o estado final retornando falso, se recebe verdadeiro aguarda uma nova palavra, se não há mais palavras passa para o estado final retornando verdadeiro
Estado final:
retorna um resultado booleano
"""
def automato2(sentenca):
letras = sentenca.split()
ultimaletra = ''
for letra in letras:
if(letra == ultimaletra):
return False
else:
ultimaletra = letra
if(automato1(letra)):
continue
else:
return False
return True
"""
Automato3:
Finito e não deterministico
Estado inicial:
recebe um texto
Estado 1:
divide as sentenças e envia uma a uma, para o automato2
Estado 2:
o automato2 rertonando verdadeiro, se mantem no mesmo estado, o automato2 retornando falso vai para o estado final retornando falso, se nao tem mais palavras vai para o estado final retornando verdadeiro
Estado final:
Retorna um resultado
"""
def automato3(texto):
sentencas = texto.split('!')
for sentenca in sentencas:
if(automato2(sentenca)):
continue
else:
return False
return True
print("EXEMPLO DE AUTOMATO VERIFICADOR DA LINGUAGEM PIPOCA!\n")
print("Digite seu codigo abaixo:\n")
entrada = input()
resutado = automato3(entrada)
if resutado:
print("O seu codigo funciona!")
else:
print("O seu codigo não funciona!")
| false |
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 |
2496ecec840fb88042ad2838809c8b4d6005648b | evertondutra/Curso_em_Video_Python | /exe078.py | 781 | 4.125 | 4 | """
Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
No final, mostre qual foi o maior e o menor valore digitado e suas
respectivas posições na lista.
"""
val = []
maior = 0
for c in range(0,5):
val.append(int(input(f'Digite o {c+1}º número: ')))
if c == 0:
maior = menor = val[c]
elif val[c] > maior:
maior = val[c]
elif val[c] < menor:
menor = val[c]
print('='*20)
print(f'Você digitou os valores {val}.')
print(f'O maior valor digitado foi {maior} nas posições ',end='')
for p, v in enumerate(val):
if v >= maior:
print(f'{p + 1}',end="...")
print(f'\nO menor valor digitado foi {menor} nas posições ',end='')
for p, v in enumerate(val):
if v <= menor:
print(f'{p + 1}',end='...') | false |
174bdefb77c6d8b342dab35336e151e92bccb6a6 | evertondutra/Curso_em_Video_Python | /exe065.py | 656 | 4.15625 | 4 | """
Crie um programa que leia vários números pelo teclado. No final, mostre a média, o maior e o menor
número digitado, e pergunte se o uspuario deseja continuar.
"""
cont = maior = menor = soma = 0
resp = 'S'
while resp != 'N':
n = int(input('Digite um número: '))
soma += n
cont += 1
if cont == 1:
maior = menor = n
elif n > maior:
maior = n
elif n < menor:
menor = n
resp = input('Deseja continuar?[S/N]:').strip().upper()[0]
print(f'A média entre os {cont} números digitados é {soma / cont:.1f}')
print(f'O maior número digitado foi {maior}')
print(f'O menor número digitado foi {menor}')
| false |
ac00b8e51e02a68663ae812b2bb2b4040efb16e8 | evertondutra/Curso_em_Video_Python | /exe079.py | 921 | 4.15625 | 4 | """
Crie um programa que possa digitar vários valores numéricos e
cadastre-os em uma lista. Caso o número ja exista la dentro,
ele não será adicionado. No final, serão exibidos todos os
valores únicos digitados, em ordem crescente.
"""
val = []
p = 0
while True:
while True:
n = input('Digite um valor: ')
if n.isnumeric() == True:
break
print('Número não digitado.')
n = int(n)
if n not in val:
val.append(n)
print('Adicionado com sucesso...')
else:
print('Valor Duplicado! Náo será adicionado.')
while True:
resp = input('Deseja continuar?[S/N] ').strip().upper()
if resp in 'NS':
break
print('Resposta inválida.')
if resp == 'N':
break
print('\033[31m=\033[m'*32)
print(f'Os valores digitados foram {val}.')
val.sort()
print(f'Os valores em ordem crescente são {val}.')
| false |
de52a1bf248d629ba07d828c320f9070afe6102d | marinasupernova/100daysofcode | /For_loop, While_loop, Random, Math : Sept_11/While_loop, Random : Sept_14/Tasks_52_59.py | 2,433 | 4.1875 | 4 | import random
'''import random
num = random.random()
print(num)'''
'''import random
color = random.choice (["red", "black", "greeen"])
print(color)'''
'''Task 52
num = random.randint(1,100)
print(num)'''
'''Task 53
fruits = random.choice(["apple", "banana", "apricot", "cherry", "peach"])
print(fruits)'''
'''Task 54
heads_or_tails = random.choice(["h", "t"])
user_choice = input("Please choose head or tails: h/t")
if user_choice == heads_or_tails:
print("You won!")
else:
print("Bad luck!")
print("The computer selected:", heads_or_tails)
if heads_or_tails =="h":
print("It was heads")
else:
print("It was tails")'''
'''Task 55
num = random.randint(1, 5)
guess_1 = int(input("Please pick a number:"))
if guess_1 == num:
print("Well done!")
elif guess_1 < num:
print("Too low")
guess_1 = int(input("Try again:"))
if guess_1 == num:
print("Correct")
elif guess_1 > num:
print("Too high")
guess_1 = int(input("Try again:"))
if guess_1 == num:
print("Correct")
else:
print("You lose!")'''
"""Task 56
random_num = random.randint(1,10)
guess = 0
while guess != random_num:
guess = int(input("Guess a number between 1 and 10: "))
print("You are right")"""
'''Task 57
random_num = random.randint(1,10)
guess = 0
while guess != random_num:
guess = int(input("Guess a number between 1 and 10: "))
if guess < random_num:
print("Too low")
elif guess > random_num:
print("Too high")
print("You are right")'''
"""num = random.random()
num1 = num * 100
num2 = random.randint
print(num1)"""
"""num1 = random.randint(1,10)
num2 = random.randint(1,10)
q1 = int(input("How much is it:", num1 * num2))
q2 = int(input("How much is it:", num1 / num2))
q3 = int(input("How much is it:", num1 + num2))
q4 = int(input("How much is it:", num1 - num2))
q5 = int(input("How much is it:", (num1 - num2) * 3))"""
'''Task 58
score = 0
for i in range (1, 6):
num1 = random.randint(1,10)
num2 = random.randint(1,10)
answer = num1 + num2
print("How much is:", num1, "+", num2, "?")
guess = int(print("Your answer is: ")
if guess == answer:
score = score +1
print("Your total score is: ", score, "out of 5")'''
i = 0
for i in range (0, 6):
color = random.choice(["red", "green", "blue", "violet", "white"])
guess = input("Guess a color: ")
if
print()
if guess == color:
print("Well done")
| false |
0b74b40d19eb4e5be0592e07711742f4354abe7d | marinasupernova/100daysofcode | /Subprograms: functions/tasks 118 -123.py | 2,202 | 4.125 | 4 | import random
'''
def get_random():
low_num = int(input("Please enter a low number: "))
high_num = int(input("Please enter a high number: "))
comp_num = random.randint(low_num, high_num)
return comp_num
'''
'''Task 120
def add_numbs():
num1 = random.randint(5,20)
num2 = random.randint(5,20)
user_answer = int(input("Please add two numbers " + str(num1) + " " + str(num2) + " :"))
correct_answer = num1 + num2
return {"user_answer": user_answer, "correct_answer": correct_answer }
def substract_num():
num1 = random.randint(25,50)
num2 = random.randint(1,25)
user_answer = int(input("Please substract two numbers " + str(num1) + " " + str(num2) + " :"))
correct_answer = num1 - num2
return {"user_answer": user_answer, "correct_answer": correct_answer }
def compare(answer1, answer2):
if answer1 == answer2:
print("Correct")
else:
print("False, correct answer is", answer1)
print("1. Addition\n 2. Substraction\n ")
user_choice = int(input("Please choose 1 or 2 : "))
if user_choice == 1:
answers = add_numbs()
compare(answers["correct_answer"], answers["user_answer"])
else:
answers = substract_num()
compare(answers["correct_answer"], answers["user_answer"])
'''
Task 121
def add_name():
name = input("Enter one name: ")
lst.append(name)
def change_name():
index = int(input("please enter an index of the name: "))
name = input("Change the name: ")
lst[index] = name
def del_name():
name = input("Please enter a name you want to delete: ")
lst.remove(name)
def view_names():
for i in lst:
print(i)
lst = []
exit = False
while exit != True:
user_choice = int(input("Please select from the options below: \n 1.Add one name \n 2. Change the name \n 3. Delete the name \n 4. View the names \n 5. Exit \n"))
if user_choice == 1:
add_name()
elif user_choice == 2:
change_name()
elif user_choice == 3:
del_name()
elif user_choice == 4:
view_names()
elif user_choice == 5:
exit = True
else:
print("Wrong choice, select a number from the above")
| false |
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 |
f9c3502f97c2fd29472cb81d474ce22f534ce1bb | palhaogv/Python-exercises | /ex086.py | 378 | 4.15625 | 4 | #crie uma matriz 3x3 e preencha com valores lidos pelo teclado
#No final, mostre a matriz na tela com o valor correto.
lista = []
for c in range(1, 10):
n = int(input(f'Digite o valor da {c}ª posição: '))
lista.append(n)
print(f'[{lista[0]}][{lista[1]}][{lista[2]}]\n'
f'[{lista[3]}][{lista[4]}][{lista[5]}]\n'
f'[{lista[6]}][{lista[7]}][{lista[8]}]\n') | false |
f6774e74fc359a562f361b06b593d20a2d269570 | lxh1997zj/-offer_and_LeetCode | /剑指offer-牛客顺序/to_offer_07.py | 2,313 | 4.1875 | 4 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
'大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n <= 39'
# n=0时,f(n)=0 n=1时,f(n)=1 n>1时,f(n)=f(n-1)+f(n-2)
class Solution:
def Fibonacci(self, n): # 循环
# write code here
a, b = 0, 1
if n <= 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
a, b = b, a+b
return b
class Solution:
def Fibonacci(self, n): # 递归,效率低,可能通不过
# write code here
a, b = 0, 1
if n <= 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
a, b = b, a+b
return b
"""
题目拓展1:跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
"""
class Solution1():
def jumpFloor(self, number):
if number == 1:
return 1
if number == 2:
return 2
a, b = 1, 2
for i in range(2, number):
a, b = b, a+b
return b
"""
题目拓展2:变态跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
"""
# 解题思路:由数学归纳法得规律
class Solution2():
def jumpFloorII(self, number):
if number <= 0:
return 0
return 2 ** (number-1)
"""
题目拓展3:矩形覆盖
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
"""
# 解题思路:这道题本质上还是斐波那契数列问题,注意分析n=0,1,2,3,...的值的情况。
class Solution3():
def rectCover(self, number):
if number <= 0:
return 0
if number == 1:
return 1
if number == 2:
return 2
a, b = 1, 2
for i in range(3, number+1):
a, b = b, a+b
return b
# 测试:
s = Solution3()
print(s.rectCover(10))
print(s.rectCover(4))
print(s.rectCover(5))
print(s.rectCover(6))
| false |
50708a5460e439e9ecb844e38d53de193bf1fe1e | lxh1997zj/-offer_and_LeetCode | /Sorting_Algorithm/bubble_sort_python.py | 329 | 4.28125 | 4 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
"""冒泡排序"""
def bubble_sort(array):
for i in range(len(array)-1, 0, -1):
for j in range(i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
array = [1,2,5,4,3,6,9,8,7]
print(bubble_sort(array)) | false |
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 |
e80e59e41310dd7485f910b796b83338fc4d168e | zhengjiani/pyAlgorithm | /leetcodeDay/March/prac876.py | 1,719 | 4.15625 | 4 | # -*- encoding: utf-8 -*-
"""
@File : prac876.py
@Time : 2020/3/23 8:55 AM
@Author : zhengjiani
@Email : 936089353@qq.com
@Software: PyCharm
链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x, p=0):
self.val = x
self.next = p
# 建立链表
class LinkList(object):
def __init__(self):
self.head = None
# 类似于尾插法初始化链表
def initList(self,data):
self.head = ListNode(data[0])
p = self.head
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
class Solution:
def middleNode(self, head:ListNode) -> ListNode:
# 数组,空间和时间复杂度都是O(N)
A = [head]
while A[-1].next:
A.append(A[-1].next)
return A[len(A)//2]
class Solution1:
def middleNode(self, head:ListNode) -> ListNode:
# 单指针法两次遍历,空间O(1),时间复杂度都是O(N)
n, cur = 0, head
while cur:
n += 1
cur = cur.next
k, cur = 0, head
while cur:
k += 1
cur = cur.next
return cur
class Solution2:
def middleNode(self, head:ListNode) -> ListNode:
# 快慢指针
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
if __name__ == '__main__':
data = [1,2,3,4,5]
l = LinkList()
l.initList(data)
s = Solution()
print(s.middleNode(l.head)) | false |
183566bd154e64127d97cda018a0e524cdbc9f62 | anjalisaraarun/campk12python | /circlee.py | 581 | 4.1875 | 4 | import turtle
def circle():
print('Hello')
circle()
def draw_circle(turtle,color,size,x,y):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x,y)
turtle.pendown()
turtle.begin_fill()
turtle.circle(size)
turtle.end_fill()
turtuga = turtle.Turtle()
turtuga.shape('turtle')
turtuga.speed(10)
draw_circle(turtuga,'green',50,0,0)
draw_circle(turtuga,'blue',50,-50,0)
draw_circle(turtuga,'yellow',50,-100,0)
turtle.penup()
turtle.goto(-70,-50)
turtle.color('green')
turtle.write("Let's learn Python!")
turtle.done()
| false |
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 |
33df38eafae8d6f4cf4ef33ead92b816e0a7aa12 | Zadams1989/programming-GitHub | /Ch 7 TeleTranslator CM.py | 1,131 | 4.125 | 4 | number=input("Enter a phone number to be translated:\n")
def teletranslator(phone=number):
phone = phone.replace('A', '2')
phone = phone.replace('B', '2')
phone = phone.replace('C', '2')
phone = phone.replace('D', '3')
phone = phone.replace('E', '3')
phone = phone.replace('F', '3')
phone = phone.replace('G', '4')
phone = phone.replace('H', '4')
phone = phone.replace('I', '4')
phone = phone.replace('J', '5')
phone = phone.replace('K', '5')
phone = phone.replace('L', '5')
phone = phone.replace('M', '6')
phone = phone.replace('N', '6')
phone = phone.replace('O', '6')
phone = phone.replace('P', '7')
phone = phone.replace('Q', '7')
phone = phone.replace('R', '7')
phone = phone.replace('S', '7')
phone = phone.replace('T', '8')
phone = phone.replace('U', '8')
phone = phone.replace('V', '8')
phone = phone.replace('W', '9')
phone = phone.replace('X', '9')
phone = phone.replace('Y', '9')
phone = phone.replace('Z', '9')
return phone
print(teletranslator())
| false |
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 |
4a89b00907c8cf026de45269ff5728a68d7fe296 | Ayush10/CSC-3530-Advance-Programming | /area_of_traiangle.py | 573 | 4.375 | 4 | # Importing Math
# import math
# Program to calculate Area of Triangle
# Formula: [Area of a triangle = (s*(s-a)*(s-b)*(s-c))-1/2]
print("Enter three sides of a triangle")
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))
# Calculating Semi-Perimiter
s = (a + b + c) / 2
# Calculating Area using formula
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
# area = math.sqrt((s * (s - a) * (s - b) * (s - c)))
print("THe value of semi-perimeter is : %0.2f" %s)
print("The area of a triangle is : %0.2f" %area) | false |
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 |
b60e640d867c6964f52743c79ed44ba8650c89f9 | rajkamal-v/PythonLessons1 | /numbers.py | 801 | 4.15625 | 4 | num1 = 10
num2 = 20
num3 = 30; num4 = 40
num5 = num6 = 50
# 50 <----- num6, num5
num7, num8, name = 60, 70.90, 'Python'
print(num7)
print(num8)
print(name)
name1 = "\"I am also a \"String\"" # '\' is an escape character
name2 = "I'm a string"
with_backslash = "i\'m a\tthing" #\n - it is a newline character; \t is for tab
print(name1)
print(name2)
print(with_backslash)
str = '''i am a multiline string
And i will be coming in several lines
thank you
'''
print(str)
m_str2 = """
i am a multiline string
And i will be coming in several lines
thank you
"""
#mutable vs immutable
new_name = 'pyth0n'
print(id(new_name))
new_name = 'python'
print(id(new_name))
'''
'pyth0n' <------
'python' <------- new_name
'''
print(id('pyth0n'))
| false |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.