blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
742c5ac2d2489f134733d4279f2bb25f17da2665 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/951 Flip Equivalent Binary Trees.py | 1,402 | 4.375 | 4 | #!/usr/bin/python3
"""
For a binary tree T, we can define a flip operation as follows: choose any node,
and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make
X equal to Y after some number of flip operations.
Write a function that determines whether two binary trees are flip equivalent.
The trees are given by root nodes root1 and root2.
Example 1:
Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Output: true
Explanation: We flipped at nodes with values 1, 3, and 5.
Flipped Trees Diagram
Note:
Each tree will have at most 100 nodes.
Each value in each tree will be a unique integer in the range [0, 99].
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
"""
O(N)
"""
if not root1 and not root2:
return True
elif not root1 or not root2:
return False
if root1.val != root2.val:
return False
return self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right) or \
self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)
| true |
79113c1c090a21d89d40a6588bbd9637c9cbfb1b | syurskyi/Algorithms_and_Data_Structure | /Python for Data Structures Algorithms/template/16 Trees/PRACTICE/Trim a Binary Search Tree.py | 1,563 | 4.21875 | 4 | # Trim a Binary Search Tree
# Problem Statement
# Given the root of a binary search tree and 2 numbers min and max, trim the tree such that all the numbers in the new
# tree are between min and max (inclusive). The resulting tree should still be a valid binary search tree.
# So, if we get this tree as input:
# title
# and we are given min value as 5 and max value as 13, then the resulting binary search tree should be:
# title
# We should remove all the nodes whose value is not between min and max.
# ** Feel free to reference the lecture on Binary Search Tree for the node class, but what it more important here is
# the logic of your function. In which case your function should be in the form:**
#
# # 669. Trim a Binary Search Tree
class Solution:
def trimBST(self, root, min_val, max_val):
"""
:type root: TreeNode
:type min_val: int
:type max_val: int
:rtype: TreeNode
"""
if not root:
return None
if root.val < min_val:
return self.trimBST(root.right, min_val, max_val)
if root.val > max_val:
return self.trimBST(root.left, min_val, max_val)
root.left = self.trimBST(root.left, min_val, max_val)
root.right = self.trimBST(root.right, min_val, max_val)
return root
# ** There is no solution cell because the nature of the code should be more logical and a test would essentially give
# away the answer. Just focus your answer to fill out the logic of the solution using the methods described above **
# Best of luck! | true |
f73e6f2de88634e45a4411e0a375430bc0ec99b6 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/991 Broken Calculator.py | 2,145 | 4.5 | 4 | #!/usr/bin/python3
"""
On a broken calculator that has a number showing on its display, we can perform
two operations:
Double: Multiply the number on the display by 2, or;
Decrement: Subtract 1 from the number on the display.
Initially, the calculator is displaying the number X.
Return the minimum number of operations needed to display the number Y.
Example 1:
Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: X = 5, Y = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: X = 3, Y = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Example 4:
Input: X = 1024, Y = 1
Output: 1023
Explanation: Use decrement operations 1023 times.
Note:
1 <= X <= 10^9
1 <= Y <= 10^9
"""
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
"""
004_greedy + work backward
If Y is odd, we can do only Y = Y + 1
If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1.
And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2.
We always choose Y / 2 if Y is even.
"""
t = 0
while Y > X:
if Y % 2 == 0:
Y //= 2
else:
Y += 1
t += 1
return t + X - Y
def brokenCalc_TLE(self, X: int, Y: int) -> int:
"""
BFS
"""
q = [X]
t = 0
has_larger = False
while q:
cur_q = []
for e in q:
if e == Y:
return t
cur = e * 2
if cur >= 1:
if cur > Y and not has_larger:
has_larger = True
cur_q.append(cur)
elif cur <= Y:
cur_q.append(cur)
cur = e - 1
if cur >= 1:
cur_q.append(cur)
q = cur_q
t += 1
raise
if __name__ == "__main__":
assert Solution().brokenCalc(2, 3) == 2
| true |
a2653c07c65e81aff304d0b3e50810129418aff7 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codewar/_Codewars-Solu-Python-master/src/kyu-_Linked_Lists-Iterative_Reverse.py | 1,838 | 4.25 | 4 | class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
class Solution():
"""
https://www.codewars.com/kata/linked-lists-iterative-reverse
Linked Lists - Iterative Reverse
Write an iterative Reverse() function that reverses a linked list.
Ideally, Reverse() should only need to make one pass of the list.
var list = 2 -> 1 -> 3 -> 6 -> 5 -> null
reverse(list)
list === 5 -> 6 -> 3 -> 1 -> 2 -> null
The push() and buildOneTwoThree() functions need not be redefined.
Related Kata in order of expected completion (increasing difficulty):
Linked Lists - Push & BuildOneTwoThree
Linked Lists - Length & Count
Linked Lists - Get Nth Node
Linked Lists - Insert Nth Node
Linked Lists - Sorted Insert
Linked Lists - Insert Sort
Linked Lists - Append
Linked Lists - Remove Duplicates
Linked Lists - Move Node
Linked Lists - Move Node In-place
Linked Lists - Alternating Split
Linked Lists - Front Back Split
Linked Lists - Shuffle Merge
Linked Lists - Sorted Merge
Linked Lists - Merge Sort
Linked Lists - Sorted Intersect
Linked Lists - Iterative Reverse
Linked Lists - Recursive Reverse
Inspired by Stanford Professor Nick Parlante's
excellent Linked List teachings.
"""
def __init__(self):
pass
def reverse_01(self, head):
"""
"""
if not head:
return None
node = head
node_new = None
while node:
if node_new:
node_ = node_new
node_new = Node(node.data)
node_new.next = node_
else:
node_new = Node(node.data)
node = node.next
head.data = node_new.data
head.next = node_new.next
| true |
a9316bdb129cb49e788caf91ac74c3304578dba2 | syurskyi/Algorithms_and_Data_Structure | /_temp/Python for Data Structures Algorithms/template/15 Recursion/Recursion Interview Problems/PRACTICE/Recursion Problem 2 - String Permutation.py | 1,228 | 4.125 | 4 | # String Permutation
# Problem Statement
# Given a string, write a function that uses 001_recursion to output a list of all the possible permutations of that string.
# For example, given s='abc' the function should return ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
# Note: If a character is repeated, treat each occurence as distinct, for example an input of 'xxx' would return
# a list with 6 "versions" of 'xxx'
# Fill Out Your Solution Below
#
# Let's think about what the steps we need to take here are:
___ permute(s
output _ # list
__ l..(s) <_ 1:
output_[s]
____
___ i, let __ enumerate(s
___ perm __ permute(s[:i]+s[i+1:]
output+_[let+perm]
r_ output
permute('abc')
# ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
#
# Test Your Solution
#
# """
# RUN THIS CELL TO TEST YOUR SOLUTION.
# """
____ n___.t.. ______ assert_equal
c_ TestPerm o..
___ testsolution
? s..(solution('abc')),s..(['abc', 'acb', 'bac', 'bca', 'cab', 'cba']))
? s..(solution('dog')),s..(['dog', 'dgo', 'odg', 'ogd', 'gdo', 'god']) )
print ('All test cases passed.')
# # Run Tests
t _ TestPerm()
t.test(permute)
#
# All test cases passed.
#
# Good Luck! | true |
b9cd2ec3eddb3da1747fdc852f5ecca70c5dc50b | syurskyi/Algorithms_and_Data_Structure | /Algorithms and Data Structures in Python (INTERVIEW Q&A)/template/Section 5 Interview Questions Array/14.PalindromeCheck.py | 872 | 4.15625 | 4 | #
# # it has O(s) so basically linear running time complexity as far as the number
# # of letters in the string is concerned
# ? ? is_palindrome s
#
# original_string _ ?
# # this is what we have implemented in the previous lecture in O(N)
# reversed_string _ r.. ?
#
# __ ? __ ?
# r_ T..
#
# r_ F..
#
#
# # O(N) linear running time where N is the number of letters in string s N=len(s)
# ? ? reverse data
#
# # string into a list of characters
# data _ l.. ?
#
# # pointing to the first item
# start_index _ 0
# # index pointing to the last item
# end_index _ l.. ?-1
#
# _____ ? > ?
# # keep swapping the items
#
# ? ?, ? ? _ ? ?, ? ?
# s.. _ ? + 1
# e.. _ ? - 1
#
# # transform the list of letters into a string
# r_ ''.j.. ?
#
#
# __ _____ __ ____
# print(?('Kevin'))
| false |
6f1ff3a3b16c190fe8967efdace456554e6d9aef | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/1021 Remove Outermost Parentheses.py | 2,688 | 4.15625 | 4 | #!/usr/bin/python3
"""
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where
A and B are valid parentheses strings, and + represents string concatenation.
For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
A valid parentheses string S is primitive if it is nonempty, and there does not
exist a way to split it into S = A+B, with A and B nonempty valid parentheses
strings.
Given a valid parentheses string S, consider its primitive decomposition:
S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
Return S after removing the outermost parentheses of every primitive string in
the primitive decomposition of S.
Example 1:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition
"(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" +
"()(())" = "()()()()(())".
Example 3:
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Note:
S.length <= 10000
S[i] is "(" or ")"
S is a valid parentheses string
"""
from collections import deque
class Solution:
def removeOuterParentheses(self, S: str) -> str:
"""
Primitive parentheses will have equal number of opened and closed
parentheses.
Use count
Exclude the first and last parathesis
"""
ret = []
cnt = 0
for e in S:
if e == "(":
cnt += 1
if cnt > 1:
ret.append(e)
else:
cnt -= 1
if cnt > 0:
ret.append(e)
return "".join(ret)
def removeOuterParentheses_error(self, S: str) -> str:
"""
stack + deque
"""
ret = []
stk = []
cur_q = deque()
for e in S:
if e == "(":
stk.append(e)
else:
prev = stk.pop()
if stk:
cur_q.appendleft(prev)
cur_q.append(e)
else:
ret.extend(cur_q)
cur_q = deque()
return "".join(ret)
if __name__ == "__main__":
assert Solution().removeOuterParentheses("(()())(())(()(()))") == "()()()()(())"
| true |
1a4cef5f104564e6c4a57c5ee5a73f09d0ce7564 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codewar/_Codewars-Solu-Python-master/src/kyu6_Linked_Lists-Sorted_Intersect.py | 2,164 | 4.125 | 4 | class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
class Solution():
"""
https://www.codewars.com/kata/linked-lists-sorted-intersect
Linked Lists - Sorted Intersect
Write a SortedIntersect() function which creates and returns a list representing
the intersection of two lists that are sorted in increasing order.
Ideally, each list should only be traversed once.
The resulting list should not contain duplicates.
var first = 1 -> 2 -> 2 -> 3 -> 3 -> 6 -> null
var second = 1 -> 3 -> 4 -> 5 -> -> 6 -> null
sortedIntersect(first, second) === 1 -> 3 -> 6 -> null
Related Kata in order of expected completion (increasing difficulty):
Linked Lists - Push & BuildOneTwoThree
Linked Lists - Length & Count
Linked Lists - Get Nth Node
Linked Lists - Insert Nth Node
Linked Lists - Sorted Insert
Linked Lists - Insert Sort
Linked Lists - Append
Linked Lists - Remove Duplicates
Linked Lists - Move Node
Linked Lists - Move Node In-place
Linked Lists - Alternating Split
Linked Lists - Front Back Split
Linked Lists - Shuffle Merge
Linked Lists - Sorted Merge
Linked Lists - Merge Sort
Linked Lists - Sorted Intersect
Linked Lists - Iterative Reverse
Linked Lists - Recursive Reverse
Inspired by Stanford Professor Nick Parlante's excellent Linked List teachings.
"""
def __init__(self):
pass
def sorted_intersect_01(self, first, second):
"""
"""
if not first or not second:
return None
node_new = None
while first and second:
if first.data == second.data:
if node_new and node_new.data != first.data:
node.next = Node(first.data)
node = node.next
else:
node_new = node = Node(first.data)
first = first.next
second = second.next
elif first.data < second.data:
first = first.next
else:
second = second.next
return node_new
| true |
75066f5c660fb1d4dae08ecc322845d0676ad360 | syurskyi/Algorithms_and_Data_Structure | /Linked List Data Structure using Python/src/Section 8 Circular Linked List/1.circularSinglyLinkedList.py | 1,780 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertEnd(self, newNode):
if self.head is None:
self.head = newNode
newNode.next = self.head
return
currentNode = self.head
while(currentNode.next is not self.head):
currentNode = currentNode.next
currentNode.next = newNode
newNode.next = self.head
def insertHead(self, newNode):
lastNode = self.head
while(lastNode.next is not self.head):
lastNode = lastNode.next
previousHead = self.head
self.head = newNode
newNode.next = previousHead
lastNode.next = self.head
def deleteEnd(self):
lastNode = self.head
while(lastNode.next is not self.head):
previousNode = lastNode
lastNode = lastNode.next
lastNode.next = None
previousNode.next = self.head
def deleteHead(self):
lastNode = self.head
while(lastNode.next is not self.head):
lastNode = lastNode.next
previousHead = self.head
self.head = self.head.next
lastNode.next = self.head
previousHead.next = None
def printList(self):
currentNode = self.head
while True:
print(currentNode.data)
currentNode = currentNode.next
if currentNode is self.head:
break
print(currentNode.data)
nodeOne = Node(10)
nodeTwo = Node(20)
nodeThree = Node(30)
linkedList = LinkedList()
linkedList.insertEnd(nodeOne)
linkedList.insertEnd(nodeTwo)
linkedList.insertEnd(nodeThree)
linkedList.deleteHead()
linkedList.printList()
| false |
f96cb099f22868e627c4a96de9c9d19d4329ce44 | syurskyi/Algorithms_and_Data_Structure | /Linked List Data Structure using Python/src/Section 7 Brain Teasers - Doubly Linked List/DLL-Medium.py | 2,248 | 4.3125 | 4 | # Swap the first node and last node of a doubly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class LinkedList:
def __init__(self):
self.head = None
def insertEnd(self, newNode):
if self.head is None:
self.head = newNode
return
currentNode = self.head
while currentNode.next is not None:
currentNode = currentNode.next
currentNode.next = newNode
newNode.previous = currentNode
def swapHead(self):
if self.head is None:
print("Empty list")
return
# List has just 1 Node
if self.head.next is None:
return
lastNode = self.head
while lastNode.next is not None:
lastNode = lastNode.next
currentHead = self.head
# Change previous pointer of head
self.head.previous = lastNode.previous
# Change previous pointer of next node of head
self.head.next.previous = lastNode
# Change next pointer of last node
lastNode.next = self.head.next
# Change next pointer of previous node of last node
lastNode.previous.next = self.head
# Change next pointer of head
self.head.next = None
# Change previous pointer of last node
lastNode.previous = None
# Make last node as head node
self.head = lastNode
def printList(self):
if self.head is None:
print("Empty list")
return
currentNode = self.head
print("Printing from beginning")
while True:
print(currentNode.data)
if currentNode.next is None:
break
currentNode = currentNode.next
print("Printing from end")
while True:
print(currentNode.data)
if currentNode.previous is None:
break
currentNode = currentNode.previous
nodeOne = Node(10)
nodeTwo = Node(30)
nodeThree = Node(15)
linkedList = LinkedList()
linkedList.insertEnd(nodeOne)
linkedList.insertEnd(nodeTwo)
linkedList.insertEnd(nodeThree)
linkedList.swapHead()
linkedList.printList()
| true |
837b0f855c0aad81cf7a92e540e4682550dedd77 | syurskyi/Algorithms_and_Data_Structure | /Python for Data Structures Algorithms/src/13 Stacks Queues and Deques/Stacks, Queues, and Deques Interview Problems/PRACTICE/Implement a Queue.py | 676 | 4.375 | 4 | # %%
'''
# Implement a Queue
It's very common to be asked to implement a Queue class! The class should be able to do the following:
* Check if Queue is Empty
* Enqueue
* Dequeue
* Return the size of the Queue
'''
# %%
class Queue(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, e):
self.items.insert(0, e)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
pass
# %%
q = Queue()
q.is_empty()
q.enqueue(1)
q.enqueue('two')
q.enqueue(3)
q.size()
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
q.is_empty()
# %%
| true |
57cc17bc6448dfa3f86bee88a09d45fa9f1197cc | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/589 N-ary Tree Preorder Traversal.py | 803 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note:
Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
from typing import List
class Solution:
def preorder(self, root: "Node") -> List[int]:
"""
reversely add the children to stk
"""
ret = []
if not root:
return ret
stk = [root]
while stk:
cur = stk.pop()
ret.append(cur.val)
for c in reversed(cur.children):
stk.append(c)
return ret
| true |
630b845ab4e00d6f2e512ebd7c0f1d2f55604a69 | syurskyi/Algorithms_and_Data_Structure | /Python for Data Structures Algorithms/exercise/18 Graph Algorithms/Graph Interview Questions - PRACTICE/Implement a Graph.py | 2,533 | 4.40625 | 4 | # Implement a Graph Class!
# That's it!
# Best of luck and reference the video lecture for any questions!
# You have to fully worked out implementations in the lectures, so make sure to refer to them!
class Graph:
'''
In order to implement a Graph as an Adjacency List what we need to do is define the methods our Adjacency List object will have:
Graph() creates a new, empty graph.
addVertex(vert) adds an instance of Vertex to the graph.
addEdge(fromVert, toVert) Adds a new, directed edge to the graph that connects two vertices.
addEdge(fromVert, toVert, weight) Adds a new, weighted, directed edge to the graph that connects two vertices.
getVertex(vertKey) finds the vertex in the graph named vertKey.
getVertices() returns the list of all vertices in the graph.
in returns True for a statement of the form vertex in graph, if the given vertex is in the graph, False otherwise.
'''
def __init__(self):
# self.nodes = set() # all the vertexes in the graph -- could be done in the edges part
self.connections = {} # all the connections start_vertex:{end_vertex:weigth}
# def add_node(self, node):
# self.nodes.add(node)
def contains(self, v):
return v in self.connections.keys()
def connect(self, start, end, weight=1):
# v = self.get_vertex(str(from_vertex)) or Vertex(str(from_vertex))
if start not in self.connections:
self.connections[start] = {end:weight}
else:
self.connections[start][end] = weight
if end not in self.connections:
self.connections[end] = {}
def get_nodes(self):
return self.connections.keys()
# assume there is one and only one start node (no one points to it) in the directed graph
def get_start_vertex(self):
cadidates = set(self.get_nodes())
for end in self.connections.values():
for k in end.keys():
if k in cadidates:
cadidates.remove(k)
# return set(self.get_nodes()) - set(end_nodes)
return cadidates
def paint(self):
print(self.connections)
g = Graph()
# v1 = Node(1)
g.connect(1, 2)
g.connect(1,3)
g.connect(1,4)
g.connect(2,4)
g.connect(2,5)
g.connect(3,5)
g.connect(5,4)
g.paint()
# {1: {2: 1, 3: 1, 4: 1}, 2: {4: 1, 5: 1}, 3: {5: 1}, 4: {}, 5: {4: 1}}
#
g.get_nodes()
# dict_keys([1, 2, 3, 4, 5])
g.get_start_vertex()
#
# {1}
#
type(g.get_start_vertex())
# set
#
s = set([1,2,3])
#
s
#
# {1, 2, 3}
#
# Good Luck! | true |
4978f195d8b16149e675ca6991bc5b73f0400926 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/pybites/PyBites-master/Bite 143. Look up a value in 3 dictionaries.py | 1,154 | 4.4375 | 4 | """ In this Bite you are presented with 3 dictionaries.
Complete get_person_age that takes a name as argument and
returns the age if in any of the 3 dictionaries.
The lookup should be case insensitive, so tim, Tim and tiM
should all yield 30. If not in any of the dictionaries, return Not found.
Note that some persons are in 2 of the 3 dictionaries.
In that case return the age of the last dictionaries
(so group3 takes precedence over group2 and group2 takes precedence over group1).
Check out the standard library ... :) - have fun! """
from collections import ChainMap
NOT_FOUND = "Not found"
group1 = {'tim': 30, 'bob': 17, 'ana': 24}
group2 = {'ana': 26, 'thomas': 64, 'helen': 26}
group3 = {'brenda': 17, 'otto': 44, 'thomas': 46}
for i in group1, group2, group3:
print(i['brenda'])
def get_person_age(name):
"""Look up name (case insensitive search) and return age.
If name in > 1 dict, return the match of the group with
greatest N (so group3 > group2 > group1)
"""
name = str(name).lower()
dict_set = ChainMap(group1, group2, group3)
return dict_set.get(name, NOT_FOUND)
get_person_age(None) | true |
4c6b752e1c97b1e36a73919934065f3a1106636d | dunber123/CIS2348 | /Homework1/Homework2.19.py | 1,202 | 4.15625 | 4 |
lemon = float(input("Enter amount of lemon juice (in cups):\n"))
water = float(input("Enter amount of water (in cups):\n"))
agave = float(input("Enter amount of agave nectar (in cups):\n"))
serves = float(input("How many servings does this make?\n"))
print('\nLemonade ingredients - yields','{:.2f}'.format(serves), 'servings')
print('{:.2f}'.format(lemon), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agave), 'cup(s) agave nectar\n')
serve_req = float(input("How many servings would you like to make?\n"))
print('\nLemonade ingredients - yields', '{:.2f}'.format(serve_req), 'servings')
serv = serve_req/serves
lemon = lemon * serv
water = water * serv
agave = agave * serv
print('{:.2f}'.format(lemon), 'cup(s) lemon juice')
print('{:.2f}'.format(water), 'cup(s) water')
print('{:.2f}'.format(agave), 'cup(s) agave nectar')
print('\nLemonade ingredients - yields', '{:.2f}'.format(serve_req), 'servings')
lemon = lemon / 16
water = water / 16
agave = agave / 16
print('{:.2f}'.format(lemon), 'gallon(s) lemon juice')
print('{:.2f}'.format(water), 'gallon(s) water')
print('{:.2f}'.format(agave), 'gallon(s) agave nectar')
| true |
64ad807a5be48ef3dd22a97c49837df1f12ca6cf | ramfay/Exam_prep | /cheaper_product.py | 941 | 4.21875 | 4 | """
Write a function that calculates which of two products is cheaper based on a quantity and price.
The function will take 4 parameters - the quantity and price of each product,
and output either "First" or "Second".
"""
def main():
print("For the first product, enter the following:")
first_quantity = int(input("Quantity: "))
first_price = float(input("Price: $"))
print("For the second product, enter the following:")
second_quantity = int(input("Quantity: "))
second_price = float(input("Price: $"))
calculate_which_product_cheaper(first_quantity, first_price, second_quantity, second_price)
def calculate_which_product_cheaper(first_quantity, first_price, second_quantity, second_price):
first_total_cost = first_quantity * first_price
second_total_cost = second_quantity * second_price
if first_total_cost < second_total_cost:
print("First")
else:
print("Second")
main() | true |
a3db449b8112c579421fa1e3cc11d0dc2cf28c2c | JamesPagani/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 887 | 4.375 | 4 | #!/usr/bin/python3
"""Square class v4.
Instances a 'Square' class with:
One integer attribute ('size').
One method ('area').
Unlike v3., this version now comes with the getters and setters.
"""
class Square:
"""Defines a Square with a size attribute."""
def __init__(self, size=0):
"""Initialize an instance."""
self.__size = size
def area(self):
"""Calculate the square area of this square."""
return self.__size ** 2
@property
def size(self):
"""Get this square's size."""
return self.__size
@size.setter
def size(self, value):
"""Set this square's size."""
if isinstance(value, int) is False:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
| true |
0e8c9c4516a46a746161ce891f1683a8454838b1 | JamesPagani/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 442 | 4.28125 | 4 | #!/usr/bin/python3
"""My list.
Write a class MyList that inherits from list:
METHODS:
+ print_sorted(self) - Prints the list, but sorted (does not modify
original list)
Only tested with lists filled with integers.
"""
class MyList(list):
"""A class derived from the list built-in class."""
def print_sorted(self):
"""Print a sorted list. Does not modify the original."""
print(sorted(self))
| true |
63f81b78cd56a569dd6006d9598b8f44e888ac11 | g4vil/100DaysofPython | /day 2/day 2.py | 2,584 | 4.3125 | 4 | #!/bin/python
#data types
#String
"Hello"
print("Hello"[0]) #print H
print("123"+"456")
#Integer (number without decimals)
print(123+456)
123456789
123_456_789
#Float
3.1416
#Boolean
True
False
#type()
num_char = len(input("What's your name?"))
new_num_char = str(num_char)
print("Your name has "+new_num_char+" characters.")
type(num_char)
str(), int(), float()
#2.1 Code Challenge
# 🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
# 🚨 Don't change the code above 👆
####################################
#Write your code below this line 👇
print(int(two_digit_number[0]) + int(two_digit_number[1]))
#Aritmetic
3 + 5
7 - 4
3 * 2
6 / 3 #return a float
4 ** 2
4 % 2 #return rest
3 // 2 #return integer
#PEMDAS LR
#Parentesis ()
#Exponentes **
#Multiplicacion * Division /
#Adicion + Substracion -
print(3*3/3+3-3)
#Challenge 2
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
new_height = float(height)
new_weight = int(weight)
print(int(new_weight/(new_height**2)))
#Redondeo
print(round(3/2))
print(3//2)
print(round(3/2, 2)) #Numero de decimales despues del punto.
print(f"Your score is {score}")
#Challenge time left
# 🚨 Don't change the code below 👇
age = input("What is your current age?")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
rest = 90 - int(age)
days = rest * 365
weeks = rest * 52
months = rest * 12
print(f"You have {days} days, {weeks} weeks, and {months} months left")
#Challenge TIp Calculator
#If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal
#HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python
print("Welcome to the tip calculator.")
total_bill = float(input("What was the total bill? $ "))
porcentage = int(input("What percentange tip would you like to give? 10, 12, or 15? "))
number_of_persons = int(input("How many people to split the bill? "))
tip = total_bill * (porcentage/100)
total_bill += tip
total_individual = round(total_bill/number_of_persons,2)
print(f"Each person should pay: $ {total_individual}")
| true |
d37efb38daaa2ed1d958b9d34b93a2327dce5f4d | Rantw/CS5590-Python-DL-Session2 | /Lab1/Lab1Part3.py | 2,190 | 4.5 | 4 | # Ronnie Antwiler
# 3 Consider the following scenario. You have a list of students who are attending class "Python" and another list
# of students who are attending class "Web Application".
#
# Find the list of students who are attending both the classes.
# Also find the list of students who are not common in both the classes.
#
# Print the both lists. Consider accepting the input from the console for list of students that belong to
# class “Python” and class “Web Application”.
webClass = []
pythonClass = []
bothClass = []
oneClass = []
cont = 'Y'
while cont != 'n' and cont != 'N':
string = input("Please enter the student name then which classes they are in: "
"(separate name and classes with a comma and space): ")
info = tuple(string.split(', '))
if info[1][0] == 'w' or info[1][0] == "W":
webClass.append(info[0])
elif info[1][0] == 'p' or info[1][0] == "P":
pythonClass.append(info[0])
if len(info) == 3:
if info[2][0] == 'w' or info[2][0] == "W":
webClass.append(info[0])
elif info[2][0] == 'p' or info[2][0] == "P":
pythonClass.append(info[0])
cont = input("Add another student (Y/N): ")
# Sort through the students listed in the python class and check if they are also in the web class. If they are add
# them to the both classes list. If they are not, then add them to the only one class list.
for student in pythonClass:
if student in webClass:
bothClass.append(student)
else:
oneClass.append(student)
# Sort through the web class list and see if they are in the python class. If they are in the python class, then they
# would have already been added to the both classes list. Just those students only in the web class need to be added
# to one class list
for student in webClass:
if student not in pythonClass:
oneClass.append(student)
print("Students in the Python class are:", ', '.join(sorted(pythonClass)))
print("Students in the Web Development class are:", ', '.join(sorted(webClass)))
print("Students in both classes are:", ', '.join(sorted(bothClass)))
print("Students in only one class are:", ', '.join(sorted(oneClass))) | true |
b1cdddd38c920c85f26756acbe206a8bd9a582e3 | Rantw/CS5590-Python-DL-Session2 | /ICP3/ICP3Part2.py | 697 | 4.125 | 4 | # Ronnie Antwiler
# 2. Web scraping
# Write a simple program that parse a Wiki page mentioned below and follow the instructions:
# https://en.wikipedia.org/wiki/Deep_learning
# 1. Parse the source code using the Beautiful Soup library and save the parsed code in a variable
# 2. Print out the title of the page
# 3. Find all the links in the page (‘a’ tag)
# 4. Iterate over each tag(above) then return the link using attribute "href" using get
import requests
from bs4 import BeautifulSoup
import os
url = 'https://en.wikipedia.org/wiki/Deep_learning'
source = requests.get(url)
plain = source.text
soup = BeautifulSoup(plain, 'html.parser')
for div in soup.findAll('a'):
print(div.get('href'))
| true |
946814131887447f548ee847b284413c654a590f | ellen-liu/mini-projects | /palindrome.py | 277 | 4.5 | 4 | '''
January 6, 2017
Program to check if the given string is a palindrome or not.
'''
word = raw_input("Enter a string: ")
def palindrome(word):
if word == word[::-1]:
print "%s is a palindrome :)" % word
else:
print "%s is not a palindrome :(" % word
palindrome(word)
| true |
6875713f1ef751f63d439fbb68a7c951c104dea5 | sparshagarwal16/Assignment | /Assignment4.py | 1,293 | 4.1875 | 4 | print("TUPLE")
print("Question 1")
#TUPLE
#Question 1
t=(2,5,"Apple","Google")
print(t)
print(len(t))
print("Question 2")
#Question 2
x=(2,3,56,48)
y=("Apple","Google","Microsoft","Adobe")
print(max(x))
print(min(x))
print(max(y))
print(min(y))
print("Question 3")
#Question 3
z=1
for i in x:
z=z*i
print("Product of the elements of the Tuple are ",z)
print("SETS")
print("Question 1")
#SETS
#Question 1
print("First set")
s=set()
n=int(input("Enter total number of elements "))
for f in range(n):
s1=input("Enter a value ")
s.add(s1)
print(s)
print("Second set")
w=set()
e=int(input("Enter total number of elements "))
for f in range(e):
w1=input("Enter a value ")
w.add(w1)
print(w)
r=s-w
print("Difference: ",r)
q=s<=w
print("Comaprision: ",q)
z=s>=w
print("Comparsion: ",z)
print("Intersection: ",s&w)
print("Dictionaries")
print("Question 1")
#Dictionaries
#Question 1
dict={}
for l in range(2):
student_name= input("Enter name of the student ")
marks=int(input("Enter marks of the student "))
dict[student_name]=marks
print(dict)
print("Question 2")
#Question 2
s=sorted(dict.items(),key=lambda t:t[1])
print(s)
print("Question 3")
#Question 3
s="MISSISSIPPI"
d={}
d["M"]=s.count("M")
d["I"]=s.count("I")
d["S"]=s.count("S")
d["P"]=s.count("P")
print(d) | false |
df29b6b635d4f648e79aafb9ba73c48fa7da1124 | stevenbooke/MIT-OCW-6.0001 | /ps1/ps1a.py | 515 | 4.21875 | 4 | import math
annual_salary = float(input('Enter your annual salary:'))
portion_saved = float(input('Enter the percent of your salary to save, as a decimal:'))
total_cost = float(input('Enter the cost of your dream home:'))
monthly_salary = annual_salary / 12
portion_down_payment = 0.25
current_savings = 0
r = 0.04
months = 0
while current_savings < portion_down_payment * total_cost:
months += 1
current_savings += portion_saved * monthly_salary + (current_savings * r) / 12
print('Number of months:', months) | true |
779c1aede50783b4f5e00af6ed24d59c97f1e334 | gpeFC/leng_comp | /practica_3.py | 1,132 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
22/08/2013
Emanuel G.P.
Lenguajes y Compiladores.
Facultad de Ciencias, UAEM.
>>Common I/O operations<<
"""
import sys
import os
import pickle
def read_file(name):
f = open(name, "r")
# Notice that we can iterative thru the file object.
for line in f:
print "->", line,
f.close()
if __name__ == "__main__":
print "Hi there!"
name = raw_input("What's you name? ")
print "Hello {}".format(name)
age = raw_input("How old are you? ")
age = int(age)
print "So, you are {1} years old, {0}".format(name, age)
print "you have lived more than %5.2f months!" % (age*12)
print "\nI will read me thru a function and spit it line by line"
read_file(sys.argv[0])
print "I can also print to a file"
f2 = open("tmp.txt", "w")
f2.write("1 line\n");
f2.write("2 line\n");
f2.write("3 line\n");
f2.write("4 line\n");
f2.write("5 line\n");
f2.close()
print "\nor 'stringify' objects:"
# Look at this.
dict = {'a': [1, 2, 3, 4], 'b': "hola!", 'c': 3.1416}
print pickle.dumps(dict)
| true |
62211b4cce075ee045c04cadac1d3f1c789552a9 | hyunjaemoon/pythonteaching | /Winter 2017/lec7/codingpractice.py | 2,970 | 4.21875 | 4 |
#Link Class is given!
class Link:
"""A linked list.
>>> s = Link(1, Link(2, Link(3)))
>>> s.first
1
>>> s.rest
Link(2, Link(3))
"""
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is Link.empty:
return 'Link({})'.format(self.first)
else:
return 'Link({}, {})'.format(self.first, repr(self.rest))
def __str__(self):
"""Returns a human-readable string representation of the Link
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> str(s)
'<1 2 3 4>'
>>> str(Link(1))
'<1>'
>>> str(Link.empty) # empty tuple
'()'
"""
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'
def __eq__(self, other):
"""Compares if two Linked Lists contain same values or not.
>>> s, t = Link(1, Link(2)), Link(1, Link(2))
>>> s == t
True
"""
if self is Link.empty and other is Link.empty:
return True
if self is Link.empty or other is Link.empty:
return False
return self.first == other.first and self.rest == other.rest
def list_to_link(lst):
"""Takes a Python list and returns a Link with the same elements.
>>> link = list_to_link([1, 2, 3])
>>> link
'Link(1, Link(2, Link(3)))'
"""
"***YOUR CODE HERE***"
def link_to_list(link):
"""Takes a Link and returns a Python list with the same elements.
>>> link = Link(1, Link(2, Link(3, Link(4))))
>>> link_to_list(link)
[1, 2, 3, 4]
>>> link_to_list(Link.empty)
[]
"""
"*** YOUR CODE HERE ***"
def remove_all(link , value):
"""Remove all the nodes containing value. Assume there exists some
nodes to be removed and the first element is never removed.
>>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3)))))))
>>> remove_all(l1, 2)
>>> l1
Link(0, Link(3, Link(1, Link(3))))
>>> remove_all(l1, 3)
>>> l1
Link(0, Link(1))
"""
"*** YOUR CODE HERE ***"
def linked_sum(lnk, total):
"""Return the number of combinations of elements in lnk that
sum up to total .
>>> # Four combinations : 1 1 1 1 , 1 1 2 , 1 3 , 2 2
>>> linked_sum (Link(1, Link(2, Link(3, Link(5)))), 4)
4
>>> linked_sum(Link(2, Link(3, Link(5))), 1)
0
>>> # One combination : 2 3
>>> linked_sum(Link(2, Link(4, Link(3))), 5)
1
"""
"*** YOUR CODE HERE ***"
def has_cycle(s):
"""
>>> has_cycle(Link.empty)
False
>>> a = Link(1, Link(2, Link(3)))
>>> has_cycle(a)
False
>>> a.rest.rest.rest = a
>>> has_cycle(a)
True
"""
"*** YOUR CODE HERE ***"
| true |
69b8ccaf0ecd2c7ae4eec235b834b870d3a41e11 | vimleshtech/python-apr-2020-01 | /1-input-and-output.py | 549 | 4.28125 | 4 | #print example: print and new line
print('hi, this is my test code')
print('i m leaning python ')
#print and don't change line
print('hi, this is my test code ',end=' ') #end is stop word
print('i m leaning python ')
#input example
a = input('enter val ') #default input type is str
b = input('enter val ') #default input type is str
print(type(a)) #print data type
print(type(b)) #print data type
#type casting / type conversion
a = int(a) #convert str to int
b = int(b)
print(type(a)) #print data type
print(type(b)) #print data type
| true |
57e881f9c9ee8cde4fbe0ccf77b997433dcbd747 | oectechcommunity/Code-Ground | /python/Average of three numbers/anuskalenka-1821211011.py | 258 | 4.3125 | 4 | #Write a program to find out average of three numbers.
#Input : 3 numbers
#Output : Average
n1 = int(input("enter first number"))
n2 = int(input("enter second number"))
n3 = int(input("enter third number"))
total = n1+n2+n3
avg = total/3
print("avg is",avg) | true |
cc693bd3c80fe9a29df32b49c1f498c946fd33d2 | oectechcommunity/Code-Ground | /python/Arc length of a circle/1701211030-Jyotsana.py | 298 | 4.3125 | 4 | def arclength():
pi=22/7
diameter = float(input('Diameter of circle: '))
angle = float(input('angle measure: '))
if angle >= 360:
print("Angle is not possible")
return
arc_length = (pi*diameter) * (angle/360)
print("Arc Length is: ", arc_length)
arclength() | true |
e8827304dd01d922aa4217c8f7a448ef17ba6e97 | AmitBaanerjee/Data-Structures-Algo-Practise | /hackerrank/append_delete.py | 2,156 | 4.34375 | 4 | You have a string of lowercase English alphabetic letters. You can perform two types of operations on the string:
Append a lowercase English alphabetic letter to the end of the string.
Delete the last character in the string. Performing this operation on an empty string results in an empty string.
Given an integer, k, and two strings, s and t, determine whether or not you can convert s to t by performing exactly k of the above operations on . If it's possible, print Yes. Otherwise, print No.
For example, strings s=[a,b,c] and t=[d,e,f]. Our number of moves, k=6. To convert s to t, we first delete all of the characters in 3 moves. Next we add each of the characters of t in order. On the 6th move, you will have the matching string. If there had been more moves available, they could have been eliminated by performing multiple deletions on an empty string. If there were fewer than moves, we would not have succeeded in creating the new string.
Function Description
Complete the appendAndDelete function in the editor below. It should return a string, either Yes or No.
appendAndDelete has the following parameter(s):
s: the initial string
t: the desired string
k: an integer that represents the number of operations
Input Format
The first line contains a string , s the initial string.
The second line contains a string , t the desired final string.
The third line contains an integer , k the number of operations.
#!/bin/python3
import math
import os
import random
import re
import sys
def appendAndDelete(s, t, k):
lengths=len(s)
lengtht=len(t)
same=0
if lengths+lengtht<k:
return "Yes"
for i,j in zip(s,t):
if i==j:
same+=1
else:
break
print(same)
differents=lengths-same
differentt=lengtht-same
totaldifferent=differents+differentt
if totaldifferent<=k and totaldifferent%2==k%2:
return "Yes"
else:
return "No"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
t = input()
k = int(input())
result = appendAndDelete(s, t, k)
fptr.write(result + '\n')
fptr.close()
| true |
c0ad1473d3223c63271ae9104646ebd3acacd9d3 | AmitBaanerjee/Data-Structures-Algo-Practise | /leetcode problems/Bigram.py | 935 | 4.1875 | 4 | # 1078. Occurrences After Bigram
#
# Given words first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second.
#
# For each such occurrence, add "third" to the answer, and return the answer.
#
# Example 1:
#
# Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
# Output: ["girl","student"]
# Example 2:
#
# Input: text = "we will we will rock you", first = "we", second = "will"
# Output: ["we","rock"]
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
third=[]
text=text.strip().split()
for i in range(len(text)):
if text[i]==first:
if (i+1<len(text) and text[i+1]==second):
if (i+1+1<len(text)):
third.append(text[i+1+1])
return third
| true |
d71efca22329d3699ea195591893848010a66031 | AmitBaanerjee/Data-Structures-Algo-Practise | /leetcode problems/872.py | 1,245 | 4.21875 | 4 | 872. Leaf-Similar Trees
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1==None or root2==None:
return False
if root1==None and root2==None:
return True
def helper(root,list1):
if root==None:
return
if root.left==None and root.right==None:
list1.append(root.val)
return
helper(root.left,list1)
helper(root.right,list1)
list1=[]
list2=[]
helper(root1,list1)
helper(root2,list2)
if list1==list2:
return True
else:
return False
| true |
cbe213265772c5d81daf18224afd2921728448cd | AmitBaanerjee/Data-Structures-Algo-Practise | /hackerrank/ICPCteam.py | 1,933 | 4.15625 | 4 | There are a number of people who will be attending ACM-ICPC World Finals. Each of them may be well versed in a number of topics. Given a list of topics known by each attendee, you must determine the maximum number of topics a 2-person team can know. Also find out how many ways a team can be formed to know that many topics. Lists will be in the form of bit strings, where each string represents an attendee and each position in that string represents a field of knowledge, 1 if its a known field or 0 if not.
For example, given three attendees' data as follows:
10101
11110
00010
These are all possible teams that can be formed:
Members Subjects
(1,2) [1,2,3,4,5]
(1,3) [1,3,4,5]
(2,3) [1,2,3,4]
In this case, the first team will know all 5 subjects. They are the only team that can be created knowing that many subjects.
Function Description
Complete the acmTeam function in the editor below. It should return an integer array with two elements: the maximum number of topics any team can know and the number of teams that can be formed that know that maximum number of topics.
acmTeam has the following parameter(s):
topic: a string of binary digits
import math
import os
import random
import re
import sys
def acmTeam(topic):
count=[]
for i in range(len(topic)):
for j in range(i+1,len(topic)):
topic1=int(topic[i],2)
topic2=int(topic[j],2)
binary_result="{0:b}".format(topic1|topic2)
one_count=binary_result.count("1")
count.append(one_count)
return max(count),count.count(max(count))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
topic = []
for _ in range(n):
topic_item = input()
topic.append(topic_item)
result = acmTeam(topic)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
42b0057680473e5483ce829d3c127b0139b171e4 | AmitBaanerjee/Data-Structures-Algo-Practise | /hackerrank/diagonal_difference.py | 608 | 4.28125 | 4 | #DIAGONAL DIFFERENCE
#Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
# 1 2 3
# 4 5 6
# 9 8 9
# The left-to-right diagonal = 1+5+9=15. The right to left diagonal =3+5+9=17 . Their absolute difference is 2.
def diagonalDifference(arr):
left_diagonal=0
right_diagonal=0
for i in range(len(arr)):
for j in range(len(arr[i])):
if i==j:
left_diagonal+=arr[i][j]
right_diagonal+=arr[i][(len(arr[0])-1)-j]
return abs(left_diagonal-right_diagonal)
| true |
bb456a38c27c6678d0e62e95b556afb2024eca4e | AmitBaanerjee/Data-Structures-Algo-Practise | /hackerrank/Leaderboard.py | 2,294 | 4.375 | 4 | # Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this:
#
# The player with the highest score is ranked number 1 on the leaderboard.
# Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.
# For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70,80 and 105, her rankings after each game are 4th,3rd and 1st.
#
# Function Description
#
# Complete the climbingLeaderboard function in the editor below. It should return an integer array where each element represents Alice's rank after the jth game.
#
# climbingLeaderboard has the following parameter(s):
#
# scores: an array of integers that represent leaderboard scores
# alice: an array of integers that represent Alice's scores
#!/bin/python3
import math
import os
import random
import re
import sys
from queue import PriorityQueue
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
q,ranking,alice_rank=PriorityQueue(),[],[]
for s in set(scores):
q.put((-s,s))
while not q.empty():
ranking.append(q.get()[1])
length=len(ranking)
for i in alice:
if i<ranking[-1]:
alice_rank.append(len(ranking)+1)
elif i>ranking[0]:
alice_rank.append(1)
elif i in ranking:
alice_rank.append(ranking.index(i)+1)
else:
# while (length>0) and (i>=ranking[length-1]):
# length=length-1
# alice_rank.append(length+1)
for j in range(len(ranking)-1):
if ranking[j]>i and ranking[j+1]<i:
alice_rank.append(j+2)
return alice_rank
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
scores_count = int(input())
scores = list(map(int, input().rstrip().split()))
alice_count = int(input())
alice = list(map(int, input().rstrip().split()))
result = climbingLeaderboard(scores, alice)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
5b0455508448625245393aa669198d9b3ed3e536 | UncleBob2/MyPythonCookBook | /classes.py | 1,184 | 4.5 | 4 | # Classes uses to make objects: contains fields, methods, instances (objects)
# Fields – data attached to an object
# Init is same as constructor
from datetime import date
import datetime
class User: # user1 is an object/instance of User Class a
'''A member of FriendFace. For now we are only storing their name and birthday"""
'''
def __init__(self, full_name, birthday):
self.name = full_name
self.birthday = birthday #yyyymmdd
#Extract first and last name
name_pieces = full_name.split(" ")
self.first_name = name_pieces[0]
self.last_name = name_pieces[-1]
def age(self):
"""Return the age of the user in years."""
today = (date.today())
yyyy = int(self.birthday[0:4])
mm = int(self.birthday[4:6])
dd = int(self.birthday[6:8])
dob = datetime.date(yyyy,mm,dd) #Date of birth
age_in_days = (today - dob).days
age_in_years = age_in_days/365
return int(age_in_years)
user1 = User("Dave Bowman", "19710315")
user2 = User('Arthur Clarke', "20001212")
print(user1.first_name, user1.last_name, user1.age())
print(user2.first_name, user2.last_name, user2.age())
| true |
f8ca16b808371785384966a934a20be4db802ba8 | UncleBob2/MyPythonCookBook | /numeric data.py | 574 | 4.125 | 4 | num = 3.14
print('return the type of a variable using type() = ',type(num))
print('float division 3/2 = ', 3/2)
print('floor division using 3//2 = ', 3//2)
print('Modulus 3 % 2 provides the remainder of the division, = ', 3 % 2 )
num = 1
num +=1
print('num = 1, num += 1 => ', num)
num *=8
print('num = 2, num *= 2 => ', num)
print('print absolute value of a variable', abs(-3))
print('build in rounding number with arg', round(3.75,1))
num_1 = '100'
num_2 = '200'
print('casting string into number for math purposes string "100" + "200" = ', int(num_1)+int(num_2))
| true |
8438b064055ae381e4200bae964c38315bff938b | UncleBob2/MyPythonCookBook | /Intro to Python book/chapter 10/deck of card OOP.py | 2,117 | 4.125 | 4 | import random
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def show(self):
print("{} of {}".format(self.value, self.suit))
class Deck:
def __init__(self):
self.cards = [] # create a list of 52 cards (variable)
self.build() # func
def build(self):
for suit in ["Spaces", "Club", "Hearts", "Diamonds"]:
for value in [
"Ace",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
]:
self.cards.append(Card(value, suit))
def show(self):
for index in self.cards:
index.show()
def shuffle(self):
"""We want to go from the end of our list back to the beginning. We create a for loop in our method, for “i in (range(len(self.cards)) minus 1 (which is the last element and in this case we want to go to zero), 0, -1 decrement)”. If we run the loop we get values 51–1 which is what we want because when we are accessing elements in an array, we want to start with the length minus 1 because the index starts at 0. In this case we want to start at 1 because by the time we shuffle every other card, that 0 index is also going to be shuffled and we don’t want to shuffle that one itself."""
for i in range(len(self.cards) - 1, 0, -1):
r = random.randint(0, i)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
def drawCard(self):
return self.cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.hand = []
def draw(self, deck):
self.hand.append(deck.drawCard())
return self
def showHand(self):
x = self.hand
print(x)
for card in x:
card.show()
deck = Deck()
deck.shuffle()
bob = Player("Bob")
for i in range(5):
bob.draw(deck)
bob.showHand()
| true |
5795c53a22d0a4baaeb20c66153c0a8109afa77a | UncleBob2/MyPythonCookBook | /for loop types.py | 1,438 | 4.625 | 5 |
colors = ["red", "green", "blue", "purple"]
for color in colors:
print(color)
print(colors,"\n")
for i in colors:
print(i)
# For example, let’s say we’re printing out president names along with their numbers (based on list indexes).
# range of length
print("\nrange len indexes example")
presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
for i in range(len(presidents)):
print("President {}: {}".format(i + 1, presidents[i]))
print("\nenumerate example")
#Python’s built-in enumerate function allows us to loop over a list and retrieve
# both the index and the value of each item in the list:
for num, name in enumerate(presidents, start=1):
print("President {}: {}".format(num, name))
#Here we’re looping over two lists at the same time using indexes
# to look up corresponding elements:
print("\nUse indexes to look something up in another list.")
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors):
ratio = ratios[i]
print("{}% {}".format(ratio * 100, color))
#Python’s zip function allows us to loop over multiple lists at the same time without indexes:
print("\nUse zip instead of indexes to look something up in another list.")
colors = ["red", "purple", "green", "blue"]
ratios = [0.3, 0.1, 0.4, 0.2 ]
for color, ratio in zip(colors, ratios):
print("{}% {}".format(ratio * 100, color)) | true |
c884d73e6ecc23d357bfd0788ee998e98e2140e0 | UncleBob2/MyPythonCookBook | /sets more efficient search .py | 771 | 4.40625 | 4 | # Sets = don't care about order, different order each run
# use set to remove duplicate value
# Membership test i.e. more efficent to determine if an element is part of a set
cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math'}
print(cs_courses)
print('Set is best for Membership test, Is "Math" in set? ', 'Math' in cs_courses)
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
art_courses = {'History', 'Math', 'Art', 'Design'}
print('Find similar elements between two sets', cs_courses.intersection(art_courses))
print('Find different elements between two sets', cs_courses.difference(art_courses))
print('Union of two sets', cs_courses.union(art_courses))
# creating empty set
empty_set = set() # can't use empty_set = {}. This is for dictionary
| true |
83aabf33e9f9810ca64b9a64e614d7bd8b4cc1a5 | UncleBob2/MyPythonCookBook | /equality vs identity == and is.py | 915 | 4.28125 | 4 | # what is the difference between "==" and "is"?
# "==" checks for equality (subjective)
# "is" checks for identity (some object in memory)
'''
'coke' == 'pepsi' false
'pepsi' == 'pepsi' true (subjective)
'pepsi' is 'pepsi' only true if same object
if lemon in pepsi, and one without lemon
pepsi == pepsi True
pepsi is pepsi FALSE
'''
l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 4, 5]
l3 = l2
print('memory location', id(l1))
print('memory location', id(l2))
print('memory location', id(l3))
print(id(l1) == id(l2))
print(id(l3) == id(l2))
if l1 is l2: # is checking if the memory address is equal
print("l1 is l2 : ", True)
else:
print("l1 is l2 : ", False)
if l1 == l2:
print("l1 == l2 : ", True)
else:
print("l1 == l2 : ", False)
if l3 is l2:
print("l3 is l2 : ", True)
else:
print("l3 is l2 : ", False)
if l3 == l2:
print("l3 == l2 : ", True)
else:
print("l3 == l2 : ", False)
| false |
bbb5940ddb218ba2266b7cca111e8a42a0c3ac2e | UncleBob2/MyPythonCookBook | /while loop and range function.py | 398 | 4.15625 | 4 | print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
for i in range(0,10,2):
print(i)
print('My name is')
i = 0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i += 1
print('\n\n new range of ascending values by 2')
for i in range(0, 10, 2):
print(i)
print('\n\n new range of descending values')
for i in range(5, -1, -1):
print(i) | false |
bfff9cf0a47ec74daf694230cf53048e5cfebc4b | UncleBob2/MyPythonCookBook | /enumerate object.py | 906 | 4.25 | 4 | names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names, 1):
print(f'{index}: {value}')
'''
# HARMFUL: Don't do this
for i in range(len(my_items)):
print(i, my_items[i])
'''
# Create a list that can be enumerated
L = ['red', 'green', 'blue']
x = list(enumerate(L))
print(x)
# Prints [(0, 'red'), (1, 'green'), (2, 'blue')]
# Start counter from 10
L = ['red', 'green', 'blue']
x = list(enumerate(L, 10))
print(x)
# Prints [(10, 'red'), (11, 'green'), (12, 'blue')]
# When you iterate an enumerate object, you get a tuple containing (counter, item)
L = ['red', 'green', 'blue']
for pair in enumerate(L):
print(pair)
# Prints (0, 'red')
# Prints (1, 'green')
# Prints (2, 'blue')
# You can unpack the tuple into multiple variables as well.
L = ['red', 'green', 'blue']
for index, item in enumerate(L):
print(index, item)
# Prints 0 red
# Prints 1 green
# Prints 2 blue
| true |
3a6b997c916747e92347398868fc984dcf5f0e96 | UncleBob2/MyPythonCookBook | /dictionary exercise.py | 1,749 | 4.34375 | 4 | """Wordcount exercise
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
...
2. For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
so the most common word is first, then the next most common, and so on.
"""
def print_words(filename):
f = open(filename, 'r')
frequency = {}
newfrequency = {}
count = 0
for line in f: # reading line by line
txt = line.lower().split()
print(txt)
# to do, assign each word to the dictionary
# if the word already in a dictionary increase the count
for word in txt:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
for key, value in sorted(frequency.items(), key=lambda item: item[1], reverse=True):
print("%s: %s" % (key, value))
print('\n')
return
def top_counts(filename):
f = open(filename, 'r')
frequency = {}
newfrequency = {}
count = 0
for line in f: # reading line by line
txt = line.lower().split()
# to do, assign each word to the dictionary
# if the word already in a dictionary increase the count
for word in txt:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
for key, value in sorted(frequency.items(), key=lambda item: item[1], reverse=True):
print("%s: %s" % (key, value))
count += 1
if count >= 20:
break
print('\n')
return
# print_words('small.txt')
top_counts('alice.txt')
| true |
0d4c19a93db84bd71638a0980dd4648cb38eeec4 | pbwis/comp-SN | /avg_word_len.py | 436 | 4.15625 | 4 | # Average word length. Special characters excluded.
example = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
def avg_word_len(sentence):
spec_char = ".,':?!" # ignore special characters
for spec in spec_char:
sentence = sentence.replace(spec, '')
words = sentence.split()
avg = sum(len(word) for word in words)/len(words)
return round(avg, 2)
print(avg_word_len(example))
| true |
e0f141c7d6bee73cf8a03cb7adda8513f9f0bf43 | garvsgit/CSE1001_python | /13.10 CLASS DECISION MAKING AND BRANCHING.py | 769 | 4.15625 | 4 | '''a=int(input("Enter A"))
b=int(input("Enter B"))
if b!=0:
print("A/B is",a/b)'''
'''
#if-else
a=int(input("Enter A"))
b=int(input("Enter B"))
if a>b:
print("A is greater")
else:
print("B is greater")
'''
'''a=int(input("Enter A"))
b=int(input("Enter B"))
if a>b:
print("%d is greater"%a)
else:
print("%d is greater"%b)
'''
'''
a=int(input())
b=int(input())
c=int(input())
if a>b:
if a>c:
print("A is greatest")
else:print("C is greatest")
else:
if b>c:
print("B is greatest")
else:
print("C is greatest")
'''
'''
num=19
num1=10
res=num1-num
if(res>0):print("Second number is Greater")
elif(res==0):print("The numbers are equal")
else:print("First number is Greater")
'''
avg=10
if(5=<avg<=10):print("Yes")
| false |
bad4db47e23df6a5c7fa47ceb9c42acbcec09f2a | helgistein/Tile-traveller | /tiletraveller.py | 1,386 | 4.34375 | 4 | #1. Declare all variables that will be used in the excercise
#2. Design how the grid is setup
#3. Figure out how the player will move
#4. code how the player and the grid will interact.
#5. set boundaries as to where the player can and can not move
#6. Make it so the player will be able to go back and forth
#n/N up
#e/E right
#s/S down
#w/W left
#You can travel: (N)orth.
#Direction: s
#Not a valid direction!
#Direction: n
#You can travel: (N)orth or (E)ast or (S)outh.
#Direction: N
#reytur 1,1 möguleikar n/N up
#reytur 1,2 möguleikar n/N up, e/E right, s/S down
#reytur 1,3 möguleikar e/E right, s/S down
#reytur 2,1 möguleikar n/N up
#reytur 2,2 möguleikar w/W left, s/S down
#reytur 2,3 möguleikar e/E right, w/W right
#reytur 3,1 möguleikar n/N up
#reytur 3,2 möguleikar n/N up, s/S down
#reytur 3,3 möguleikar s/S down, w/W left
north = "(N)orth"
south = "(S)outh"
east = "(E)ast"
west = "(W)est"
i = 1
j = 1
location = (i, j)
while i != 3 and j != 1:
print("You can travel: (N)orth")
direction = input("Direction: ")
while direction == ("s", "e", "w"):
direction = input("Direction: ")
if direction == "n":
j += 1
else:
print("Not a valid direction!")
elif i == 1 and j == 2:
print("You can travel: (N)orth or (E)ast or (S)outh. ")
direction = input("Direction: ")
while direction
| true |
53ab7730738f9857c2e35df1ae425938c675a1bc | valdezemanuel25/IntroProjects | /game.py | 1,332 | 4.125 | 4 | import random
#This is a rock paper scissors game using functions to play with the computer
# this is a function becuase is started as def and has a set of instructions
def play():
# get user input to start the game
user = input("Rock = r, Paper = p, Scissors = s\n")
# set a list and random.choice tells pycharm to get a random letter from the list
computer = random.choice(['r','p','s'])
print(f'{user} vs {computer}')
# the == compares two variables
if user == computer:
return 'It\s a tie'
# this calls the function player_wins() and passes user&computer has parameters
if player_wins(user,computer):
return 'You won'
# this is outside the if staements becuase if neither are true then the player lost
return 'You lost'
# a function that needs parameters to work
def player_wins(player,oppenent):
#return true if player wins
#r>s, s>p, p>r these are the choices for the player to win
# it will run thru every scenario if one is true then it will return true otherwise returns false
if(player == 'r' and oppenent == 's') or (player == 's' and oppenent == 'p')\
or (player == 'p' and oppenent == 'r'):
return True
# if we used functions we need to call them in order for python to execute the steps we coded so we type..
print(play())
| true |
66e5064126a6e7e8fdf9638306b951950d5ec03a | xzang1/Learning-Python--bootcamp- | /Python day2.py | 1,708 | 4.1875 | 4 | name=input("please enter your name:")
age= input("please enter your age:")
print('My name is ',name, ' and my age is ', age)
first_name=input("Please enter your first name:")
last_name=input("Please enter your last name:")
full_name=first_name+" "+last_name
print('Hello, my name is {} and my age is {}'.format(full_name,age))
#Afternoon class
def print_lyrics():
print("Hey Jude, don't make it bad.")
print("Take a sad song and make it better.")
print_lyrics()
def repeat_lyrics():
print_lyrics()
print('Na- na- na- na- na- na- na- na- na- na\n'*5)
print_lyrics()
repeat_lyrics()
def print_twice(name):
print(name)
print(name)
print_twice("Amy")
def give_a_break():
s='break'
return s
print(give_a_break())
print_twice(give_a_break())
def cal(a,b):
return a + b
print(cal(1,2))
def my_abs(n):
if n>=0:
return n
else:
return -n
print("The absolute value is ", my_abs(-8), ".")
import math
def quadratic(a,b,c):
discriminant = b**2 - 4*a*c
if discriminant >=0:
x1= (-b + math.sqrt(discriminant))/(2*a)
x2= (-b - math.sqrt(discriminant))/(2*a)
return x1 , x2
else:
return None, None
input_a=float(input("Please enter a:"))
input_b=float(input("Please enter b:"))
input_c=float(input("Please enter c:"))
sol_1,sol_2=quadratic(input_a,input_b,input_c)
if sol_1:
print('Results are: {} and {}'.format(sol_1,sol_2))
else:
print("no solution.")
age=int(input("Enter your age"))
if age <=6:
print("kid")
elif age>=18:
print("Adult")
else:
print("teenager")
def fib(n):
if n==1 or n==2:
return 1
else:
return fib(n-2)+fib(n-1)
print(fib(5))
| false |
57a2bc0142156a36623a7eab48a3159bd8111383 | dongxinghuashao/practise | /elif.py | 402 | 4.125 | 4 | # if
# elif
# else
# name = input("please enter your name : ")
# print(name)
# print(type(name))
age = int(input("please enter your age : "))
# print(type(age))
# print(name + str(age))
if age < 21:
print("you can not smoke")
elif age == 21:
print("you are now 21,you can go to smoke")
elif age == 100:
print("you are 100,please quit smoking")
else:
print("you can smoke man :" + name)
| false |
15432c0c0c88e0c6ca5d0e34c360652c9e99668f | nest-lab/Epsilon | /problem4.py | 426 | 4.21875 | 4 | print ("A Hashtag system")
input_by_users = raw_input("Enter any sentence or word: ")
words_from_input = input_by_users.split()
#print input_by_users
words_with_hashtags = []
for i in xrange(len(words_from_input)):
if "#" in words_from_input[i]:
words_with_hashtags.append(words_from_input[i])
if len(words_with_hashtags) == 0:
print ("No Hashtags")
else:
for j in words_with_hashtags:
print j
| false |
e9576d531fb15a6b448a9bd13114607ed161fe67 | NicoleGruber/AulasPython | /Aula03/Exercicio/Exercicio05.py | 948 | 4.21875 | 4 | #--- Exercicio 5 - Input, Estrutura de decisão e operações matemáticas
#--- Crie um programa que leia o salário de uma pessoa
#--- Use o método 50-20-10-20 - https://www.jaseimevirar.com/blog/como-voce-organiza-seu-orcamento-mensal/
#--- Informe os percentuais e valores que a pessoa deve utilizar em cada categoria
#--- Deve ser utilizado a função format e os caracteres de tabulação e quebra de linha para cada categoria
salario = float(input('Digite o seu salario: '))
parte1 = salario*0.5
parte2 = salario*0.2
parte3 = salario*0.1
parte4 = salario*0.2
print('{} destinado a despesas fixas\n'.format(parte1))
print('{} destinado a investimentos de longo prazo como aposentadoria e independência financeir \n'.format(parte2))
print('{} destinado a investimentos de curto prazo, podendo ser uma reserva de emergência, uma viagem, um carro, etc;\n'.format(parte3))
print('{} para gastos livres e despesas variáveis\n'.format(parte4)) | false |
3082e0d37826a569a89ccfb42c8e330fd82b1aa8 | NicoleGruber/AulasPython | /Aula03/Exercicio/Exercicio04.py | 900 | 4.1875 | 4 | #--- Exercicio 4 - Input, Estrutura de decisão e operações matemáticas
#--- Crie um programa que realize a autenticação de usuário
#--- Crie duas variáveis para conter o usuário e senha padrão do sistema
#--- Leia o usuário e senha informados pelo usuário via função input()
#--- Valide se usuário e senha estão corretos
#--- Caso o usuário e senha estejam corretos informe com mensagem de boas vindas
#--- Caso o usuário e senha estejam incorretos informe com mensagem de falha de login
usuario_salvo = 'ABCDE'
senha_salvo = '12345'
usuario = input('Digite o usuario: ').strip()
senha = input('Digite a senha: ').strip()
if usuario == usuario_salvo:
if senha == senha_salvo:
print('''Seja Bem Vindo''')
elif senha != senha_salvo:
print('Falha de login, Senha incorreta')
elif usuario != usuario_salvo:
print('Falha de login, Usuário incorreto') | false |
81ed5c24036f56ad042935e829e882e4e876a61e | Haedt406/python | /python fun/vauhns/1st.py | 1,095 | 4.15625 | 4 | ##import math
##
##def main():
## Quizzes = int(input("How many quizzes did you have? "))
## step = 0
## QScore = 0
## QTotalScore = 0
## quizAverage = 0
## finalExam = 0
## for i in range(0, Quizzes):
## step = step + 1
## QScore = int(input(("What was your score on quiz ")+str(step)+("? ")))
## QTotalScore = QTotalScore + QScore
## quizAverage = float((QTotalScore)/(Quizzes))
## finalExam = float(input("What was your score on the final exam? "))
## GradePercentage = ((finalExam * 0.6)+(quizAverage*0.4))
## print(("Your final grade percentage: ")+str(GradePercentage))
##main()
import turtle
def imprint(turtleName, xCoord, yCoord, color):
turtleName.color = color
turtleName.pu()
turtleName.goto((xCoord), (yCoord))
turtleName.pd()
turtleName.stamp()
turtleName.pu()
some_turtle = turtle.Turtle()
some_turtle.shape("turtle")
some_turtle.hideturtle()
imprint(some_turtle, 0, 0, "red")
imprint(some_turtle, 100, -50, "blue")
imprint(some_turtle, -75, -25, "purple")
| true |
6628d0f8513fd108bd86eed94b0f0f8bab174d15 | PennyCelly/program | /STUDY/迭代器和生成器/迭代器.py | 1,108 | 4.4375 | 4 | """
创建一个迭代器
1.把一个类作为一个迭代器使用,需要在类中实现两个方法 __iter__() 与 __next__() 。
2.当类的构造函数为 __init__(), 它会在对象初始化的时候执行。
3.__iter__() 方法返回一个特殊的迭代器对象, 这个迭代器对象实现了 __next__() 方法并通过 StopIteration 异常标识迭代的完成。
4.__next__() 方法会返回下一个迭代器对象。
"""
# 创建一个返回数字的迭代器,初始值为 1,逐步递增 1:
class Mynumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
classMynumbers = Mynumbers()
myiter = iter(classMynumbers)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
"""
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
"""
list1 = ['1', '2', 'a', 'b', 'c']
it = iter(list1)
for i in list1:
print(next(it))
| false |
0e61305979ee6b5b05914876e95b964f3c150879 | Marionjames-ally/WORLD-NEWS | /app/models.py | 772 | 4.15625 | 4 | class Articles:
"""
Class articles that show the objects in the article
"""
def __init__(self, title, description, url, author, urlToImage, publishedAt):
self.title = title
self.description = description
self.url = url
self.author = author
self.urlToImage = urlToImage
self.publishedAt = publishedAt
class Sources:
"""
A class sources that shows sources that are supposed to be displayed in the object
"""
def __init__(self, name, id, url, category, language, country, description):
self.name = name
self.id = id
self.url = url
self.category = category
self.language = language
self.country = country
self.description = description
| true |
d6cc1381026c56f87fb7bc9c7af499e5cd75fe5e | CharakRaman/FEST2021 | /vernam-cipher.py | 709 | 4.375 | 4 | """
Vernam Cipher
A method of encrypting alphabetic text. It is a Transposition techniques for converting a plain text into a cipher text.
In this mechanism we assign a number to each character of the Plain-Text, like a = 0, b = 1, c = 2, .. z = 25.
"""
def vernam(key, message):
message = str(message)
m = message.upper().replace(" ", "")
encrypt = ""
for i in range(len(m)):
letter = ord(m[i])-65
letter = (letter + key) % 25
letter += 65
encrypt = encrypt + chr(letter)
return encrypt
print("*****VERNAM CIPHER*****")
Key = int(input("Key: "))
message = input("Message: ")
encrpt = vernam(Key, message)
print("Encrypted Message: ",encrpt) | true |
f07fe682a7a028a871f7a551fef58cbc0deaaad0 | haripoorna/python_snips | /others/extractKeys.py | 539 | 4.46875 | 4 | # Python3 code to demonstrate
# Extracting specifix keys from dictionary
# Using dictionary comprehension + items()
# initializing dictionary
test_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4}
# printing original list
print("The original dictionary : " + str(test_dict))
# Using dictionary comprehension + items()
# Extracting specifix keys from dictionary
res = {key: test_dict[key] for key in test_dict.keys() & {'akshat', 'nikhil'}}
# print result
print("The filtered dictionary is : " + str(res))
| true |
497611d5467515bfaa8bb761b4abad6bddb759ff | lamyaAltuwairqi/Student | /Student.py | 1,731 | 4.1875 | 4 | print("Hello to Student program")
print("_"*60)
print("1. Insert student")
print("2. Search for Student")
print("3. Print Count Of Student")
print("4. Remove Student ")
print("5. Exit")
students=[
{"fullName":"lamyaa altuwairqi",
"mobile":"0551245966",
"address":"Riyadh",
"email":"lamya.altuwairqi@gmail.com"}
]
w=True
while w==True:
x=int(input("choose one number: "))
if x == 1:
name=input("Please enter the name of the Student: ")
mobile=input("Please enter the mobile of the Student: ")
address=input("Please enter the address of the Student: ")
email=input("Please enter the email of the Student: ")
students.append({"fullName":name, "mobile":mobile, "address":address, "email":email})
for x in students:
for i, y in x.items():
print(i,y)
print("-"*50)
elif x==2:
name=input("Please enter the name of the Student: ")
def search(z):
for p in students:
if p['fullName'] == z:
return p
print(search(name))
elif x==3:
print(len(students))
elif x==4:
name=input("Please enter the name of the Student: ")
def delete(z):
for p in students:
if p['fullName'] == z:
students.remove(p)
return "data deleted"
else:
return "there is no student in that name"
print(delete(name))
elif x==5:
w=False
else: #when the user choose number more than 5
print("please choose from 1 to 5 ") | false |
70816b30f17dc4ac10450ff8e8b29d3bfb967f13 | manjot-baj/My_Python_Django | /Python Programs/filter_function.py | 552 | 4.25 | 4 | # filterfunction are used to filter your list or tuple
# according to your defined function
# filter function is iterable but only one time
# ex : filter(defined function,list/tuples)
# our list
numbers = [i for i in range(1,11)]
# defing function with normal code.
def is_even(num):
return num % 2 == 0
evens =list(filter(is_even,numbers))
print(evens)
# doing iteration
for i in evens:
print(i)
# defing with lambda expression
evens_1 = tuple(filter(lambda a:a%2==0,numbers))
print(evens_1)
# doing iteration
for i in evens_1:
print(i)
| true |
93919b6397f9fa0d808ebc994c90da825ca0ecb9 | manjot-baj/My_Python_Django | /Python Programs/oop_class_variable.py | 601 | 4.28125 | 4 | # circle
# area = pi r square
# circumference = 2 pi r
class Circle:
""" Circle class...has methods area and circumference of circle """
# Class Variable
# Class variable is used when the variable value is constant
pi = 3.14
def __init__ (self,radius):
self.radius = radius
def area(self):
""" inside Circle class...Gives area of circle """
return Circle.pi * self.radius**2
def circumference(self):
""" inside Circle class...Gives circumference of circle """
return 2 * Circle.pi * self.radius
C1 = Circle(5)
print(C1.area())
| true |
a0691e864bf9c853afcbe6f55a8049b9c4e7c301 | manjot-baj/My_Python_Django | /Python Programs/Dictionaries_Excercise_4.py | 674 | 4.3125 | 4 | # Update the dictionary
# Dictionary 1
userinfo = {
"Name" : "Manjot",
"age" : 21,
"list": ["hello",34,15,["world",45,51]]
}
# Dictionary 2
# It is a empty dictionary
Games = {}
# Adding data in empty dictionary
Games["GName"]="Assassins Creed"
Games["Size"]="15gb"
Games["Type"]="RPG"
Games["No of Character"]=5
Games["Characters"]=["ezio","altair","connor","edward","arno"]
# Updating
# Update method
# Dictionary1.update(Dictionary2)
# If the key in Dictionary1
# is same as it is present in Dictionary2
# then the key value of Dictionary2
# overrides the value of Dictionary1
# In short it updates the key value
userinfo.update(Games)
print(userinfo) | true |
fc02279df10e8136573a536757b035ce56729479 | manjot-baj/My_Python_Django | /Python Programs/Dictionaries_Excercise_7.py | 742 | 4.34375 | 4 | # Making a program that takes the input from the user
# and stores it in Dictionary
# and prints the user input values
# Making a empty Dictionary
User_Info = {}
# Taking input from user
Name = input("Enter Your Name : ")
Age = int(input("Enter Your Age : "))
# Note : If the input is passed in a single variable
# through split method then it creates list
Fav_Movies =input("Enter Your Favourate movies : ").split(",")
Fav_Songs = input("Enter Your Favourate Songs : ").split(",")
# Adding User Values in Dictionary
User_Info["Name"] = Name
User_Info["Age"] = Age
User_Info["Fav_Movies"] = Fav_Movies
User_Info["Fav_Songs" ]= Fav_Songs
# For printing values one by one
for key,value in User_Info.items():
print(f"{key}:{value}")
| true |
516d13ee47908c8fdaaa150bf0c265435aeca175 | nilbsongalindo/APA | /Insertion and Selection Sort/insertion_and_selection_sort.py | 978 | 4.125 | 4 | # Insertion Sort
def InsertionSort(lista):
for i in range(1, len(lista)):
atual = lista[i]
for j in range(i - 1, -1, -1): #For que decresce partindo última posição ordenada até o início da lista
if lista[j] > atual:
lista[j], lista[j + 1] = lista[j + 1], lista[j]
else:
break
return lista
def SelectionSort(lista):
for i in range(0, len(lista)):
min = lista[i]
for j in range(i + 1, len(lista)):
if lista[j] < min:
min = lista[j]
lista[i], lista[j] = lista[j], lista[i]
return lista
def main():
teste = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]
print('Lista original: %s' % str(teste))
print('Lista ordenada pelo Insertion Sort: %s '% str(InsertionSort(teste)))
print('Lista ordenada pelo Selection Sort: %s '% str(SelectionSort(teste)))
"""
best_case = [0, 4, 10, 20, 55, 63, 78, 90, 103, 120, 150]
worst_case = [150, 120, 103, 90, 78, 63, 55, 20, 10, 4, 0]
"""
if __name__ == '__main__':
main()
| false |
1899df119a4522250aa471e0ff63e727d5502130 | cwlinkem/assignment-1 | /primefactors.py | 450 | 4.3125 | 4 | #will break a number into its prime factors
num = input ("Please enter a number: ")
def calc_factors(num):
small_factors = []
i = 2
while i <= num:
if num % i == 0:
small_factors = calc_factors(num/i)
small_factors.append(i)
return small_factors
i += 1
factors = small_factors
factors.sort()
return factors
factors = calc_factors(num)
print 'The number', str(num), 'can be factored into the following prime numbers',factors
| true |
6f8becc018b30c05e2c3ee517a65604e22d4cc19 | crudmucosa/automatetheboringstuffpython | /collatz.py | 503 | 4.21875 | 4 | #! /usr/bin/env python
"""
Demonstrate the collatz sequence. Any number you enter should return 1. How
does this work? Who the heck knows!?
"""
def collatz(number):
#check for even-ness
if number % 2 == 0:
return (number // 2)
if number % 2 == 1:
return (3 * number + 1)
print('Please enter a number:')
numberInput = int(raw_input())
numberOutput = collatz(numberInput)
while (numberOutput != 1):
numberOutput = collatz(numberOutput)
print(numberOutput)
| true |
97d06b4e1dd80062a46119e3f76cb900bff43452 | adilmujeeb/Udacity_AWS_ML_Foundation_nanodegree | /OOP/pants.py | 1,683 | 4.4375 | 4 | class Pants:
""" Pants class represents an article of clothing in a store
"""
def __init__(self, color, waist_size, length, price):
""" Method for initializing a Pants object
Args:
color (str)
waist_size (int)
length (int)
price (float)
Attributes:
color (str): color of a pants object
waist_size (str): waist size of a pants object
length (str): length of a pants object
price (float): price of a pants object
"""
self.color = color
self.waist_size = waist_size
self.length = length
self.price = price
def change_price(self, new_price):
""" change_price method changes the price attribute of a pants object
Args:
new_price (float): the new price of the pants object
Returns: None
"""
self.price = new_price
def discount(self, percentage):
""" discount method outputs a discounted price of a pants object
Args:
percentage (float): a decimal representing the amount to discount
Returns:
float: the discounted price
"""
return self.price * (1 - percentage)
def check_results():
pants = Pants('red', 35, 36, 15.12)
assert pants.color == 'red'
assert pants.waist_size == 35
assert pants.length == 36
assert pants.price == 15.12
pants.change_price(10) == 10
assert pants.price == 10
assert pants.discount(.1) == 9
print("All tests passed!")
if __name__ == '__main__':
check_results()
| true |
65a089cdf11163ba347fbfd2c7b0e3fbfdce0507 | Abhinav-Chdhary/My-Competitivem-Prep | /listCommand.py | 1,233 | 4.15625 | 4 | """ def inserter():
return "monday"
def printer():
return "tuesday"
def remover():
return "wednesday"
def appender():
return "thursday"
def sorter():
return "friday"
def popper():
return "saturday"
def reverser():
return "sunday"
def default():
return "Invalid command"
switcher = {
1: "insert",
2: "print",
3: "remove",
4: "append",
5: "sort",
6: "pop",
7: "reverser"
} """
arr = []
def runner(command):
d=command.split()
if command.split()[0] == "insert":
arr.insert(int(d[1]),int(d[-1]))
elif command == "print":
print(arr)
elif command.split()[0] == "remove":
arr.remove(int(d[-1]))
elif command == "sort":
arr.sort()
elif command == "pop":
arr.pop()
elif command == "reverse":
arr.reverse()
elif command.split()[0] == "append":
arr.append(int(d[-1]))
else:
print("invalid command")
if __name__ == '__main__':
N = int(input())
for _ in range(0,N):
runner(input())
#sample input
"""
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
""" | false |
f6c28e2eaf2ed38bca5caa3023389dec18963a1c | tdub-man/python-algorithms | /UpArrow.py | 1,330 | 4.28125 | 4 | from math import e as E
from math import pi as PI
# Formal recursive definition of arrow
def upArrow(a=0,n=0,b=0):
if n==0:
return a*b
elif n>=1 and b==0:
return 1
else:
return upArrow(a,n-1,upArrow(a,n,b-1))
def twoArrow(x=0,n=0):
p=1
for i in range(1,n+1):
p = pow(x,p)
return p
def threeArrow(x=0,n=0):
p=1
for i in range(1,n+2):
p = pow(x,p)
return p
# More computable arrow definition
def uArrow(base=0,arrow=0,power=0):
if arrow==0:
return base*power
elif power==0:
return 1
elif arrow==1:
return pow(base,power)
else:
p=1
for i in range(1,power+arrow-1):
p = pow(base,p)
return p
def main():
# a = uArrow(base=2,arrow=2,power=5)
# b = uArrow(base=2,arrow=3,power=4)
# c = uArrow(base=2,arrow=4,power=3)
# d = uArrow(base=2,arrow=5,power=2)
# e = uArrow(base=2,arrow=6,power=1)
#
# f = uArrow(base=2,arrow=7,power=0) # Any number raised to 0 = 1
# g = uArrow(base=2,arrow=0,power=7) # 0 Arrow is multiplication
# h = uArrow(base=2,arrow=1,power=6) # 1 Arrow is exponentiation
# print("{0} : {1} : {2}".format(f,g,h))
# print("A=B=C=D=E ? {0}\nA = {1}".format((a == b == c == d == e),a))
if __name__ == '__main__':
main()
| false |
f324fd1200bb5e44600efc01971f2a1a11ccf0ea | soumilk/Algorithms_and_Their_Techniques | /05-Recursion and Backtrack/fibonacci_series.py | 325 | 4.40625 | 4 | '''
This is the simple recursive program to find the nth term of
fibonacci series
0 1 1 2 3 5 8 13 21 34 ....
'''
def fib(n):
# Base case
if n==0 or n==1:
return n
# Recursive case
return fib(n-1)+fib(n-2)
n=int(input("Enter the nth term to find : "))
print(fib(n))
| true |
050d468d5828c5676c42f9a5595b94981beb897f | RichW1/Cybersecurity-Bootcamp | /1-Lesson-Plans/XX-Supplemental-LPs/Python/Async-Python/3/Activities/12-Word-Search/Solved/WordSearch.py | 1,187 | 4.3125 | 4 | # Create a function that takes in a word and then searches for the word within the text
def wordSearch(word):
# Open the file called "Monologue.txt"
monologueFile = open("Monologue.txt")
# Read the text contained within the file
monologueText = monologueFile.read()
# Add a space before the word to make sure that it is independent
wordWithSpace = " " + word + " "
# Search for any instances of the word provided
if (monologueText.find(wordWithSpace) > -1):
# If the word is found, count how many times it appears by splitting the text on the word and counting the length of the list returned
countList = monologueText.split(wordWithSpace)
# Print how many times the word was found
print("The word" + wordWithSpace + "can be found " +
str(len(countList) - 1) + " times")
# If no instances of the word were found, print that the word is not in the text
else:
print("The word" + wordWithSpace + "is not in the text")
# Collect a word from the user
wordToSearch = input("Please enter a word to search for: ")
# Pass the word to search into the function created
wordSearch(wordToSearch)
| true |
15e31d11a757036bfe66d9fcc6dfcce986da06a6 | JoKerDii/Thinkpy-mySol | /Exercise7.2.py | 472 | 4.25 | 4 | import math
def eval_loop():
"""Iteratively prompts the user, takes the resulting input and evaluates it
using eval, and prints the result.
It should continue until the user enters 'done', and then return the value of
the last expression it evaluated.
"""
while True:
user_input = input("Input:")
if eval(user_input) == 'done':
break
print(eval(user_input))
return eval(user_input)
eval_loop()
| true |
5157bc4ba1dcefd33ff35491c25cbc264592ae31 | JoKerDii/Thinkpy-mySol | /Exercise5.3.py | 741 | 4.3125 | 4 | def is_triangle(a, b, c):
"""
This function aims to check if it is possible to form a triangle from sticks with the given lengths
"""
if a > (b+c) and b > (a+c) and c > (b+a):
print("Yes.")
elif a == b+c or b == a+c or c == a+b:
print("Degenerate.")
else:
print("No.")
# test
# is_triangle(1,2,3)
def is_inputTriangle():
"""
This function prompts the user to input three stick lengths
and check whether sticks with the given lengths can form a triangle.
"""
a = int(input("Please input a number for a:"))
b = int(input("Please input a number for b:"))
c = int(input("Please input a numebr for c:"))
is_triangle(a, b, c)
# test
# is_inputTriangle()
| true |
ce56a3d4dfee5f139f121ad0f47895eeb96eaf0d | chunkityip/CodingBat- | /List-2 .py | 1,463 | 4.28125 | 4 | count_evens
#Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
def count_evens(nums):
count=0
for num in nums:
if num %2==0:
count+=1
return count
------------------------------------------------------------------------------------------------------------------------------------------
big_diff
#Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
#Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
def big_diff(nums):
return max(nums) - min(nums)
-------------------------------------------------------------------------------------------------------------------------------------------
centered_average
#Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array.
#If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.
#Use int division to produce the final average. You may assume that the array is length 3 or more.
def centered_average(nums):
small = min(nums)
big = max(nums)
return (sum(nums) - small - big) / (len(nums) - 2)
--------------------------------------------------------------------------------------------------------------------------------------------
| true |
f1ceb803d69876bf7a1bd127391c6afe9400fb88 | FiennesHarris/eblock_python | /2.py | 369 | 4.375 | 4 | import random
num=random.randint(1,10)
guess=int(input("Guess the number between 1-10"))
# Add the missing code here to allow the user
# to keep guessing until their guess matches the number.
while num != guess:
if num < guess:
guess=int(input("Guess to High"))
elif num > guess:
guess=int(input("Guess to Low"))
print("correct")
| true |
19ae2d0bedf7266fd6b2a994e314c2ac6b388d65 | sidduGIT/Hacker-Rank- | /default_dict.py | 2,131 | 4.375 | 4 | '''
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
In this challenge, you will be given
integers, and . There are words, which might repeat, in word group . There are words belonging to word group . For each words, check whether the word has appeared in group or not. Print the indices of each occurrence of in group . If it does not appear, print
.
Constraints
Input Format
The first line contains integers,
and separated by a space.
The next lines contains the words belonging to group .
The next lines contains the words belonging to group
.
Output Format
Output
lines.
The line should contain the -indexed positions of the occurrences of the
word separated by spaces.
Sample Input
5 2
a
a
b
a
b
a
b
Sample Output
1 2 4
3 5
Explanation
'a' appeared
times in positions , and .
'b' appeared times in positions and .
In the sample problem, if 'c' also appeared in word group , you would print .
'''
from collections import defaultdict
d=defaultdict(list)
d['bagewadi'].append('atharv')
d['mogali'].append('suraj')
d['bagewadi'].append('surabhi')
d['mogali'].append('suman')
print(d)
for i in d.items():
print(i)
dict1={'A':1}
dict2=defaultdict(int)
if 'A' in dict1:
print(dict1['A'])
#if 'A' in dict2:
print(dict2)
n,m=map(int,input().split())
dA=defaultdict(list)
listB=[]
for i in range(n):
dA[input()].append(i+1)
print(dA)
for i in range(m):
listB=listB+[input()]
print(listB)
for i in listB:
if i in dA:
print(' '.join(map(str,dA[i])))
else:
print('-1')
| true |
e90006ff5d5053dd38e31286091a7d52089cb3f0 | sidduGIT/Hacker-Rank- | /numpy_dot_cross.py | 1,070 | 4.15625 | 4 | '''
dot
The dot tool returns the dot product of two arrays.
import numpy
A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])
print numpy.dot(A, B) #Output : 11
cross
The cross tool returns the cross product of two arrays.
import numpy
A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])
print numpy.cross(A, B) #Output : -2
Task
You are given two arrays
and . Both have dimensions of X
.
Your task is to compute their matrix product.
Input Format
The first line contains the integer
.
The next lines contains space separated integers of array .
The following lines contains space separated integers of array
.
Output Format
Print the matrix multiplication of
and
.
Sample Input
2
1 2
3 4
1 2
3 4
Sample Output
[[ 7 10]
[15 22]]
'''
import numpy
A=numpy.array([1,2])
B=numpy.array([3,4])
print(numpy.dot(A,B))
A=numpy.array([1,2])
B=numpy.array([3,4])
print(numpy.cross(A,B))
n=int(input())
A=[input().split() for _ in range(n)]
A=numpy.array(A,int)
B=[input().split() for _ in range(n)]
B=numpy.array(B,int)
print(numpy.dot(A,B))
| true |
30a8ef4243a24280ec2cadeace106a16f48c926c | sidduGIT/Hacker-Rank- | /pdf_viewer.py | 2,081 | 4.21875 | 4 | '''
When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In this PDF viewer, each word is highlighted independently. For example:
PDF-highighting.png
In this challenge, you will be given a list of letter heights in the alphabet and a string. Using the letter heights given, determine the area of the rectangle highlight in
assuming all letters are
wide.
For example, the highlighted
. Assume the heights of the letters are and . The tallest letter is high and there are letters. The hightlighted area will be so the answer is
.
Function Description
Complete the designerPdfViewer function in the editor below. It should return an integer representing the size of the highlighted area.
designerPdfViewer has the following parameter(s):
h: an array of integers representing the heights of each letter
word: a string
Input Format
The first line contains
space-separated integers describing the respective heights of each consecutive lowercase English letter, ascii[a-z].
The second line contains a single word, consisting of lowercase English alphabetic letters.
Constraints
, where
is an English lowercase letter.
contains no more than
letters.
Output Format
Print a single integer denoting the area in
of highlighted rectangle when the given word is selected. Do not print units of measure.
Sample Input 0
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
abc
Sample Output 0
9
Explanation 0
We are highlighting the word abc:
Letter heights are
, and . The tallest letter, b, is high. The selection area for this word is
.
Note: Recall that the width of each character is
.
Sample Input 1
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 7
zaba
Sample Output 1
28
Explanation 1
The tallest letter in
is at . The selection area for this word is .
'''
def area_viewer(char_height,word):
char_height=[char_height[ord(i)-97] for i in word]
return max(char_height)*len(word)
char_height=list(map(int,input().split()))
word=input()
print(area_viewer(char_height,word))
| true |
b7249d49fe7d957391fa56d87a312c1c7292ff0e | sidduGIT/Hacker-Rank- | /transpose.py | 975 | 4.4375 | 4 | import numpy
arr=numpy.array([[1,2,3],
[4,5,6]])
print('original array')
print(arr)
print('shape')
print(numpy.shape(arr))
trans_arr=numpy.transpose(arr)
print('transpose')
print(trans_arr)
print('shape of transpose array',numpy.shape(trans_arr))
import numpy
arr=numpy.array([[1,2,3],[4,5,6]])
print(arr)
flatten=arr.flatten()
print(flatten)
'''
Task
You are given a
X integer array matrix with space separated elements ( = rows and
= columns).
Your task is to print the transpose and flatten results.
Input Format
The first line contains the space separated values of
and .
The next lines contains the space separated elements of
columns.
Output Format
First, print the transpose array and then print the flatten.
Sample Input
2 2
1 2
3 4
Sample Output
[[1 3]
[2 4]]
[1 2 3 4]
'''
import numpy
n,m=tuple(map(int,input().split()))
arr=[input().split() for i in range(n)]
arr=numpy.array(arr)
print(numpy.transpose(arr))
print(arr.flatten())
| true |
34fdd2543f4958eded869997b1b26647a1391899 | sidduGIT/Hacker-Rank- | /beautiful_day.py | 2,124 | 4.4375 | 4 | '''
Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number , its reverse is . Their difference is . The number reversed is , and their difference is
.
She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day.
Given a range of numbered days,
and a number , determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where is evenly divisible by
. If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range.
Function Description
Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range.
beautifulDays has the following parameter(s):
i: the starting day number
j: the ending day number
k: the divisor
Input Format
A single line of three space-separated integers describing the respective values of
, , and
.
Constraints
Output Format
Print the number of beautiful days in the inclusive range between
and
.
Sample Input
20 23 6
Sample Output
2
Explanation
Lily may go to the movies on days
, , , and
. We perform the following calculations to determine which days are beautiful:
Day
is beautiful because the following evaluates to a whole number: Day is not beautiful because the following doesn't evaluate to a whole number: Day is beautiful because the following evaluates to a whole number: Day is not beautiful because the following doesn't evaluate to a whole number: Only two days, and , in this interval are beautiful. Thus, we print as our answer.
'''
def reversed1(n):
rev=0
while n!=0:
rem=n%10
rev=rev*10+rem
n=n//10
return rev
#print(reversed1(int('1234')))
def beautiful_day(i,j,k):
count=0
for n in range(i,j+1):
if (abs(n-reversed1(n))%k)==0:
count+=1
return count
ijk=input().split()
i=int(ijk[0])
j=int(ijk[1])
k=int(ijk[2])
print(beautiful_day(i,j,k))
| true |
7e8c7b034d7d35a0c970a1a3530a97f664d9c1e6 | ra-110110/Algorithms-and-data-structures-on-Python | /ex_7_task_3.py | 1,854 | 4.1875 | 4 | """
Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом.
Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся
элементы, которые не меньше медианы, в другой — не больше медианы.
Примечание: задачу можно решить без сортировки исходного массива.
Но если это слишком сложно, используйте метод сортировки, который не рассматривался на уроках
(сортировка слиянием также недопустима).
"""
from random import randint
int_list = []
m = int(input("Введите натуральное число для массива: "))
size = 2 * m + 1
for i in range(size):
int_list.append(randint(0, 100))
print(int_list)
# 1 вариант
from numpy import median #модуль
print(median(int_list))
# 2 вариант
from statistics import median #модуль
print(median(int_list))
# 3 вариант
def medianN(lst):
med = sorted(lst)[int((len(lst) - 1) / 2)] #ищем центральный элемент отсортированного списка
print(med)
medianN(int_list)
# 4 вариант (без сортировки)
def medianNum(lst):
while len(lst) != 1: #удаляем максимальный и минимальные элементы пока не останется один средний
lst.pop(lst.index(max(lst)))
lst.pop(lst.index(min(lst)))
print(*lst)
medianNum(int_list)
| false |
7bf8767ef30de36d3f5eabe4bccf89aa104e6404 | amyvalukonis/CrackingTheCodingInterview | /CCI/4.1/balance.py | 938 | 4.15625 | 4 | #implement a fn to check if a bin tree is balanced
#balanced=no nodes subtrees differ by more than 1
class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def checkHeight(self,root):
if root is None:
return 0
leftHeight=self.checkHeight(root.left)
if leftHeight is -1:
return -1
rightHeight=self.checkHeight(root.right)
if rightHeight is -1:
return -1
difference=leftHeight-rightHeight
if abs(difference)>1:
return -1
else:
return max(leftHeight,rightHeight) + 1
def balanced(self,root):
if self.checkHeight(root) is -1:
return False
return True
if __name__=="__main__":
node = Node(2)
node.left=Node(1)
node.right=Node(2)
node.left.left=Node(4)
node.left.left.left=Node(5)
result=node.balanced(node)
print("the result is %s"%result)
| true |
2ce586a455ad79002351941f5752d136c88d8993 | AlexPlatin/Grokking_Algorithms_book | /Quick_sort.py | 391 | 4.125 | 4 | def quicksort(list_of_values: list) -> list:
if len(list_of_values) < 2:
return list_of_values
pivot_elem = list_of_values[0]
less_part = [i for i in list_of_values[1:] if i <= pivot_elem]
greater_part = [i for i in list_of_values[1:] if i > pivot_elem]
return quicksort(less_part) + [pivot_elem] + quicksort(greater_part)
print(quicksort([1, 2, 5, 4, 3, 5, 6])) | true |
f0dc7e1fe2c893af9167334766cd54dfb0dfa2a0 | brandonhdez7/immersive11-18-unit1 | /python101.py | 963 | 4.15625 | 4 | print "hello, world"
print """
it was a stormy night
A murder happen.
"""
theBestClass = "The 11-18 Immersive"
print theBestClass
month = "November"
print type(month)
date = 13
print type(date)
dateAsFloat = 13.0
print type(dateAsFloat)
aBool = True
print type(aBool)
aList = []
print type(aList)
aDictionary ={}
print type (aDictionary)
first = "brandon"
last = "hernandez"
fullName = first + " " + last
print fullName
fourteen = 10 + 4
print fourteen
fourteen = "10" + "4"
print fourteen
fourteen = int("10") + 4
print fourteen
print 2+2
print 2-2
print 2/2
print 2*2
print 2%2
print 2**3
print "-" * 20
name = raw_input("what is your name? ")
print name
print 2 == 2
secret_number = 5
if (secret_number == 3):
print "secret_number is 3"
else:
print "secret_number is not 3."
game_on = True
i = 0:
while(game_on):
i+= 1
if(i == 10):
game_on = False
else:
print "Game on!!" | true |
4f7815f0f8d4f94bd35b0b536c9036e3a1c8396a | grsclc/practice_python | /palindrome.py | 1,046 | 4.3125 | 4 | entered_text = str(input('please enter a word: ')) #user prompted to enter a phrase/word
lower_text = entered_text.lower() #all cases are lowered
no_space = str(lower_text.replace(" ","")) #all the spaces are removed
print('the string without spaces is: ',no_space)
reversed_string = ''.join(reversed(no_space))
print('the reversed string is: ',reversed_string)
no_space_list = list(no_space.split(' ')) #the phrase is converted to a list for iteration purposes
print('the phrase you entered without spaces is: ', no_space_list)
reversed_string_list = list(reversed_string.split(' ')) #the phrase is converted to a list for iteration purposes
print('the reversed phrase you entered without spaces is: ',reversed_string_list)
for i in range(len(reversed_string_list)): #the for loop to compare two lists and determine whether they are identical
if reversed_string_list[i]==no_space_list[i]:
print('The phrase you enetered is a palindrome.')
else:
print('The phrase you enetered is not a palindrome.')
| true |
dba9aa83e258a5a177354d760b23a12f9726434d | shubhamrocks888/stack | /stack_in_python.py | 1,088 | 4.34375 | 4 | # Python program for implementation of stack
# import maxsize from sys module
# Used to return -infinite when stack is empty
##Pros: The linked list implementation of stack can grow and shrink according to the needs at runtime.
##Cons: Requires extra memory due to involvement of pointers.
from sys import maxsize
# Function to create a stack. It initializes size of stack as 0
def create_stack():
stack = []
return stack
# Stack is empty when stack size is 0
def is_empty(stack):
return len(stack)==0
# Function to add an item to stack. It increases size by 1
def push(stack,item):
stack.append(item)
print(item ,"pushed to satck")
# Function to remove an item from stack. It decreases size by 1
def pop (stack):
if is_empty(stack):
return str(-maxsize -1)
return stack.pop()
# Function to return the top from stack without removing it
def peek(stack):
if is_empty(stack):
return str(-maxsize -1)
return stack[-1]
s = create_stack()
push(s,1)
push(s,2)
push(s,3)
print(pop(s))
print(pop(s))
print(pop(s))
print(pop(s))
| true |
55ec027fec7c45ce169b1aa655b0fbc1b418a25c | nicolasrls/codigos | /Python3/Exercícios Lista/Lista/q2.py | 272 | 4.21875 | 4 | #Digitar números até que o número 0 seja digitado. Criar lista com os números digitados e em seguida mostrar os elementos.
numero = int(input("Número: "))
freio = 0
l = []
while numero != freio:
l.append(numero)
numero = int(input("Número: "))
print(l) | false |
45079c15d908c556d19b8494882f13ed2052e09e | gorakh999/Magic_Square_Matrix | /Magic_Square_Matrix.py | 1,077 | 4.3125 | 4 | '''A python program to find the magic square matrix '''
''' a Square matrix is said to be a magic square matrix
if the sum of each rows / each column and diagonal is a constant
number '''
def magic_square(n):
magicSquare = []
for i in range(n):
l = []
for j in range(n):
l.append(0)
magicSquare.append(l)
i = n//2
j = n-1
num = n*n
count = 1
while (count<=num):
if (i == -1 and j==n): #Condition 4
j =n-2
i =0
else:
if(j==n): #coloumn value is exceeding
j=0
if(i<0): # row is becoming -1
i = n-1
if(magicSquare[i][j]!=0):
j = j-2
i = i+1
continue
else:
magicSquare[i][j] = count
count = count+1
i = i-1
j = j+1 #condition 1
for i in range(n):
for j in range(n):
print(magicSquare[i][j], end = " ")
print()
print("The sum of each row/coloumn/diagonal is :",(n*(n**2+1))/2)
n=int(input("Enter the size of Square Matrix you want to get Magic Square \n"))
magic_square(n) | true |
d4724460f969dbbc7d75dd15aba4a8f5a6418931 | sparshtomar1005/Lists-Programs | /even elements (list comp.).py | 324 | 4.28125 | 4 | #Taking only even elements from a list and putting it in different list using list comprehensions
list=[]
x=int(input("How many Elements you want in List:"))
for i in range(x):
a=int(input("Enter the Element:"))
list.append(a)
even=[a for a in list if a%2==0]
even.sort()
print("Even List:",even) | true |
172bf9939dd72ba8805c1efc337752524350de67 | MrsSimpson/Algorithms | /SortingProject1/source/selection_sort.py | 1,836 | 4.28125 | 4 | #implementation 2 (my original)
"""my_selection_sort algorithm takes an array as a 1D array as an argument. The length of the
array is stored and then the smallest index is set to the first element in the array by
default. If the array length is equal to 0 or 1, the for loops will be skipped over and the
program will return to main. If the array has more than 1 element in it, the algorithm will drop
into the outer for loop which runs until the next to last element. The smallest variable is set
to the counter for the outer loop. We then drop into the inner for loop. The j index will be set
to 1 + i so that we are looking at 1 element ahead of the outer loops index. If the array[j] element is
smaller than the smallest element, then the smallest index is now set to the j counter.
After the remainder of the array is iterated through, I have an if statement to check and make sure
that the smallest variable is not the same as the array[i] index. If it is not, the values in the
array will be swapped in place. If they are the same, the counter for i will increment and the
process will repeat by comparing the next index with the rest of the elements in the array looking for the smallest
value to place at the new i index."""
def selection_sort(test_array):
array_length = len(test_array)
smallest_index = 0
if array_length != 0 and array_length != 1:
for i in range(0, array_length - 1):
smallest = test_array[i]
for j in range((i+1), array_length):
if test_array[j] < smallest:
smallest = test_array[j]
smallest_index = j
if smallest != test_array[i]:
test_array[smallest_index], test_array[i] = test_array[i], test_array[smallest_index]
return test_array
| true |
44560ba9a8cda68b1fe05b74d8406803c72e125f | comp110-20f/course-material | /demos/black_triangle.py | 553 | 4.375 | 4 | """Draw a black triangle with turtle graphics as a test of installation success."""
from turtle import Turtle, Screen
__author__ = "Kris Jordan <kris@cs.unc.edu>"
# Establish a window for our friend the turtle.
window: Screen = Screen()
# Construct a Turtle object and bind it to the name ertle.
ertle: Turtle = Turtle()
# Draw a black triangle.
ertle.begin_fill()
ertle.forward(100)
ertle.left(120)
ertle.forward(100)
ertle.left(120)
ertle.forward(100)
ertle.left(120)
ertle.end_fill()
# Don't quit the window until the user clicks on it.
window.exitonclick() | true |
5be1a1be1c61db8d82ea088901cbf4856d407d7a | renatamuy/pythonnoob | /repeticoes_encaixadas_1.py | 903 | 4.15625 | 4 | def desenha(linha):
while linha > 0:
coluna = 1
while coluna <= linha:
print('*', end = "")
coluna = coluna + 1
print()
linha = linha - 1
desenha(5)
###########
print()
print()
print()
print()
print()
altura = 5
linha = 1
while linha <= altura:
print("*", end = "")
coluna = 2
while coluna < altura:
if linha == 1 or linha == altura:
print("*", end = "")
else:
print(end = " ")
coluna = coluna + 1
print("*")
linha = linha + 1
x = 1
cont = 0
while x < 3:
y = 0
while y <= 4:
print(" Iteração")
print(y)
y = y + 1
x = x + 1
'''x < 3 em duas situações.
y <= 4 em 5 situações = 0 1 2 3 4
Então você tem 2 vezes 5 valores no aninhamento. 10 vezes é iterado'''
| false |
f287aa3c8966da6a67392a74afbfa680e54e26a4 | ariadnecs/python_3_mundo_2 | /exercicio053.py | 843 | 4.21875 | 4 | # Exercício Python 53: Crie um programa que leia uma frase qualquer e
# diga se ela é um palíndromo, desconsiderando os espaços.
# Exemplos de palíndromos: APOS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA,
# O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA
frase = str(input('Digite uma frase: ')).strip().upper().split()
unir = ''.join(frase)
inverter = ''
for letra in range(len(unir) -1, -1, -1):# da ultima até a primeira letra, lembrar que python inicia a contagem no 0,
# por isso o primeiro -1, a primeira letra é zero, então o for deve ir até o -1,
# e o último -1 indica que o for é de trás para frente
inverter += unir[letra]
print('O inverso de {} é {}.'.format(unir, inverter))
if unir == inverter:
print('A frase digitada é um palíndromo!')
else:
print('A frase digitada não é um palíndromo!') | false |
60c931e1dc885a1c8d977dfd1465e882714968f7 | ariadnecs/python_3_mundo_2 | /exercicio071.py | 1,261 | 4.21875 | 4 | # Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico.
# No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro)
# e o programa vai informar quantas cédulas de cada valor serão entregues.
# OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
print('=' * 40)
print(f'{"Banco coisa e tal":^40}')
print('=' * 40)
while True:
valor = int(input('Qual valor você deseja sacar: R$'))
print(f'Valor solicitado para saque R${valor:<8} \nSaque:')
divint_cinq = valor // 50
rest_cinq = valor % 50
if divint_cinq != 0:
print(f'{divint_cinq:>4} cédula(s) de R$50')
elif rest_cinq == 0:
break
divint_vinte = rest_cinq // 20
rest_vinte = rest_cinq % 20
if divint_vinte != 0:
print(f'{divint_vinte:>4} cédula(s) de R$20')
elif rest_vinte == 0:
break
divint_dez = rest_vinte // 10
rest_dez = rest_vinte % 10
if divint_dez != 0:
print(f'{divint_dez:>4} cédula(s) de R$10')
elif rest_dez == 0:
break
divint_um = rest_dez // 1
if divint_um != 0:
print(f'{divint_um:>4} cédula(s) de R$1')
break
print('=' * 40)
print('Operação finalizada. Tenha um bom dia!')
| false |
ea7edfe76eff7a1029d68077b697be7bea6db622 | jason-galea/euler_python | /Finished/28.py | 1,250 | 4.21875 | 4 | def find_sum_of_diagonals(max_grid_size):
"""
Expects an odd number
"""
DEBUG = True
# DEBUG = False
sum = 1
current_grid_size = 1
previous_number = 1
if DEBUG: print(f"previous_number = {previous_number}")
while True:
current_grid_size += 2
if DEBUG: print(f"current_grid_size = {current_grid_size}")
### Find & add diagonals from current iteration
### NOTE: Increment between diagonals to be added == current_grid_size -1
### NOTE: E.G: Corners of top row of grid size 5 are 21 & 25
### NOTE: Increment == 25 - 21 == 4 == current_grid_size - 1
for _ in range(4):
previous_number += current_grid_size - 1
if DEBUG: print(f"previous_number = {previous_number}")
sum += previous_number
if (current_grid_size >= max_grid_size):
# return sum
print(f"Sum of diagonal numbers in grid of size {max_grid_size} == {sum}")
exit()
if __name__ == "__main__":
# find_sum_of_diagonals(3)
# find_sum_of_diagonals(5) ### Should return 101
# find_sum_of_diagonals(101)
find_sum_of_diagonals(1001)
| true |
de7841b32b3b4f6b4ff11e12bdb8e3960e5017e5 | ekuns/AdventOfCode | /2018/day09-slow.py | 1,354 | 4.125 | 4 | #!/usr/bin/python3
import sys
if (len(sys.argv) < 3):
print("Supply two arguments: 1) Number of players, 2) Number of marbles")
sys.exit()
playercount = int(sys.argv[1])
marblecount = int(sys.argv[2])
print("Number of players: %d" % ( playercount ))
print("Number of marbles: %d" % ( marblecount ))
scores = [0] * playercount
marbles = [0]
currentIndex = 0
currentPlayer = 1
def dumpBoard():
for i in range(0, len(marbles)):
if (currentIndex == i):
print("(%d)" % (marbles[i]), end=" ")
else:
print(marbles[i], end=" ")
print()
for i in range(1, marblecount):
insertAt = (currentIndex + 1) % len(marbles) + 1
#print("inserting %d at offset %d" % (i, insertAt))
if i % 23 != 0:
marbles.insert(insertAt, i)
currentIndex = insertAt
else:
deleteAt = (currentIndex + len(marbles) - 7) % len(marbles)
scores[currentPlayer-1] += i + marbles[deleteAt]
#dumpBoard()
#print("Player %d deleting marble %d aka %d" % (playercount, deleteAt, marbles[deleteAt]))
del marbles[deleteAt]
currentIndex = deleteAt
#dumpBoard()
#dumpBoard()
currentPlayer = (currentPlayer + 1) % playercount
#print("Final board is")
#dumpBoard()
#print("Final scores are: %s" % (scores))
print("High score is %d" % (max(scores)))
| true |
eb21876f68c434ada852ec15c6b6522c52e50c23 | TungstenRain/Random-Python-Challenges | /nested_lists.py | 1,429 | 4.21875 | 4 | """
Author: Frank Olson
Given the names and grades for each student in a Physics class of N students,
store them in a nested list,
and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format:
The first line contains an integer, N, the number of students.
The 2N subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade.
Constraints:
There will always be one or more students having the second lowest grade.
Output Format:
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line
"""
def main():
# Initialize a dictionary
names_and_scores = {}
for _ in range(int(input())):
name = input()
score = input()
names_and_scores[name] = score
# Initialize variables
second_lowest_score = sorted(list(set(names_and_scores.values())))[1]
name_list = []
for key, value in names_and_scores.items():
if value == second_lowest_score:
name_list.append(key)
for name in sorted(name_list):
print(name)
if __name__ == "__main__":
main() | true |
77ccbd3cb100b15ad4c60588c21e60224b6c9f09 | kathleenfwang/algorithms-and-data-structures | /hackerrank/guess_number.py | 997 | 4.15625 | 4 | # picks a random number from 1 - 10 inclusive
# user gets 3 chances to guess, each time priting out feedback if right or wrong
import random
def main():
score = 0
guess_number(score)
def guess_number(score):
tries = 3
correct_num = random.randint(1,10)
def play_again():
print("-----------------")
user_in = input("Play again? y/n ")
if user_in == "y": guess_number(score)
else:
print("Thanks for playing!")
print("********************")
while tries > 0:
print("*************************************")
guess = input("Guess the number (1-10): ")
if guess == str(correct_num):
score += 1
print("Congrats you are correct! Score: ", score)
play_again()
else:
print("Wrong :(")
tries -=1
if tries == 0:
print("Correct number is: ", correct_num)
play_again()
main() | true |
c041d4a00a9cdfb612be7341f182eba628e4fa38 | Krudff/BST-Implementation | /BST Implementation.py | 2,793 | 4.125 | 4 | class BSTNode:
def __init__(self, data=None, left=None, right=None):
self._data = data
self._left = left
self._right = right
def __delete__(self):
del self._left
del self._right
def _insert(self, val):
# Part A.
# Complete the following function so that BSTree.insert(val)
# correctly inserts an element val into its correct location in
# the binary search tree.
if (val < self._data):
if (self._left == None):
# --- Do something here. ---
self._left = BSTNode(val)
else:
# --- Do something here. ---
self._left._insert(val)
else:
if (self._right == None):
# --- Do something here. ---
self._right = BSTNode(val)
else:
# --- Do something here. ---
self._right._insert(val)
def _print(self):
# Part B.
# Implement the following function recursively so that BSTree.print()
# correctly prints the contents of the BST in sorted order.
# --- Write your code here.----
if(self._left!=None):
self._left._print()
print(self._data, end=" ")
if(self._right!=None):
self._right._print()
def _find(self, val):
if (val == self._data):
return True
elif (val < self._data):
if (self._left == None):
return False
else:
return self._left._find(val)
else:
if (self._right == None):
return False
else:
return self._right._find(val)
class BSTree:
def __init__(self):
self._root = None
def __delete__(self):
del self._root
def insert(self, val):
'''Inserts val into the BST.'''
if (self._root != None):
self._root._insert(val)
else:
self._root = BSTNode(val)
def find(self, val):
'''Returns True if val is in the BST, and False otherwise.'''
return self._root._find(val)
def print(self):
'''Prints the sorted contents of the BST.'''
self._root._print()
print()
# NOTE: The following statements in main check for the correctness of
# your implementation. Do not modify anything beyond this point!
if __name__ == '__main__':
n = int(input())
ls = list()
for i in range(n):
ls.append(int(input()))
myTree = BSTree()
for x in ls:
myTree.insert(x)
myTree.print()
print(myTree.find(7))
print(myTree.find(15)) | false |
beab12fad4fb2914249a1d7405ddbb39b57ce1c7 | Mangethe/AnalyseHackathon | /AnalyseHackathon/recursion.py | 1,993 | 4.65625 | 5 | def sum_array(array):
"""Return sum of all items in array
Args:
array (array): list or array-like object containing numerical values.
Returns:
the sum of all items in array.
Example(s):
>>> sum_array(np.array([2, 5, 62, 5, 42, 52, 48, 5]))
221
"""
sum_all = 0 #our starting point
for item in array:
sum_all = sum_all + item #using the for loop we add each item to the starting point
return sum_all #return the sum of all items in the given array
def fibonacci(n):
"""Return nth term in fibonacci sequence
Args:
n (int): nth term in Fibonacci sequence to calculate
Returns:
int: nth term of Fibonacci sequence, equal to sum of previous two terms
Examples:
>>> fibonacci(1)
1
>> fibonacci(2)
1
>> fibonacci(3)
2
"""
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def factorial(n):
"""Return n!
Args:
n (int): number to run through factorial function
Returns:
the factorial of a given number using [n! == n(n-1)!].
Example(s):
>>> factorial(6)
720
"""
if n == 0:
n_fact = 1 # 0! = 1, since an empty set can only be ordered one way
else:
n_fact = n * factorial(n-1) #[n! == n(n-1)! if n!=0]
return n_fact #returns the factorial of the given value
def reverse(word):
"""Return a given word in reverse'''
Args:
word (str): string to be returned in reverse
Returns:
string in reverse order.
Example(s):
>>> reverse('Nqobile')
'eliboqN'
>>> reverse('12345')
'54321'
"""
reversed_word = ''
start = len(word)-1
stop = -1
step = -1
#range --- range(start,stop,step)
for letter in range(start,stop,step):
reversed_word = reversed_word + word[letter]
return reversed_word #return reversed word
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.