blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
cc0b8ef1943eb8b6b5b42870be3387bbde4f8001
|
MindCC/ml_homework
|
/Lab02/Question/lab2_Point.py
| 2,008
| 4.46875
| 4
|
# -*- coding: cp936 -*-
'''
ID:
Name:
'''
import math
class Point:
'''
Define a class of objects called Point (in the two-dimensional plane).
A Point is thus a pair of two coordinates (x and y).
Every Point should be able to calculate its distance
to any other Point once the second point is specified.
άƽϵPoint㣩Point2xy
Pointʵּ2֮ķdistanceTo( Point )
'''
def __init__(self, x, y):
self.__x = x
self.__y = y
def distance_to(self, other):
'''
㲢selfother֮ľ
'''
# sqrt(x^2+y^2)
return math.sqrt((self.__x - other.__x) ** 2 + (self.__y - other.__y) ** 2)
def __str__(self):
'''
صַʾ(x,y)
'''
return '(%d,%d)' % (self.__x, self.__y)
class Line:
'''
Define a class of objects called Line. Line(ߣ
Every Line is a pair of two Points. Line2
Lines are created by passing two Points to the Line constructor.
A Line object must be able to report its length,
which is the distance between its two end points.
'''
def __init__(self, p1, p2):
self.__p1 = p1
self.__p2 = p2
def length(self):
'''
ʾߵ2֮ľ
'''
return self.__p1.distance_to(self.__p2)
def __str__(self):
'''
ߵַʾ(x1,y1)--(x2,y2)
'''
return str(self.__p1) + '--' + str(self.__p2)
if __name__ == "__main__":
p1 = Point(0, 3)
print(p1)
assert str(p1) == "(0,3)"
p2 = Point(4, 0)
print(p2)
assert str(p2) == "(4,0)"
print(p1.distance_to(p2)) # should be 5.0
line1 = Line(p1, p2)
print(line1)
assert str(line1) == "(0,3)--(4,0)"
print(line1.length()) # should be 5.0
print(Line(Point(0, 0), Point(1, 1)).length())
| true
|
0b57a9545507ed95c6f205e680e6436645fffc68
|
jacareds/Unis
|
/2020.4_Atv2_Exer5.py
| 278
| 4.25
| 4
|
#Escreva uma função que:
#a) Receba uma frase como parâmetro.
#b) Retorne uma nova frase com cada palavra com as letras invertidas.
def inverText(text):
inversor = (text)
print(inversor[::-1])
entradInput = str(input("Digite uma frase: "))
inverText(entradInput)
| false
|
dc7c432deb82bf1f07e3f6e2b0632fb515c5ed62
|
DiegoAyalaH/Mision-04
|
/Rectangulos.py
| 1,626
| 4.25
| 4
|
#Nombre Diego Armando Ayala Hernández
#Matrícula A01376727
#resumen del programa: Obtiene los datos de dos rectangulos y te da el area y el perimetor de ambos
#Calcula el área de un rectángulo
def calcularArea(altura, ancho):
area = altura * ancho
return area
#Calcula el perímetro de un rectángulo
def calcularPerimetro(altura, ancho):
perimetro = (2 * altura) + (2 * ancho)
return perimetro
#Te dice cual de las dos áreas es mayor o si son iguales
def decirCualMayorArea(areaUno,areaDos):
if areaUno > areaDos:
return "El primer rectángulo es mayor"
elif areaUno < areaDos:
return "El segundo rectángulo es mayor"
return "Los rectangulos son iguales"
#Función main: recibe las dimensiones, te da el área y perímetro de los ambos rectángulos. También te dice cual es mayor o si son iguales
def main():
print("Escribe las dimensiones del primer rectángulo")
alturaUno = int(input("Altura: "))
anchoUno = int(input("Ancho: "))
print()
print("Escribe las dimensiones del segundo rectángulo")
alturaDos = int(input("Altura: "))
anchoDos = int(input("Ancho: "))
perimetro1 = calcularPerimetro(alturaUno, anchoUno)
perimetro2 = calcularPerimetro(alturaDos, anchoDos)
areaUno = calcularArea(alturaUno, anchoUno)
areaDos = calcularArea(alturaDos, anchoDos)
mayorArea = decirCualMayorArea(areaUno, areaDos)
print("Primer rectángulo")
print("Área : ", (areaUno))
print("Perímetro : ", (perimetro1))
print("Segundo rectángulo")
print("Área ", (areaDos))
print("Perímetro ", (perimetro2))
print(mayorArea)
| false
|
d29faa39dec07a25caa6383e0ecbe35edebbb4c5
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/minimumDominoRotationsForEqualRow.py
| 2,392
| 4.4375
| 4
|
"""
Minimum Domino Rotations For Equal Row
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Example 1:
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
"""
"""
Greedy
Time: O(N) since here one iterates over the array
Space: O(1)
"""
class Solution:
def minDominoRotations(self, A: List[int], B: List[int]) -> int:
def check(x):
"""
Return min number of swaps
if one could make all elements in A or B equal to x.
Else return -1.
"""
# how many rotations should be done
# to have all elements in A equal to x
# and to have all elements in B equal to x
rotations_a = rotations_b = 0
for i in range(n):
# rotations coudn't be done
if A[i] != x and B[i] != x:
return -1
# A[i] != x and B[i] == x
elif A[i] != x:
rotations_a += 1
# A[i] == x and B[i] != x
elif B[i] != x:
rotations_b += 1
# min number of rotations to have all
# elements equal to x in A or B
return min(rotations_a, rotations_b)
n = len(A)
rotationsA = check(A[0]) # If one could make all elements in A or B equal to A[0]
rotationsB = check(B[0]) # If one could make all elements in A or B equal to B[0]
if rotationsA != -1 and rotationsB != -1:
return min(rotationsA, rotationsB)
elif rotationsA == -1:
return rotationsB
else:
return rotationsA
| true
|
1b399e72edc812253cacad330840ed59cf0194c9
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/diameterOfBinaryTree.py
| 1,290
| 4.3125
| 4
|
"""
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time Complexity: O(N). We visit every node once.
Space Complexity: O(N), the size of our implicit call stack during our depth-first search.
"""
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
self.depth(root)
return self.res-1 # -1 because length is defined as the number of edges
def depth(self, node):
if not node:
return 0
left = self.depth(node.left)
right = self.depth(node.right)
self.res = max(self.res, left+right+1)
return max(left, right) + 1
| true
|
f490e6054c9d90343cab89c810ca2c649d8138fe
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/mergeIntervals.py
| 1,167
| 4.125
| 4
|
"""
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
"""
Time: O(nlogn)
Space: O(n)
"""
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
start, end, result = [], [], []
for interval in intervals:
st, en = interval.start, interval.end
start.append(st)
end.append(en)
start.sort()
end.sort()
i = 0
while i < len(intervals):
st = start[i]
while i < len(intervals) - 1 and start[i + 1] <= end[i]:
i += 1
en = end[i]
result.append([st, en])
i += 1
return result
| true
|
d86c8afbca66bd1b0731b02fbb2c1bbf551c2615
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/reverseLinkedList.py
| 2,118
| 4.21875
| 4
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = None
while head:
head.next, head, new_head = new_head, head.next, head
return new_head
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
return self._reverse(head)
def _reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n, node)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
Iterative
Time: O(n)
Space: O(1)
"""
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr is not None:
nextTemp = curr.next
curr.next = prev
prev = curr
curr = nextTemp
return prev
"""
Recursive
The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part? Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø
Assume from node nk+1 to nm had been reversed and you are at node nk.
n1 → … → nk-1 → nk → nk+1 ← … ← nm
We want nk+1’s next node to point to nk.
So,
nk.next.next = nk;
Be very careful that n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.
Time: O(n)
Space: O(n) due to stack space
"""
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
| false
|
99e25be34833e876da74bb6f53a62edf745be9a5
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/sortedSquares.py
| 2,053
| 4.25
| 4
|
"""
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
"""
"""
Time Complexity: O(N log N), where N is the length of A.
Space Complexity: O(N).
"""
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
return sorted(x*x for x in A)
"""
Approach 2: Two Pointer
Intuition
Since the array A is sorted, loosely speaking it has some negative elements with squares in decreasing order, then some non-negative elements with squares in increasing order.
For example, with [-3, -2, -1, 4, 5, 6], we have the negative part [-3, -2, -1] with squares [9, 4, 1], and the positive part [4, 5, 6] with squares [16, 25, 36]. Our strategy is to iterate over the negative part in reverse, and the positive part in the forward direction.
Algorithm
We can use two pointers to read the positive and negative parts of the array - one pointer j in the positive direction, and another i in the negative direction.
Now that we are reading two increasing arrays (the squares of the elements), we can merge these arrays together using a two-pointer technique.
Time Complexity: O(N), where N is the length of A.
Space Complexity: O(N).
"""
class Solution(object):
def sortedSquares(self, A):
N = len(A)
# i, j: negative, positive parts
j = 0
while j < N and A[j] < 0:
j += 1
i = j - 1
ans = []
while 0 <= i and j < N:
if A[i]**2 < A[j]**2:
ans.append(A[i]**2)
i -= 1
else:
ans.append(A[j]**2)
j += 1
while i >= 0:
ans.append(A[i]**2)
i -= 1
while j < N:
ans.append(A[j]**2)
j += 1
return ans
| true
|
33e938d5592965fa2c772c5c958ced297ee18955
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/flipEquivalentBinaryTree.py
| 1,531
| 4.1875
| 4
|
"""
Flip Equivalent Binary Trees
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.
"""
"""
There are 3 cases:
If root1 or root2 is null, then they are equivalent if and only if they are both null.
Else, if root1 and root2 have different values, they aren't equivalent.
Else, let's check whether the children of root1 are equivalent to the children of root2. There are two different ways to pair these children.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Time Complexity: O(min(N_1, N_2)) where N_1, N_2N are the lengths of root1 and root2.
Space Complexity: O(min(H_1, H_2)) are the heights of the trees of root1 and root2.
"""
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1 is None and root2 is None:
return True
if not root1 or not root2 or 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
|
302f7ed1d4569abaf417efddff2c2b1721146207
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/maxStack.py
| 2,794
| 4.25
| 4
|
"""
Max Stack
Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
-1e7 <= x <= 1e7
Number of operations won't exceed 10000.
The last four operations won't be called when stack is empty.
"""
"""
A regular stack already supports the first 3 operations and max heap can take care of the last two. But the main issue is when popping an element form the top of one data structure how can we efficiently remove that element from the other. We can use lazy removal (similar to Approach #2 from 480. Sliding Window Median) to achieve this is in average O(log N) time.
"""
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.maxHeap = []
self.toPop_heap = {} #to keep track of things to remove from the heap
self.toPop_stack = set() #to keep track of things to remove from the stack
def push(self, x):
"""
:type x: int
:rtype: void
"""
heapq.heappush(self.maxHeap, (-x,-len(self.stack)))
self.stack.append(x)
def pop(self):
"""
:rtype: int
"""
self.top()
x = self.stack.pop()
key = (-x,-len(self.stack))
self.toPop_heap[key] = self.toPop_heap.get(key,0) + 1
return x
def top(self):
"""
:rtype: int
"""
while self.stack and len(self.stack)-1 in self.toPop_stack:
x = self.stack.pop()
self.toPop_stack.remove(len(self.stack))
return self.stack[-1]
def peekMax(self):
"""
:rtype: int
"""
while self.maxHeap and self.toPop_heap.get(self.maxHeap[0],0):
x = heapq.heappop(self.maxHeap)
self.toPop_heap[x] -= 1
return -self.maxHeap[0][0]
def popMax(self):
"""
:rtype: int
"""
self.peekMax()
x,idx = heapq.heappop(self.maxHeap)
x,idx = -x,-idx
self.toPop_stack.add(idx)
return x
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()
| true
|
5851ff675353f950e8a9a1c730774a35ab54b8db
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/stringConversion.py
| 2,321
| 4.25
| 4
|
"""
Given 2 strings s and t, determine if you can convert s into t. The rules are:
You can change 1 letter at a time.
Once you changed a letter you have to change all occurrences of that letter.
Example 1:
Input: s = "abca", t = "dced"
Output: true
Explanation: abca ('a' to 'd') -> dbcd ('c' to 'e') -> dbed ('b' to 'c') -> dced
Example 2:
Input: s = "ab", t = "ba"
Output: true
Explanation: ab -> ac -> bc -> ba
Example 3:
Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bcdefghijklmnopqrstuvwxyza"
Output: false
Example 4:
Input: s = "aa", t = "cd"
Output: false
Example 5:
Input: s = "ab", t = "aa"
Output: true
Example 6:
Input: s = "abcdefghijklmnopqrstuvwxyz", t = "bbcdefghijklmnopqrstuvwxyz"
Output: true
Both strings contain only lowercase English letters.
"""
"""
Time Complexity: O(s)
Space Complexity: O(s)
This seems like those mapping problems of one string to another on steroids. After we modify a certain letter, the new letter for that group may be the same as a later letter in s. So we'd want to use a placeholder for certain mappings, but at what point do we run out of placeholders? Definitely when we're using all 26 letters, but is that the only time? It seems like it's very hard to prove that, given all the potential overlaps of mappings that may occur.
If that is the reality though, I'd say as long as we can map every letter in s to the same letter in b, and as long as there aren't 26 letters (or if there are 26 letters, the strings must be identical), then we can do the conversion...
"""
def convert(s, t):
if len(s) != len(t):
return False
if s == t:
return True
dict_s = {} # match char in s and t
unique_t = set() # count unique letters in t
for i in range(len(s)):
if (s[i] in dict_s):
if dict_s[s[i]] != t[i]:
return False
else:
dict_s[s[i]] = t[i]
unique_t.add(t[i])
if len(dict_s) == 26:
return len(unique_t) < 26
return True
if __name__ == '__main__':
assert convert('abca', 'dced') == True
assert convert('ab', 'ba') == True
assert convert('abcdefghijklmnopqrstuvwxyz', 'bcdefghijklmnopqrstuvwxyza') == False
assert convert('aa', 'cd') == False
assert convert('ab', 'aa') == True
assert convert('abcdefghijklmnopqrstuvwxyz', 'bbcdefghijklmnopqrstuvwxyz') == True
| true
|
de1cdd7c24ce9e56af7baaf562ad915960eb246d
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/uniquePaths.py
| 1,433
| 4.15625
| 4
|
"""
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
"""
"""
DP (recursion is 2^n)
Time: O(m*n)
Space: O(m*n) => can be reduced to just storing one row to O(n) space
"""
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for _ in range(m)] for _ in range(n)]
dp[0][0] = 1
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
"""
Math Way
"""
# math C(m+n-2,n-1)
def uniquePaths1(self, m, n):
if not m or not n:
return 0
return math.factorial(m+n-2)/(math.factorial(n-1) * math.factorial(m-1))
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
grid = [[1 for i in range(m)] for _ in range(n)]
for i in range(n):
for j in range(m):
if not i or not j:
continue
grid[i][j] = grid[i - 1][j] + grid[i][j - 1]
return grid[n - 1][m - 1]
| true
|
e81fb3440413a2ca42df459fec604df7d2aad8b8
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/largestSubarrayLengthK.py
| 1,764
| 4.1875
| 4
|
"""
Largest Subarray Length K
Array X is greater than array Y if the first non matching element in both
arrays has a greater value in X than Y.
For example:
X = [1, 2, 4, 3, 5]
Y = [1, 2, 3, 4, 5]
X is greater than Y because the first element that does not match is larger in X.
and if
A = [1, 4, 3, 2, 5] and K = 4, the result is
[4, 3, 2, 5]
"""
# my interpretation is that we can look at all the possible starting indices for a starting array and compare the first value. All elements are unique (distinct), so one value within an array will always be larger or smaller than another--giving us the largest subarray if we just compare that first index.
# if A is all unique
"""
Time: O(N), space: O(1)
"""
def solution(a, k):
# store the first starting index for a subarray as the largest since len(a) will be <= k
first_idx = 0
for x in range(1, len(a)-k+1): # check indices where a subarray of size k can be made
# replace the largest first index if a larger value is found
first_idx = x if a[first_idx] < a[x] else first_idx
return a[first_idx:first_idx+k]
def solution2(a, k):
first_idx = 0
for x in range(1, len(a) - k + 1):
# compare values at each index for the would be sub arrays
for i in range(k):
# replace the largest index and break out of the inner loop is larger value is found
if a[first_idx + i] <= a[x + i]:
first_idx = x
break
# if the current stored largest subarray is larger than the current subarray, move on
else:
break
return a[first_idx:first_idx+k]
if __name__ == '__main__':
assert solution(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5]
assert solution2(a=[1, 4, 3, 2, 5], k=4) == [4, 3, 2, 5]
assert solution2(a=[1, 4, 4, 2, 5], k=4) == [4, 4, 2, 5]
| true
|
2b4e64d837993111fde673235c80dc26e3ded912
|
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
|
/Challenges/reconstructItinerary.py
| 2,112
| 4.375
| 4
|
"""
Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
"""
"""
DFS
Time: O(N) where N is number of tickets
Note: sort in reverse first so we can have the graph to contain the smallest lexical order
so we can guarantee the lexical order of the itinerary can be as good as possible
"""
class Solution:
# Iterative
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = collections.defaultdict(list)
for src, dest in sorted(tickets, reverse=True):
graph[src].append(dest)
res = []
stack = ['JFK']
while stack:
while graph[stack[-1]]:
stack.append(graph[stack[-1]].pop())
res.append(stack.pop())
return res[::-1]
# Recursive
def findItinerary(self, tickets):
targets = collections.defaultdict(list)
for a, b in sorted(tickets)[::-1]:
targets[a] += b,
route = []
def visit(airport):
while targets[airport]:
visit(targets[airport].pop())
route.append(airport)
visit('JFK')
return route[::-1]
| true
|
aeab15f7f34cbad76d3a883e44b0883a1666e4d7
|
nixis-institute/practice
|
/python/bhawna/week.py
| 352
| 4.125
| 4
|
number=int(input("enter the number"))
if number==1:
print("monday")
elif number==2:
print("tuesday")
elif number==3:
print("wednesday")
elif number==4:
print("thursday")
elif number==5:
print("friday")
elif number==6:
print("saturday")
elif number==7:
print("sunday")
else:
print("given input is wrong")
| false
|
768b7b2bb0dd863b28c6ff657a3819fc4ae6162a
|
akuks/Python3.6---Novice-to-Ninja
|
/Ch9/09-FileHandling-01.py
| 634
| 4.21875
| 4
|
import os
# Prompt User to Enter the FileName
fileName = str(input("Please Enter the file Name: "))
fileName = fileName.strip()
while not fileName:
print("Name of the File Cannot be left blank.")
print("Please Enter the valid Name of the File.")
fileName = str(input("Please Enter the file Name: "))
fileName = fileName.strip()
# Check if the file Entered by the User exists
if not os.path.exists(fileName):
print(fileName, " does not exists")
print("Exiting the Program")
exit(1)
print("File Name Entered by the User is : ", fileName)
fh = open(fileName, 'r')
for line in fh:
print(line)
| true
|
848ff8ae6cb99f3f6b768df53ebd4d9fd9486cfe
|
akuks/Python3.6---Novice-to-Ninja
|
/Ch8/08-tuple-01.py
| 204
| 4.125
| 4
|
# Create Tuple
tup = (1, 2, 3, "Hello", "World")
print(tup)
# Looping in Tuple
for item in tup:
print (item)
# in operator
b = 4 in tup
print(b)
# Not in Operator
b = 4 not in tup
print (b)
| true
|
bbed894c316e17e8cdbde0ed2d0db28ddd6d2285
|
pbscrimmage/thinkPy
|
/ch5/is_triangle.py
| 1,108
| 4.46875
| 4
|
'''
is_triangle.py
Author: Patrick Rummage
[patrickbrummage@gmail.com]
Objective:
1. Write a function is_triangl that takes three integers as
arguments, and prints either "yes" or "no" depending on
whether a triangle may be formed from the given lengths.
2. Write a function that prompts the user to input three
lengths, converts them to integers, and uses is_triangle
to test whether the given lengths can form a triangle.
'''
def test_lengths():
values = [ ['a', 0], ['b', 0], ['c', 0] ]
for v in values: # get input and validate
valid = False
while not valid:
v[1] = int(raw_input("Enter a value for %s: " % v[0]))
if v[1] < 1:
print "a, b, and c must be positive integers!"
else:
valid = True
is_triangle(values[0][1], values[1][1], values[2][1])
def is_triangle(a, b, c):
var_list = [a, b, c]
for v in var_list:
lcopy = var_list[:]
lcopy.remove(v)
if v > sum(lcopy):
print "No."
print "Yes."
test_lengths()
| true
|
a3338b41d3399b462b32674111f28e465782f6f2
|
abbye1093/AFS505
|
/AFS505_U1/assignment3/ex16.py
| 1,309
| 4.4375
| 4
|
#reading and writing files
#close: closes the file, similar to file > save
#read: reads contents of files
#readline: reads just one readline
#truncate: empties the file
#write('stuff') : writes 'stuff' to file
#seek(0): moves the read/write location to the beginning of the files
from sys import argv
script, filename = argv
#getting filename from the argv entry when opening/running py file
print(f"We're goint to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?") #want input from user while script is running
print("Opening the file...")
target = open(filename, 'w') #opening the file in write mode, instead of default read
print("Truncating the file. Goodbye!")
#truncating empties the file
target.truncate()
print("Now I'm going to ask you for three lines.")
#asks for user input for each line
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
#will this work? nope,
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
#close aka file > save
target.close() #run close with no parameter changes on target
| true
|
72d72c40a3279d64be8b7677e71761aed1b7155f
|
ggggg/PythonAssignment-
|
/exchange.py
| 452
| 4.1875
| 4
|
# get currency
print('enter currency, USD or CAD:')
currency = input().upper()
# get the value
print('Enter value:')
value = float(input())
# usd
if (currency == 'USD'):
# make calculation and output result
print('The value in CAD is: $' + str(value * 1.27))
# cad
elif (currency == 'CAD'):
# make calculation and output result
print('The value in USD is: $' + str(value * 0.79))
# currency not found
else:
print('Currency not found.')
| true
|
efea3fc1186254cd2a2b40171114de6af466a8cd
|
angelaannjaison/plab
|
/15.factorial using function.py
| 312
| 4.21875
| 4
|
def fact(n):
f=1
if n==0:print("The factorial of ",n,"is 1")
elif(n<0):print("factorial does not exit for negative numbers")
else:
for i in range(1,n+1):
f=f*i
print("The factorial of ",n,"is",f)
n=int(input("To find factorial:enter a number = "))
fact(n)
| true
|
754c02472453ab001c18bb13f5118aa0851ada80
|
angelaannjaison/plab
|
/17.pyramid of numbers.py
| 258
| 4.15625
| 4
|
def pyramid(n):
for i in range(1,n+1):#num of rows
for j in range(1,i+1):#num of columns
print(i*j,end=" ")
print("\n")#line space
n=int(input("To construct number pyramid:Enter number of rows and columns: "))
pyramid(n)
| true
|
e500b5ef5f72359ba07c06ed10ec2b3e12dabfb6
|
angelaannjaison/plab
|
/to find largest of three numbers.py
| 297
| 4.1875
| 4
|
print("To find the largest among three numbers")
A = int(input("Enter first number = "))
B = int(input("Enter second number = "))
C = int(input("Enter third number = "))
if A>B and A>C:
print(A," is greatest")
elif B>C:
print(B," is greatest")
else:
print(C,"is greatest")
| true
|
8e3aeedca99b9abff8282876fbf5b655c1f10a76
|
mtouhidchowdhury/CS1114-Intro-to-python
|
/Homework 3/hw3q4.py
| 787
| 4.46875
| 4
|
#homework 3 question 4
#getting the input of the sides
a = float(input("Length of first side: "))
b = float(input("Length of second side: "))
c = float(input("Length of third side: "))
if a == b and b == c and a ==c :# if all sides equal equalateral triangle
print("This is a equilateral triangle")
elif a == b or a == c or b == c:# if two sides equal isosceles triangle
print("this is a isoseles triangle")
elif (a == b or a == c or b == c) and (a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or c**2 + b**2 == a**2):
print("this is an isosceles right triangle ")#if two sides equal and pythagorean formula fits its isosceles right triangle
else:#if none of the conditions apply its neither
print("neither equalateral nor isosceles right triangle")
| true
|
e2836dded795cfd45e297f05d467e04c35901858
|
mtouhidchowdhury/CS1114-Intro-to-python
|
/Homework 7/hw7q3.py
| 1,710
| 4.1875
| 4
|
#importing module
import random
#generating a random number and assign to a variable
randomNumber = random.randint(1,100)
#set number of guesses to 0 and how many remain to 5
numberGuesses= 0
guessRemain = 5
#first guess
userGuess = int(input("please enter a number between 1 and 100: "))
# minus from guess remain and adding to number of guesses
guessRemain -= 1
numberGuesses += 1
# making bounds for the ranges
lowerBound = 0
upperBound = 101
#if first guess correct then goes to if otherwise goes to else
if userGuess == randomNumber:
print("Your Correct!")
#loop till guesses remaining is 0 and user's guess is the number
else:
while guessRemain != 0 and userGuess != randomNumber :
if userGuess < randomNumber:
lowerBound = userGuess
userGuessLine = "Guess again between "+ str(lowerBound + 1) + " and " + str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: "
userGuess = int(input (userGuessLine))
guessRemain -= 1
numberGuesses += 1
elif userGuess > randomNumber:
upperBound = userGuess
userGuessLine = "Guess again between " + str(lowerBound + 1) + " and "+ str(upperBound - 1) + ". You have " + str(guessRemain) + " guesses remaining: "
userGuess = int(input (userGuessLine))
guessRemain -= 1
numberGuesses += 1
#output if won tells how many guesses took if lost then tells user that he/she lost
if userGuess == randomNumber:
line= "Congrats! you guessed the answer in " + str(numberGuesses) + " guesses!"
print(line)
else:
print ("You ran out of guesses")
| true
|
a12107517ff64eb1332b2dcfcbe955419bc5d935
|
kelvin5hart/calculator
|
/main.py
| 1,302
| 4.15625
| 4
|
import art
print(art.logo)
#Calculator Functions
#Addition
def add (n1, n2):
return n1 + n2
#Subtraction
def substract (n1, n2):
return n1 - n2
#Multiplication
def multiply (n1, n2):
return n1 * n2
#Division
def divide(n1, n2):
return n1 / n2
opperators = {
"+": add,
"-":substract,
"*": multiply,
"/": divide
}
def calculator():
num1 = float(input("What's the first number? \n"))
nextCalculation = True
for i in opperators:
print (i)
while nextCalculation:
operator = input("Pick an operation from the line above: ")
if operator not in opperators:
nextCalculation = False
print("Your entry was invalid")
calculator()
num2 = float(input("What's the next number? \n"))
operation = opperators[operator]
result = operation(num1, num2)
print(f"{num1} {operator} {num2} = {result}")
continueCalculation = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculation or 'e' to exit. \n").lower()
if continueCalculation == "y":
num1 = result
elif continueCalculation == "n":
nextCalculation = False
calculator()
elif continueCalculation == "e":
nextCalculation = False
else:
print("Invalid Entry")
nextCalculation = False
calculator()
| true
|
36f1263ebdbaf546d5e6b6ad874a0f8fc51ef65a
|
andredupontg/PythonInFourHours
|
/pythonInFourHours.py
| 1,628
| 4.1875
| 4
|
# Inputs and Outputs
"""
name = input("Hello whats your name? ")
print("Good morning " + name)
age = input("and how old are you? ")
print("thats cool")
"""
# Arrays
"""
list = ["Volvo", "Chevrolet", "Audi"]
print(list[2])
"""
# Array Functions
"""
list = ["Volvo", "Chevrolet", "Audi"]
list.insert(1, "Corona")
list.remove("Corona")
list.clear()
list.pop()
list.index("Volvo)
"""
# Functions
"""
def myFirstFunction():
print("Hello this is my first function! ")
print("NEW PROGRAM")
myFirstFunction()
"""
# Return Function
"""
def powerNumber(number):
return number * number
print("NEW PROGRAM")
print(powerNumber(3))
"""
# If & Else
"""
age = 0
if age >= 18:
print("Overage")
elif age < 18 and age > 0:
print("Underage")
else:
print("Not even born")
"""
# While Loops
"""
i = 0
while i < 4:
print("Haha")
i += 1
print("End of the loop")
"""
# For Loopss
"""
fruits = ["apple", "orange", "banana"]
for x in fruits:
print(x)
"""
# Class & Objects
"""
class Student:
def __init__(self, name, age, career):
self.name = name
self.age = age
self.career = career
student = Student("Andre", 22, "systems engineering")
print(student.name)
print(student.age)
print(student.career)
"""
# Class Methods
"""
class Student:
def __init__(self, name, age, career):
self.name = name
self.age = age
self.career = career
def calculateSalaryByAge(self):
if self.age < 60 and self.age >= 18:
return 3000
else:
return 0
student = Student("Andre", 22, "Systems Engineering")
print(student.calculateSalaryByAge())
"""
| true
|
f4ac6f727eda468a18aaaeb59489940150419e63
|
Tanushka27/practice
|
/Class calc.py
| 423
| 4.125
| 4
|
print("Calculator(Addition,Subtraction,Multiplication and Division)")
No1=input("Enter First value:")
No1= eval(No1)
No2= input("Enter Second value:")
No2= eval(No2)
Sum= No1+No2
print (" Sum of both the values=",Sum)
Diff= No1-No2
print("Difference of both values=",Diff)
prod= No1*No2
print("Product of both the values=",prod)
Div= No1/No2
print ("Division of the value is=",Div)
mod= No1%No2
print ("remainder is=",mod)
| true
|
9ab6fc2ba3ae33bc507d257745279687926d62d2
|
khushbooag4/NeoAlgo
|
/Python/ds/Prefix_to_postfix.py
| 1,017
| 4.21875
| 4
|
"""
An expression is called prefix , if the operator appears in the expression before the operands. (operator operand operand)
An expression is called postfix , if the operator appears in the expression after the operands . (operand operand operator)
The program below accepts an expression in prefix and outputs the corresponding postfix expression .
"""
# prefixtopostfix function converts a prefix expression to postfix
def prefixtopostfix(exp):
stack = []
n = len(exp)
for i in range(n - 1, -1, -1):
if exp[i].isalpha():
stack.append(exp[i])
else:
op1 = stack.pop()
op2 = stack.pop()
stack.append(op1 + op2 + exp[i])
print("the postfix expresssion is : " + stack.pop())
# Driver Code
if __name__ == "__main__":
exp = input("Enter the prefix expression : ")
prefixtopostfix(exp)
"""
Sample I/O:
Enter the prefix expression : *+abc
the postfix expresssion is : ab+c*
Time complexity : O(n)
space complexity : O (n)
"""
| true
|
9adc4c2e16a6468b7c39231425c0c7f2a3b6f843
|
khushbooag4/NeoAlgo
|
/Python/ds/Sum_of_Linked_list.py
| 2,015
| 4.25
| 4
|
"""
Program to calculate sum of linked list.
In the sum_ll function we traversed through all the functions of the linked list and calculate
the sum of every data element of every node in the linked list.
"""
# A node class
class Node:
# To create a new node
def __init__(self, data):
self.data = data
self.next = None
# Class Linked list
class LinkedList:
# create a empty linked list
def __init__(self):
self.head = None
# Function to insert elements in linked list
def push(self, data):
newNode = Node(data)
temp = self.head
newNode.next = self.head
# If linked list is not None then insert at last
if self.head is not None:
while (temp.next != self.head):
temp = temp.next
temp.next = newNode
else:
newNode.next = newNode # For the first node
self.head = newNode
# Function to print given linked list
def print_List(self):
temp = self.head
if self.head is not None:
while (True):
print(temp.data)
temp = temp.next
if (temp == self.head):
break
# Function to calculate sum of a Linked list
def sum_ll(self, head):
sum_ = 0
temp = self.head
if self.head is not None:
while True:
sum_ += temp.data
temp = temp.next
return sum_
# Initialize lists as empty by creating Linkedlist objects
head = LinkedList()
# Pushing elements into LinkedList
n = int(input("Enter the no. of elements you want to insert: "))
for i in range(n):
number = int(input(f"Enter Element {i + 1}: "))
head.push(number)
print("Entered Linked List: ")
head.print_List()
sum_ = head.sum_ll(head)
print(f"\nSum of Linked List: {sum_}")
"""
Time Complexity: O(n)
Space Complexity: O(n)
SAMPLE INPUT/OUTPUT:
Entered Circular Linked List:
20 30 40 50
Sum of Linked List: 140
"""
| true
|
ca903edb902b818cd3cda5ad5ab975f12f99d467
|
khushbooag4/NeoAlgo
|
/Python/search/three_sum_problem.py
| 2,643
| 4.15625
| 4
|
"""
Introduction:
Two pointer technique is an optimization technique which is a really clever way of using
brute-force to search for a particular pattern in a sorted list.
Purpose:
The code segment below solves the Three Sum Problem. We have to find a triplet out of the
given list of numbers such that the sum of that triplet equals to another given value.
The Naive Approach is to calculate the sum of all possible triplets and return the one with
the required sum or None. This approach takes O(N^3) time to run. However, by using Two pointer
search technique we can reduce the time complexity to O(N^2).
Method:
Three Sum Problem using Two Pointer Technique
"""
def three_sum_problem(numbers, sum_val):
"""
Returns a triplet (x1,x2, x3) in list of numbers if found, whose sum equals sum_val, or None
"""
# Sort the given list of numbers
# Time complexity: O(N.logN)
numbers.sort()
size = len(numbers)
# Two nested loops
# Time complexity: O(N^2)
for i in range(size-3+1):
# Reduce the problem to two sum problem
two_sum = sum_val - numbers[i]
# Initialize the two pointers
left = i+1
right = size-1
# Search in the array until the two pointers overlap
while left < right:
curr_sum = numbers[left] + numbers[right]
# Update the pointers
if curr_sum < two_sum:
left += 1
elif curr_sum > two_sum:
right -= 1
else:
# Return the numbers that form the desired triplet
return "({},{},{})".format(numbers[i], numbers[left], numbers[right])
# No triplet found
return None
def main():
"""
Takes user input and calls the necessary function
"""
# Take user input
numbers = list(map(int, input("Enter the list of numbers: ").split()))
sum_val = int(input("Enter the value of sum: "))
# Find the triplet
triplet = three_sum_problem(numbers, sum_val)
if triplet is None:
print(f"No triplet found with sum: {sum_val}")
else:
print(f"{triplet} is the triplet with sum: {sum_val}")
if __name__ == "__main__":
# Driver code
main()
"""
Sample Input 1:
Enter the list of numbers: 12 3 4 1 6 9
Enter the value of sum: 24
Sample Output 1:
(3,9,12) is the triplet with sum: 24
Time Complexity:
For sorting: O(N.log N)
For two-pointer technique: O(N^2)
T = O(N.log N) + O(N^2)
T = O(N^2)
"""
| true
|
f9e6bfee3042b3a877fe84856ed539acc1c6f687
|
khushbooag4/NeoAlgo
|
/Python/math/Sieve-of-eratosthenes.py
| 980
| 4.21875
| 4
|
'''
The sieve of Eratosthenes is an algorithm for finding
all prime numbers up to any given limit. It is
computationally highly efficient algorithm.
'''
def sieve_of_eratosthenes(n):
sieve = [True for i in range(n + 1)]
p = 2
while p ** 2 <= n:
if sieve[p]:
i = p * p
while i <= n:
sieve[i] = False
i += p
p += 1
length = len(sieve)
for i in range(2, length):
if sieve[i]:
print(i, end=" ")
def main():
print("Enter the number upto which prime numbers are to be computed: ")
n = int(input())
print("The number of prime numbers less than " + str(n) + " is :")
sieve_of_eratosthenes(n)
if __name__ == "__main__":
main()
'''
Sample I/O:
Enter the number upto which prime numbers are to be computed:
30
The number of prime numbers less than 30 is :
2 3 5 7 11 13 17 19 23 29
Time complexity : O(n*(log(log(n))))
Space complexity : O(n)
'''
| false
|
8d08dac477e5b8207c351650fef30b64da52c64a
|
khushbooag4/NeoAlgo
|
/Python/math/roots_of_quadratic_equation.py
| 1,544
| 4.34375
| 4
|
''''
This is the simple python code for finding the roots of quadratic equation.
Approach : Enter the values of a,b,c of the quadratic equation of the form (ax^2 bx + c )
the function quadraticRoots will calculate the Discriminant , if D is greater than 0 then it will find the roots and print them otherwise it will print Imaginary!!
'''
import math
class Solution:
def quadraticRoots(self, a, b, c):
d = ((b*b) - (4*a*c))
if d<0:
lst=[]
lst.append(-1)
return lst
D = int(math.sqrt(d))
x1 = math.floor((-1*b + D)/(2*a))
x2 = math.floor((-1*b - D)/(2*a))
lst = []
lst.append(int(x1))
lst.append(int(x2))
lst.sort()
lst.reverse()
return lst
# Driver Code Starts
if __name__ == '__main__':
# For the values of a,b,c taking in a list in one line eg : 1 2 3
print("Enter the values for a,b,c of the equation of the form ax^2 + bx +c")
abc=[int(x) for x in input().strip().split()]
a=abc[0]
b=abc[1]
c=abc[2]
# Making a object to class Solution
ob = Solution()
ans = ob.quadraticRoots(a,b,c)
if len(ans)==1 and ans[0]==-1:
print("Imaginary Roots")
else:
print("Roots are :",end=" ")
for i in range(len(ans)):
print(ans[i], end=" ")
print()
'''
Sample Input/Output:
Enter the values for a,b,c of the equation of the form ax^2 + bx +c
1 2 1
Output:
Roots are : -1 -1
Time Complexity : O(1)
Space Complexity : O(1)
'''
| true
|
e88f786eb63150123d9aba3a3dd5f9309d825ca1
|
khushbooag4/NeoAlgo
|
/Python/math/positive_decimal_to_binary.py
| 876
| 4.59375
| 5
|
#Function to convert a positive decimal number into its binary equivalent
'''
By using the double dabble method, append the remainder
to the list and divide the number by 2 till it is not
equal to zero
'''
def DecimalToBinary(num):
#the binary equivalent of 0 is 0000
if num == 0:
print('0000')
return
else:
binary = []
while num != 0:
rem = num % 2
binary.append(rem)
num = num // 2
#reverse the list and print it
binary.reverse()
for bit in binary:
print(bit, end="")
#executable code
decimal = int(input("Enter a decimal number to be converted to binary : "))
print("Binary number : ")
DecimalToBinary(decimal)
'''
Sample I/O :
Input :
Enter a decimal number to be converted into binary: 8
Output:
Binary number:
1000
Time Complexity : O(n)
Space Complexity : O(1)
'''
| true
|
170fef88011fbda1f0789e132f1fadb71ebca009
|
khushbooag4/NeoAlgo
|
/Python/cp/adjacent_elements_product.py
| 811
| 4.125
| 4
|
"""
When given a list of integers,
we have to find the pair of adjacent
elements that have the largest product
and return that product.
"""
def MaxAdjacentProduct(intList):
max = intList[0]*intList[1]
a = 0
b = 1
for i in range(1, len(intList) - 1):
if(intList[i]*intList[i+1] > max):
a = i
b = i+1
max = intList[i]*intList[i+1]
return(a, b, max)
if __name__ == '__main__':
intList = list(map(int, input("\nEnter the numbers : ").strip().split()))
pos1, pos2, max = MaxAdjacentProduct(intList)
print("Max= ", max, " product of elements at position ", pos1, ",", pos2)
"""
Sample Input - Output:
Enter the numbers : -5 -3 -2
Max= 15 product of elements at position 0 , 1
Time Complexity : O(n)
Space Complexity : O(1)
"""
| true
|
99f2401aa02902befcf1ecc4a60010bb8f02bc32
|
khushbooag4/NeoAlgo
|
/Python/other/stringkth.py
| 775
| 4.1875
| 4
|
'''
A program to remove the kth index from a string and print the remaining string.In case the value of k
is greater than length of string then return the complete string as it is.
'''
#main function
def main():
s=input("enter a string")
k=int(input("enter the index"))
l=len(s)
#Check whether the value of k is greater than length
if(k>l):
print(s)
#If k is less than length of string then remove the kth index value
else:
s1=''
for i in range(0,l):
if(i!=k):
s1=s1+s[i]
print(s1)
if __name__== "__main__":
main()
'''
Time Complexity:O(n),n is length of string
Space Complexity:O(1)
Input/Output:
enter a string python
enter the index 2
pyhon
'''
| true
|
e45468bee33c3ba54bed011897de4c87cdf5b669
|
GerardProsper/Python-Basics
|
/Lesson 1_10102020.py
| 2,366
| 4.3125
| 4
|
## Intro to Python Livestream - Python Basics with Sam
name = 'Gerard'
####print(name)
##
##for _ in range(3):
## print(name)
##
##for i in range(1,5):
## print(i)
l_5=list(range(5))
##
##for i in range(2,10,2):
## print(i)
##for num in l_5:
## print(num)
## print(num*2)
## print()
##
##letters = 'PTJB'
##
##for letter in letters:
## print(letter + name[1:])
##def hello():
## name = input("Enter name:")
## print('Hello ' + name)
##
##hello()
##def blank():
## print()
##
##def blank_3():
## blank()
## blank()
## blank()
##
##def blank_9():
## blank_3()
## blank_3()
## blank_3()
##
##blank_9()
numbers = [1,-5,2,-4,0,6,-10,3]
##for number in numbers:
## if number % 2 == 0:
## print(number, "is even")
## else:
## print (number, "is odd")
##
##for number in numbers:
## if number == 0:
## print ("Zero")
## elif number > 0:
## print ("positive")
## else:
## print("negative")
##
##def even(x):
## """ enter number to be checked if even"""
## if x % 2 == 0:
## return True
##def even(x):
## return x % 2 == 0
##
##def odd(y):
## return y % 2 != 0
##
##print (even(4))
##
##print (odd(3))
##for row in range (5):
## for col in range(5):
## print(col,end='') ##cannot use 'sep' as only calling out col and not row. 'end' makes a row become column (or everything one line) https://www.youtube.com/watch?v=1CGZ9YDCeWg
## print() # if have print with 'for col' then it's the same as just print(col) as print () supersedes print (col, end=''). Putting it here makes it break after finishing col
##
##
##01234
##01234
##01234
##01234
##01234
##
##
##>>> for row in range (5):
## for col in range (5):
## print(col,end='')
##
##
##0123401234012340123401234
##
##
##>>> for row in range (5):
## for col in range (5):
## print(col,end='')
## print()
##
##
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##0
##1
##2
##3
##4
##
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
people = [" Malaysia", "Singapore", "China"]
for x in adj:
for y in fruits:
for z in people:
print(x,y,z)
| false
|
a5336ab6b2ac779752cab97aee3dcca16237a4d7
|
dkrajeshwari/python
|
/python/prime.py
| 321
| 4.25
| 4
|
#program to check if a given number is prime or not
def is_prime(N):
if N<2:
return False
for i in range (2,N//2+1):
if N%i==0:
return False
return True
LB=int(input("Enter lower bound:"))
UB=int(input("Enter upper bound:"))
for i in range(LB,UB+1):
if is_prime(i):
print(i)
| true
|
204a83101aee7c633893d87a111785c3884829de
|
dkrajeshwari/python
|
/python/bill.py
| 376
| 4.125
| 4
|
#program to calculate the electric bill
#min bill 50rupee
#1-500 6rupees/unit
#501-1000 8rupees/unit
#>1000 12rupees/unit
units=int(input("Enter the number of units:"))
if units>=1 and units<=500:
rate=6
elif units>=501 and units<=1000:
rate=8
elif units>1000:
rate=12
amount=units*rate
if amount<50:
amount=50
print(f"Units used:{units},Bill amount:{amount}")
| true
|
458273bb73e4b98f097fbb87cfa531f994f55fc7
|
vaishnavi59501/DemoRepo1
|
/samplescript.py
| 2,635
| 4.59375
| 5
|
#!/bin/python3
#this scipt file contains list,tuple,dictionary and implementation of functions on list,tuple and Dictionary
#list
#list is collection of objects of different types and it is enclosed in square brackets.
li=['physics', 'chemistry', 1997, 2000]
list3 = ["a", "b", "c", "d"]
print(li[1]) #accessing first element in list li
print(li) #diplaying the list li
print(li[:2]) #displaying range of elements in list
print(li*2) #displaying list li two times using repetition operator(*)
l=li+list3
print(l) #concatenating two lists and displaying it
#updating list
li[2]='physics'
print(li)
a=1997
print(a in li) #returns true if a is member of list otherwise false
print(len(li)) #returns the no of elements in list
print(max(list3)) #returns maximum element in list list3
print(min(list3)) #returns minimum element in list list3
list3=list3+["e","f"] #adding elements to the list
print(list3)
tuple1=(1,2,3,4,5)
print("tuple :",tuple1) #converting sequence of elements (e.g. tuple) to list
print("tuple converted to list ",list(tuple1))
print(list1.count(123)) #returns the number of occurence of the element in the list
print(list3)
del list3[3] #deletes the element at index 3 in list3
print(list3)
#tuple
#tuple is similar to list but the difference is elements are enclosed using braces () and here updating tuple is not valid action.
tup=(23,) #declaring tuple with single element along with character comma
print(tup)
print(tup+(34,36,37)) #adding elements to tuple
print(len(tup)) #returns the no of elements in tuple
print(tuple(li)) #converts list li to tuple
#Dictionary
#Dictionary is kind of hash table type whicl has key-value pairs
dict1={1:"apple",2:"orange"} #declaring dictionary with key:value pair, here key can be of numeral or string datatype
print(dict1)
print(dict1[2]) #getting the value of key 2
print(dict1.keys()) #extracting keys set from dictionary
print(dict1.values()) #extracting values set form dictionary
dict1[3]="grapes" #adding new key value pair
print(dict1)
#del dict1[3]
print(dict1[1])
print(len(dict1)) # returns the no of key-value pairs in dictionary dict1
print(str(dict1)) # displays dict1 in string representation
print(type(dict1)) # returns the type of dict1
dict2=dict1.copy() #copying dict1 to dict2
print(dict2)
dict3=dict.fromkeys(list3,"value") #converting list to dictionary with default value-"value"
print(dict3)
print(dict1.get(2)) #accessing value of key 2 in dictionary
print(dict1.get(4,"pears"))
print(dict1)
dic={4:"avacado"}
dict1.update(dic) #adding new key-value pair to existing dict1 by update() method
print(dict1)
| true
|
46d85c6a471072788ab8ec99470f0b27e9d1939d
|
cscosu/ctf0
|
/reversing/00-di-why/pw_man.py
| 1,614
| 4.125
| 4
|
#!/usr/bin/env python3
import sys
KEY = b'\x7b\x36\x14\xf6\xb3\x2a\x4d\x14\x19'
SECRET = b'\x13\x59\x7a\x93\xca\x49\x22\x79\x7b'
def authenticate(password):
'''
Authenticates the user by checking the given password
'''
# Convert to the proper data type
password = password.encode()
# We can't proceed if the password isn't even the correct length
if len(password) != len(SECRET):
return False
tmp = bytearray(len(SECRET))
for i in range(len(SECRET)):
tmp[i] = password[i] ^ KEY[i]
return tmp == SECRET
def get_pw_db(file_name):
'''
Constructs a password database from the given file
'''
pw_db = {}
with open(file_name) as f:
for line in f.readlines():
entry, pw = line.split('=', 1)
pw_db[entry.strip()] = pw.strip()
return pw_db
def main():
'''
Main entry point of the program. Handles I/O and contains the main loop
'''
print('Welcome to pw_man version 1.0')
password = input('password: ')
if not authenticate(password):
print('You are not authorized to use this program!')
sys.exit(1)
pw_db = get_pw_db(sys.argv[1])
print('Passwords loaded.')
while True:
print('Select the entry you would like to read:')
for entry in pw_db.keys():
print('--> {}'.format(entry))
selected = input('Your choice: ')
try:
print('password for {}: {}'.format(selected, pw_db[selected]))
except KeyError:
print('unrecognized selection: {}'.format(selected))
print('please')
if __name__ == '__main__':
main()
| true
|
438658b5f7165211e7ec5dec55b63097c5852ede
|
alshore/firstCapstone
|
/camel.py
| 527
| 4.125
| 4
|
#define main function
def main():
# get input from user
# set to title case and split into array
words = raw_input("Enter text to convert: ").title().split()
# initialize results variable
camel = ""
for word in words:
# first word all lower case
if word == words[0]:
word = word.lower()
# add word to results string
camel += word
else:
# all other words remain in title case and
# get added to the results string
camel += word
# print results to console
print camel
# call main function
main()
| true
|
33735735d54ebe3842fca2fa506277e2cd529734
|
georgemarshall180/Dev
|
/workspace/Python_Play/Shakes/words.py
| 1,074
| 4.28125
| 4
|
# Filename:
# Created by: George Marshall
# Created:
# Description: counts the most common words in shakespeares complete works.
import string
# start of main
def main():
fhand = open('shakes.txt') # open the file to analyzed.
counts = dict() # this is a dict to hold the words and the number of them.
for line in fhand:
line = line.translate(string.punctuation) #next lines strip extra stuff out and format properly.
line = line.lower()
line = line.replace('+',' ')
words = line.split()
for word in words: # counts the words.
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
# Sort the dictionary by value
lst = list()
for key, val in counts.items():
lst.append((val, key))
lst.sort(reverse=True) # sorts the list from Greatest to least.
# print the list out.
for key, val in lst[:100]:
print(key, val)
# runs this file if it is main
if __name__ == "__main__":
main()
| true
|
d85ef4cc9b3ec8018e4f060a1d5185782dcff088
|
vikasb7/DS-ALGO
|
/same tree.py
| 829
| 4.15625
| 4
|
'''
Vikas Bhat
Same Tree
Type: Tree
Time Complexity: O(n)
Space Complexity: O(1)
'''
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.left=left
self.right=right
self.val=val
class main:
#Recursive
def sameTree(self,root1,root2):
if root1 and not root2:
return False
if root2 and not root1:
return False
if not root1 and not root2:
return True
if root1.val!=root2.val:
return False
return self.sameTree(root1.left,root2.left) and self.sameTree(root1.right,root2.right)
if __name__=="__main__":
t1=TreeNode(1)
t1.left=TreeNode(2)
t1.right=TreeNode(3)
t2=TreeNode(1)
t2.left=TreeNode(2)
t2.right= TreeNode(3)
v=main()
print(v.sameTree(t1,t2))
| false
|
3623a3d7e5497f9e4ce80cf559e0fdfa085c109b
|
Mohith22/CryptoSystem
|
/key_est.py
| 1,438
| 4.15625
| 4
|
#Diffie Helman Key Exchange
#Author : Mohith Damarapati-BTech-3rd year-NIT Surat-Computer Science
#Establishment Of Key
#Functionalities :
#1. User can initiate communication through his private key to get secretly-shared-key
#2. User can get secretly shared-key through his private key
#For Simplicity Choose -
#Prime Modulus - 10007 & Generator - 293
import sys
def findv(gen,prime,pkey):
return pow(gen,pkey,prime)
print "Welcome!!! \n"
prime = raw_input("Enter Prime Modulus Value (Public) : ")
gen = raw_input("Enter Generator Value (Public) : ")
pkey = raw_input("Enter Your Private Key (Enter It Carefully): ")
print "\n"
while True:
print "Select Your Choice : \n"
print "1. Initiate Communication - Press 1"
print "2. Get Shared-Key - Press 2"
print "\n"
while True:
choice = raw_input("Enter Your Choice: ")
print "\n"
if choice=='1':
val = findv(int(gen),int(prime),int(pkey))
print "Value Sent Is : ",
print val
break
elif choice=='2':
valu = raw_input("Enter Value You Got From The Other Party : ")
skey = findv(int(valu),int(prime),int(pkey))
print "********Shared Key Is******** : ",
print skey,
print " Keep It Secured !!! ****"
break
else:
print "Enter Valid Choice"
print "\n\n"
print "Want to something else :"
print "Press 'y'"
print "Else to exit press any key"
ch = raw_input("Choice : ")
print "\n\n"
if ch!='y':
print "Program Exit ....."
break
| false
|
ddbedd13893047ab7611fe8d1b381575368680a6
|
ryanSoftwareEngineer/algorithms
|
/arrays and matrices/49_group_anagrams.py
| 1,408
| 4.15625
| 4
|
'''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically
using all the original letters exactly once.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
'''
def groupAnagrams( strs):
output = []
map = {}
map_i = 0
for i in strs:
b = i[:]
b= "".join(sorted(b))
if b in map:
output[map[b]].append(i)
else:
map[b] = map_i
output.append([i])
map_i += 1
return output
def attempttwo(strs):
# iterate through strs
# for every iteration of strs iterate through single string
# create array 0 to 26 to hold counts
# array of 26 from 0 to 26 represents count for each character
# convert to string of ints or tuple(array)
# use hash table to store string of counts
answer = {}
for word in strs:
alphabet = [0]*26
for char in word:
alphabet[ord(char.lower())-ord('a')] += 1
str_result = str(alphabet)
if str_result in answer:
answer[str_result].append(word)
else:
answer[str_result] = [word]
return list(answer.values())
strs = ["eat","tea","tan","ate","nat","bat"]
print(attempttwo(strs))
| true
|
57cd15146c5a663a0ccaa74d2187dce5c5dc6962
|
PabloLSalatic/Python-100-Days
|
/Days/Day 2/Q6.py
| 498
| 4.1875
| 4
|
print('------ Q 6 ------')
# ?Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
# ?Suppose the following input is supplied to the program:
# ?Hello world
# ?Practice makes perfect
# *Then, the output should be:
# *HELLO WORLD
# *PRACTICE MAKES PERFECT
lines = []
while True:
line = input('linea: ')
if line:
lines.append(line.upper())
else:
break
for line in lines:
print(line)
| true
|
7902ec6be552b5e44af3e0c73335acd52c7cb3e7
|
44858/lists
|
/Bubble Sort.py
| 609
| 4.28125
| 4
|
#Lewis Travers
#09/01/2015
#Bubble Sort
unsorted_list = ["a", "d", "c", "e", "b", "f", "h", "g"]
def bubble_sort(unsorted_list):
list_sorted = False
length = len(unsorted_list) - 1
while not list_sorted:
list_sorted = True
for num in range(length):
if unsorted_list[num] > unsorted_list[num+1]:
list_sorted = False
unsorted_list[num], unsorted_list[num+1] = unsorted_list[num+1], unsorted_list[num]
return unsorted_list
#main program
sorted_list = bubble_sort(unsorted_list)
print(sorted_list)
| true
|
90b59d5607388d4f18382624219a9fcfd7c9cf17
|
LorenzoY2J/py111
|
/Tasks/d0_stairway.py
| 675
| 4.3125
| 4
|
from typing import Union, Sequence
from itertools import islice
def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]:
"""
Calculate min cost of getting to the top of stairway if agent can go on next or through one step.
:param stairway: list of ints, where each int is a cost of appropriate step
:return: minimal cost of getting to the top
"""
prev_1, prev = stairway[0], stairway[1]
for cost in islice(stairway, 2, len(stairway)):
current = cost + min(prev_1, prev)
prev_1, prev = prev, current
return prev
if __name__ == '__main__':
stairway = [1, 3, 5, 1]
print(stairway_path(stairway))
| true
|
15242cc4f007545a85c3d7f65039678617051231
|
LorenzoY2J/py111
|
/Tasks/b1_binary_search.py
| 841
| 4.1875
| 4
|
from typing import Sequence, Optional
def binary_search(elem: int, arr: Sequence) -> Optional[int]:
"""
Performs binary search of given element inside of array
:param elem: element to be found
:param arr: array where element is to be found
:return: Index of element if it's presented in the arr, None otherwise
"""
first = 0
last = len(arr) - 1
while first <= last:
mid = (last + first) // 2
if elem == arr[mid]:
break
elif elem < arr[mid]:
last = mid - 1
else:
first = mid + 1
else:
return None
while mid > 0 and arr[mid - 1] == elem:
mid -= 1
return mid
def main():
elem = 10
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(elem, arr))
if __name__ == '__main__':
main()
| true
|
7941328e4cb2d286fefd935541e2dab8afde61c0
|
SACHSTech/ics2o1-livehack---2-Maximilian-Schwarzenberg
|
/problem2.py
| 771
| 4.59375
| 5
|
"""
-------------------------------------------------------------------------------
Name: problem2.py
Purpose: To check if the inputted sides form a triangle.
Author: Schwarenberg.M
Created: 23/02/2021
------------------------------------------------------------------------------
"""
# Welcome message
print("Welcome to the Triangle Checker")
print("---")
# Input triangle sides
side1 = int(input("Enter the length of the first side: "))
side2 = int(input("Enter the length of the second side: "))
side3 = int(input("Enter the length of the third side: "))
print("---")
# processing and output of data
if side1 + side2 >= side3 or side1 + side3 >= side2 or side3 + side2 >= side1:
print("The figure is a triangle.")
else:
print("The figure is NOT a triangle.")
| true
|
9b3495345e4f4ad9648dcca17a8288e62db1220e
|
sriniverve/Python_Learning
|
/venv/tests/conditions.py
| 271
| 4.21875
| 4
|
'''
This is to demonstrate the usage of conditional operators
'''
temperature = input('Enter the temperature:')
if int(temperature) > 30:
print('This is a hot day')
elif int(temperature) < 5:
print('This is a cold day')
else:
print('This is a pleasant day')
| true
|
1140a8dd58988892ecca96673ffe3d2c1bf44564
|
sriniverve/Python_Learning
|
/venv/tests/guessing_number.py
| 395
| 4.21875
| 4
|
'''
This is an example program for gussing a number using while loop
'''
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess_number = int(input('Guess a number: '))
guess_count += 1
if guess_number == secret_number:
print('You guessed it right. You Win!!!')
break
else:
print('You are have exhausted your options. Sorry!!!')
| true
|
01b3319010f240b6ddfdd0b5ae3e07f201a9a046
|
sriniverve/Python_Learning
|
/venv/tests/kg2lb_converter.py
| 285
| 4.21875
| 4
|
'''
This program is to take input in KGs & display the weight in pounds
'''
weight_kg = input('Enter your weight in Kilograms:') #prompt user input
weight_lb = 2.2 * float(weight_kg) #1 kg is 2.2 pounds
print('You weight is '+str(weight_lb)+' pounds')
| true
|
23d110cff79eb57616586da7f78c7ac6d4e7a957
|
vmmc2/Competitive-Programming
|
/Sets.py
| 1,369
| 4.4375
| 4
|
#set is like a list but it removes repeated values
#1) Initializing: To create a set, we use the set function: set()
x = set([1,2,3,4,5])
z = {1,2,3}
#To create an empty set we use the following:
y = set()
#2) Adding a value to a set
x.add(3)
#The add function just works when we are inserting just 1 element into our set
#3) Adding more than one element to a set
x.update([34,45,56])
#To do this, we use the update function.
#We can also pass another set to the update function
y = {1,2,3}
a = {4,5,6}
y.update(a, [34,45,56])
#4) Removing a specific value from a set
#We can use two different functions to do this same action: remove() and discard()
a.remove(1) or a.discard(1)
#The problem with remove() is that if we are trying to remove a value that doesn`t exist in the set, we are going to get a key error.
#On the other hand, if we try to discard a value that doesn`t exist, then we don`t get any type of error. In other words, it works just fine.
So, ALWAYS use the discard() method.
s1 = {1,2,3}
s2 = {2,3,4}
s3 = {3,4,5}
#5) Intersection Method
s4 = s1.intersection(s2) # s4 = {2,3}
s4 = s1.intersection(s2, s3) # s4 = {3}
#6) Difference Method
s4 = s1.difference(s2) # s4 = {1}
s4 = s2.difference(s1) # s4 = {4}
#OBSERVATION: We can pass multiple sets as arguments to these different methods.
#7) Sym Difference
s4 = s1.symmetric_difference(s2)
| true
|
768ce4a45879ad23c94de8d37f33f7c8c50dca24
|
AmangeldiK/lesson3
|
/kall.py
| 795
| 4.1875
| 4
|
active = True
while active:
num1 = int(input('Enter first number: '))
oper = input('Enter operations: ')
num2 = int(input('Enter second number: '))
#dict_ = {'+': 'num1 + num2', '-': 'num1 - num2', '*': 'num1 * num2', '/': 'num1 / num2'}
if oper == '+':
print(num1+num2)
elif oper == '-':
print(num1-num2)
else:
if oper == '*':
print(num1*num2)
elif oper == '/':
try:
num1 / num2 == 0
except ZeroDivisionError:
print('Division by zero is forbidden!')
else:
print(num1/num2)
else:
print('Wrong operations')
continue_ = input('If you want continue click any button and Enter, if not click to Enter: ')
| true
|
230616616f10a6207b4a407b768afaabb846528a
|
SynthetiCode/EasyGames-Python
|
/guessGame.py
| 744
| 4.125
| 4
|
#This is a "Guess the number game"
import random
print('Hello. What is your nombre?')
nombre = input()
print('Well, ' + nombre + ', I am thining of a numero between Uno(1) y Veinte(20)')
secretNumber =random.randint(1,20)
#ask player 6 times
for guessesTaken in range(0, 6):
print ('Take a guess:' )
guess = int(input())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # <-- This condition is the correct guess!
if guess ==secretNumber:
print ('Good job, ' + nombre + '! You guessed my number in ' + str(guessesTaken+1)+ ' guesses!')
else:
print ('Nope, the number I was thinking of was: ' + str(secretNumber))
print ('Better luck next time')
| true
|
fb038cc7201cd3302a5eeedf9fd86511d6ff2cf6
|
mdanassid2254/pythonTT
|
/constrector/hashing.py
| 422
| 4.65625
| 5
|
# Python 3 code to demonstrate
# working of hash()
# initializing objects
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56
# Printing the hash values.
# Notice Integer value doesn't change
# You'l have answer later in article.
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))
| true
|
0e6b136b69f36b75e8088756712889eb45f1d24a
|
Kaden-A/GameDesign2021
|
/VarAndStrings.py
| 882
| 4.375
| 4
|
#Kaden Alibhai 6/7/21
#We are learning how to work with strings
#While loop
#Different type of var
num1=19
num2=3.5
num3=0x2342FABCDEBDA
#How to know what type of date is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase="Hello there!"
print(type(phrase))
#String functions
num=len(phrase)
print(phrase[3:7]) #from 3 to 6
print(phrase[6:]) #from index to the end
print(phrase*2) #print it twice
#concadentation --> joining strings
phrase = phrase + "Goodbye"
print(phrase)
print(phrase[2:num-1])
while "there" in phrase:
print("there" in phrase)
phrase="changed"
print(phrase)
# make 3 string variables print them individually
#"print s1+s2"
#print st2+st3
#print st1+st2+st3
phrase1="Lebron"
phrase2=">"
phrase3="MJ"
print(phrase1)
print(phrase2)
print(phrase3)
print(phrase1+phrase2)
print(phrase2+phrase3)
print(phrase1+ " ", phrase2+ " ",phrase3)
| true
|
f7aac03275b43a35f790d9698b94e76f93207e7d
|
abokareem/LuhnAlgorithm
|
/luhnalgo.py
| 1,758
| 4.21875
| 4
|
"""
------------------------------------------
|Luhn Algorithm by Brian Oliver, 07/15/19 |
------------------------------------------
The Luhn Algorithm is commonly used to verify credit card numbers, IMEI numbers, etc...
Luhn makes it possible to check numbers (credit card, SIRET, etc.) via a control key (called checksum, it is a number
of the number which makes it possible to check the others). If a character is incorrect, then Luhn's algorithm will
detect the error.
Starting with the right-most digit, double every other digit to the left of it. Then all of the undoubled and doubled
digits together. If the total is a multiple of 10, then the number passes the Luhn Algorithm.
For Luhn to be true:
(double digits + undoubled digits) % 10 == 0
========================================================================================================================
"""
def luhn_algorithm_test(number):
digit_list = list(map(int, str(number)))
luhn_digits = []
total = 0
for digit in digit_list[-2::-2]:
double_digit = digit * 2
if double_digit >= 10:
double_digit = double_digit - 9
luhn_digits.append(double_digit)
digit_list.remove(digit)
total = sum(digit_list) + sum(luhn_digits)
if total % 10 == 0:
return "Luhn Algorithm Test Passed"
else:
return "Luhn Algorithm Test Failed"
def main():
while True:
try:
number = int(input("Please enter a number: "))
print(luhn_algorithm_test(number))
except ValueError:
print("Sorry, please input numbers only.")
continue
else:
break
if __name__ == '__main__':
main()
| true
|
a0d900a3e43322ab1e994aa82f74a5d759e8260a
|
AlSavva/Python-basics-homework
|
/homework3-4.py
| 2,163
| 4.21875
| 4
|
# Программа принимает действительное положительное число x и целое
# отрицательное число y. Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y). При
# решении задания необходимо обойтись без встроенной функции возведения числа
# в степень.
# Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в
# степень с помощью оператора **. Второй — более сложная реализация без
# оператора **, предусматривающая использование цикла.
def my_pow(x, y):
"""Function implementing the operation of raising to a negative exponent
This function takes a real positive number and a negative integer
as arguments.
x: float, y: int, and y < 0
"""
if int(y) >= 0:
return 'Error! y argument cannot be greater than zero'
try:
x != 0
return 1 / x ** -y
except ZeroDivisionError:
return 'Error! x argument cannot be zero'
# Вариант без использования встроенной функции возведения в степень
def my_2pow(x, y):
"""Function implementing the operation of raising to a negative exponent,
but does not use the exponentiation operation
This function takes a real positive number and a negative integer
as arguments.
x: float, y: int, and y < 0
"""
if int(y) >= 0:
return 'Error! y argument cannot be greater than zero'
try:
x != 0
res = 1
count = 0
while count != -y:
count += 1
res *= 1 / x
return res
except ZeroDivisionError:
return 'Error! x argument cannot be zero'
print(my_pow(2, -2))
print(my_2pow(2, -2))
| false
|
a8051d4c26e31ecb5a315948a9e3bdad44975aec
|
catdog001/leetcode_python
|
/Tree/leetcode_tree/easy/226.py
| 1,546
| 4.15625
| 4
|
"""
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
def revert(root):
if not root:
return root
root.left, root.right = revert(root.right), revert(root.left)
return root
new_root = revert(root)
return new_root
def create_tree(self):
# A、L、B、E、 C、D、W、X
A = TreeNode("A")
L = TreeNode("L")
B = TreeNode("B")
E = TreeNode("E")
C = TreeNode("C")
D = TreeNode("D")
W = TreeNode("W")
X = TreeNode("X")
A.left = L
A.right = C
L.left = B
L.right = E
C.right = D
D.left = W
W.right = X
return A
if __name__ == '__main__':
solution = Solution()
root = solution.create_tree()
# 翻转一棵树
invertTree = solution.invertTree(root)
print("该树翻转后的树是{}".format(invertTree))
| false
|
f4e4beb1d2975fd523ca7dd744aa7a96e686373a
|
WeiyiDeng/hpsc_LinuxVM
|
/lecture7/debugtry.py
| 578
| 4.15625
| 4
|
x = 3
y = 22
def ff(z):
x = z+3 # x here is local variable in the func
print("+++ in func ff, x = %s; y = %s; z = %s") %(x,y,z)
return(x) # does not change the value of x in the main program
# to avoid confusion, use a different symbol (eg. u) instead of x in the function
print("+++ before excuting ff, x = %s; y = %s") %(x,y)
y = ff(x)
print("+++ after excuting ff, x = %s; y = %s") %(x,y)
# in ipython>>> run debugtry.py
# outputs:
# before ff: x = 3, y = 22
# within ff: z = 3, x = 6, y = 22
# after ff: x = 3, y = 6
| true
|
6f6a83c6661a2d80a173c1e8b069004e7e8ca744
|
MisterHat-89/geekBrainsPython
|
/Lesson_5/exam_2.py
| 577
| 4.21875
| 4
|
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк,
# выполнить подсчет количества строк, количества слов в каждой строке.
text = ""
f_file = open(r'dz2.txt', 'r')
print(f_file.read())
print("")
count_words = 0
lines = 0
f_file.seek(0)
for line in f_file.readlines():
lines += 1
count_words = len(line.split(" "))
print(f"В строке {lines} - {count_words} слов")
f_file.close()
print(f"Строк {lines}")
| false
|
f91c87f85bb2a97e6dea6d3e0d622ad4b003e239
|
rasooll/Python-Learning
|
/azmoon4/part2.py
| 364
| 4.34375
| 4
|
def find_longest_word(input_string):
maxlen = 0
maxword = ""
input_list = input_string.split()
#print (input_list)
for word in input_list:
#print (len(word))
if len(word) >= maxlen:
maxlen = len(word)
maxword = word
#print (maxlen, maxword)
return maxword
print (find_longest_word("salam in ye matn azmayeshi baraye test matnibebozorgiein ast"))
| false
|
1269f7390bfc63e8962b3bda78a114500e5f03fa
|
Nilesh2000/CollegeRecordWork
|
/Semester 2/Ex12d.py
| 1,087
| 4.25
| 4
|
myDict1 = {'Name':'Nilesh', 'RollNo':69, 'Dept':'IT', 'Age':18}
#print dictionary
print("\nDictionary elements : ", myDict1)
#Printing Values by passing keys
print("Student department : ", myDict1['Dept'])
#Editing dictionary elements
myDict1['Dept']="CSE"
print("After Editing dictionary elements : " , myDict1)
#Adding a element
myDict1['College'] = 'SVCE'
print("After appending : ", myDict1)
#Number of dictionary elements
print("Number of dictionary elements : ", len(myDict1))
#string representation of the dictionary
print("String representation : ", str(myDict1))
#Returning correseponding value of the passed key
print("College is : ", myDict1.get('College'))
#List of keys
print("The keys in the dictionary are : ", myDict1.keys())
#List of values
print("The values in the dictionary are : ", myDict1.values())
#deleting dictionary elements
del myDict1['RollNo']
print("Dictionary after deleting key RollNo : ", myDict1)
#Deleting using pop()
myDict1.pop('Age')
print("Dictionary after popping key Age is : ", myDict1)
#Deleting complete dictionary
myDict1.clear()
| false
|
f0778146abc57271d1587461b9893289fd65dc86
|
bedoyama/python-crash-course
|
/basics/ch4__WORKING_WITH_LISTS/2_first_numbers.py
| 358
| 4.375
| 4
|
print("range(1,5)")
for value in range(1, 5):
print(value)
print("range(0,7)")
for value in range(0, 7):
print(value)
print("range(7)")
for value in range(7):
print(value)
print("range(3,7)")
for value in range(3, 7):
print(value)
print("range(-1,2)")
for value in range(-1, 2):
print(value)
numbers = list(range(4))
print(numbers)
| true
|
8b8e3c886a6d3acf6a0c7718919c56f354c3c912
|
bedoyama/python-crash-course
|
/basics/ch5__IF_STATEMENTS/3_age.py
| 338
| 4.15625
| 4
|
age = 42
if age >= 40 and age <= 46:
print('Age is in range')
if (age >= 40) and (age <= 46):
print('Age is in range')
if age < 40 or age > 46:
print('Age is older or younger')
age = 39
if age < 40 or age > 46:
print('Age is older or younger')
age = 56
if age < 40 or age > 46:
print('Age is older or younger')
| true
|
2b03e816c33cfdcfd9b5167de46fda66c7dda199
|
angelavuong/python_exercises
|
/coding_challenges/grading_students.py
| 981
| 4.125
| 4
|
'''
Name: Grading Students
Task:
- If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5.
- If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.
Example:
grade = 84 will be rounded to 85
grade = 29 will not be rounded because it is less than 40
'''
#!/bin/python3
import sys
def solve(grades):
# Complete this function
new_list = []
for each in grades:
if (each < 38):
pass
else:
if (each%5 >= 3):
remainder = 5 - (each%5)
each = remainder + each
elif(each%5 == 0):
pass
else:
pass
new_list.append(each)
return new_list
n = int(input().strip())
grades = []
grades_i = 0
for grades_i in range(n):
grades_t = int(input().strip())
grades.append(grades_t)
result = solve(grades)
print ("\n".join(map(str, result)))
| true
|
570b9f3e710d94baf3f4db276201a9c484da4a71
|
angelavuong/python_exercises
|
/coding_challenges/count_strings.py
| 573
| 4.125
| 4
|
'''
Name: Count Sub-Strings
Task:
Given a string, S, and a substring - count the number of times the substring appears.
Sample Input:
ABCDCDC
CDC
Sample Output:
2
'''
def count_substring(string,sub_string):
counter = 0
length = len(sub_string)
for i in range(len(string)):
if (string[i] == sub_string[0]):
if (string[i:(i+length)] == sub_string):
counter += 1
else:
pass
return counter
string = input().strip()
sub_string = input().strip()
count = count_substring(string,sub_string)
print(count)
| true
|
aa378a188bce0e97a0545221e65f148838b3650c
|
angelavuong/python_exercises
|
/coding_challenges/whats_your_name.py
| 536
| 4.1875
| 4
|
'''
Name: What's Your Name?
Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following:
Hello <firstname> <lastname>! You just delved into python.
Sample Input:
Guido
Rossum
Sample Output:
Hello Guido Rossum! You just delved into python.
'''
def print_full_name(a, b):
print("Hello " + a + " " + b + "! You just delved into python.")
if __name__ == '__main__':
first_name = raw_input()
last_name = raw_input()
print_full_name(first_name, last_name)
| true
|
d5d229788bf6391a3be21f75c54166a1b836b3e4
|
6reg/pc_func_fun
|
/rev_and_normalized.py
| 519
| 4.15625
| 4
|
def reverse_string(s):
reversed = ""
for i in s:
reversed = i + reversed
return reversed
def normalize(s):
normalized = ""
for ch in s:
if ch.isalpha():
normalized += ch.lower()
return normalized
def is_palindrome(s):
normalized = normalize(s)
rev = reverse_string(normalized)
return normalized == rev
print(is_palindrome("Hello"))
print(is_palindrome("A man, a plan, a canal - Panama!"))
print(is_palindrome("kayak"))
print(is_palindrome("Goodbye"))
| true
|
cd916150b60d80e1def43eb10aaafd65429badb1
|
lumeng/repogit-mengapps
|
/data_mining/wordcount.py
| 2,121
| 4.34375
| 4
|
#!/usr/bin/python -tt
## Summary: count words in a text file
import sys
import re # for normalizing words
def normalize_word(word):
word_normalized = word.strip().lower()
match = re.search(r'\W*(\w+|\w\W+\w)\W*', word_normalized)
if match:
return match.group(1)
else:
return word_normalized
def count_word_in_file(filename):
#my_file = open(filename, 'rU', 'utf-8')
my_file = open(filename, 'rU')
word_dict = {}
for line in my_file:
words = line.split()
for w in words:
# mengToDo: improve word normalization logic
# What Google's n-gram data set uses?
w_normalized = normalize_word(w)
if w_normalized in word_dict:
word_dict[w_normalized] += 1
else:
word_dict[w_normalized] = 1
return word_dict
def print_word_count(filename):
"""counts how often each word appears in the text and prints:
word1 count1
word2 count2
...
in order sorted by word. 'Foo' and 'foo' count as the same word
"""
word_count_dict = sorted(count_word_in_file(filename).items())
for word, count in word_count_dict:
print word, count
return word_count_dict
def get_count(word_count_tup):
return word_count_tup[1]
def print_top_words(filename, size=50):
"""prints just the top 20 most common words sorted by sizeber of occurrences of each word such
that the most common word is first."""
word_count_dict = count_word_in_file(filename)
sorted_word_count_dict = sorted(word_count_dict.items(), key=get_count, reverse=True)
for word, count in sorted_word_count_dict[:size]:
print word, count
###
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topwords} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_word_count(filename)
elif option == '--topwords':
print_top_words(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
# END
| true
|
516721a52862c9532385d52da79d11085a759181
|
EvgenyMinikh/Stepik-Course-431
|
/task17.py
| 1,250
| 4.1875
| 4
|
"""
Напишите программу, которая шифрует текст шифром Цезаря.
Используемый алфавит − пробел и малые символы латинского алфавита: ' abcdefghijklmnopqrstuvwxyz'
Формат ввода:
На первой строке указывается используемый сдвиг шифрования: целое число. Положительное число соответствует сдвигу вправо. На второй строке указывается непустая фраза для шифрования. Ведущие и завершающие пробелы не учитывать.
Формат вывода:
Единственная строка, в которой записана фраза: Result: "..." , где вместо многоточия внутри кавычек записана зашифрованная последовательность.
"""
alphabet = ' abcdefghijklmnopqrstuvwxyz'
shift = int(input())
source_string = input().strip()
print('Result: "', end='')
for letter in source_string:
position = alphabet.find(letter)
new_position = (position + shift) % 27
print(alphabet[new_position], end='')
print('"', end='')
| false
|
f65486941b6ee5852a4aaf2bf6547b7d5d863dd9
|
blei7/Software_Testing_Python
|
/mlist/binary_search.py
| 1,682
| 4.3125
| 4
|
# binary_search.py
def binary_search(x, lst):
'''
Usage: The function applies the generic binary search algorithm to search if the value
x exists in the lst, and returns a list contains: TRUE/FAlSE depends on whether the x value has been found,
x value, and x position indice in list
Argument:
x: numeric
lst: sorted list of numerics
Return:
a list contains:
- first element is a logical value (TRUE/FALSE)
- second element is a numeric value of x
- third element is a numeric in range of 0 to length(list) where 0 indicates the element is not in the list
Examples:
binary_search(4, [1,2,3,4,5,6])
>>> [TRUE,4,3]
binary_search(5, [10,100,200,300])
>>> [FALSE,5,0]
'''
# Raise error if input not a list
if type(lst) != list:
raise TypeError("Input must be a list")
# Raise error if input is not integer (eg. float, string...)
for i in lst:
if type(i) != int:
raise TypeError("Input must be list of intergers")
# Raise error if input values less than 1000
if max(lst) >= 1000:
raise ValueError("Input values exceed 1000. Please limit range of input values to less than 1000.")
#binary search algorithm
#empty list
if len(lst) == 0:
return [False, x, 0]
low = 0
high = len(lst)-1
while low <= high:
mid = (low + high) //2
if lst[mid] < x:
low = mid + 1
elif x < lst[mid]:
high = mid - 1
else:
return [True, x, mid]
return [False, x, 0]
| true
|
612c8ca841d8da2fc2e8e00f1a14fb22126d1277
|
sumanmukherjee03/practice-and-katas
|
/python/top-50-interview-questions/ways-to-climb-stairs/main.py
| 2,336
| 4.1875
| 4
|
# Problem : Given a staircase of n steps and a set of possible steps that we can climb at a time
# named possibleSteps, create a function that returns the number of ways a person can take to reach the
# top of the staircase.
# Ex : Input : n = 5, possibleSteps = {1,2}
# Output : 8
# Explanation : Possible ways are - 11111, 1112, 1121, 1211, 2111, 122, 212, 221
# Think recursively with a few examples and see if there is any pattern to the solution
# When n=0 , possibleSteps = {1,2} - Output = 1
# When n = 1, possibleSteps = {1,2} - Output = 1
# When n = 2, possibleSteps = {1,2} - Output = 2
# When n = 3, possibleSteps = {1,2} - Output = 3
# When n = 4, possibleSteps = {1,2} - Output = 5
# When n = 5, possibleSteps = {1,2} - Output = 8
# The output is a fibonacci sequence : 1,1,2,3,5,8
# The recursive relation here is f(n) = f(n-1) + f(n-2)
#
# This is because to climb any set of steps n, if the solution is f(n),
# then we can find f(n) by finding the solution to climb n-1 steps + 1 step OR n-2 steps and 2 steps,
# ie to reach the top we must be either 1 step away from it or 2 steps away from it.
# That's why f(n) = f(n-1) + f(n-2)
#
# Similarly when possibleSteps = {2,3,4}, then to reach any step n, we must be either 2 steps
# away from it or 3 steps away from it or 4 steps away from it.
# f(n) = f(n-2) + f(n-3) + f(n-4)
# If the set of possibleSteps is of length m, then the time complexity is O(m^n)
# This can be improved with dynamic programing
def waysToClimb01(n, possibleSteps):
if n == 0:
return 1
noWays = 0
for steps in possibleSteps:
if n-steps > 0:
noWays += waysToClimb01(n-steps, possibleSteps)
return noWays
# With dynamic programming consider an array that holds the number of ways to climb n steps.
# So, for possibleSteps = {2,3,4}
# arr[i] = arr[i-2] + arr[i-3] + arr[i-4]
#
# arr = 1 0 1 1 2 2 4 5
# n=0 n=1 n=2 n=3 n=4 n=5 n=6 n=7
def waysToClimb02(n, possibleSteps):
arr = [0] * (n+1) # n+1 because to consider n steps we need to also consider the 0th step
arr[0] = 1
for i in range(1,n+1):
for j in possibleSteps:
if i-j >= 0:
arr[i] += arr[i-j]
return arr[n]
| true
|
2137855080a086d767c6c1c750a92e2c50e47f5a
|
sumanmukherjee03/practice-and-katas
|
/python/top-50-interview-questions/sort/main.py
| 1,234
| 4.28125
| 4
|
# Problem : Sort an array
# Time complexity O(n^2)
def bubbleSort(arr):
if len(arr) <= 1:
return arr
# Run an outer loop len(arr) times
i = 0
while i < len(arr):
# Keep swapping adjacent elements, ie sort adjacent elements in the inner loop
j = 1
while j < len(arr):
if arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
j += 1
i += 1
return arr
# Time complexity of merge sort is O(nlogn)
def mergeSort(arr):
if len(arr) <= 1:
return arr
def merge(left, right):
if len(left) == 0:
return right
if len(right) == 0:
return left
res = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
if i < len(left):
res = res + left[i:len(left)]
if j < len(right):
res = res + right[j:len(right)]
return res
mid = len(arr)//2
l = mergeSort(arr[0:mid])
r = mergeSort(arr[mid:len(arr)])
return merge(l, r)
| false
|
f69d4a3a4e1abadb5d462889976fcaffafbdc9f8
|
ChrisStreadbeck/Python
|
/apps/fizzbuzz.py
| 705
| 4.1875
| 4
|
var_range = int(input("Enter a Number to set the upper range: "))
def fizzbuzz(upper):
for num in range(1, upper):
if num != upper:
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz')
elif num % 3 == 0:
print('Fizz')
elif num % 5 == 0:
print('Buzz')
else:
print(num)
fizzbuzz(upper = var_range + 1)
# ----------------------
#without input
def fizzbuzz(upper):
for num in range(1, upper):
if num != upper + 1:
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz')
elif num % 3 == 0:
print('Fizz')
elif num % 5 == 0:
print('Buzz')
else:
print(num)
fizzbuzz(100)
| false
|
14adf897de38f2d27bc32c8bc7d298b9f1ffbbed
|
ChrisStreadbeck/Python
|
/learning_notes/lambdas.py
| 440
| 4.1875
| 4
|
#Lambda is a tool used to wrap up a smaller function and pass it to other functions
full_name = lambda first, last: f'{first} {last}'
def greeting(name):
print(f'Hi there {name}')
greeting(full_name('kristine', 'hudgens'))
#so it's basically a short hand function (inline) and it allows the name to be called
# simply later on in the second function.
#Can be used with any type of code, but it's most commonly used for mathmatics
| true
|
f91112d5f2d441cb357b52d77aa72c74d586fc73
|
Shady-Data/05-Python-Programming
|
/studentCode/Recursion/recursive_lines.py
| 928
| 4.53125
| 5
|
'''
3. Recursive Lines
Write a recursive function that accepts an integer argument, n. The function should display
n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line
showing 2 asterisks, up to the nth line which shows n asterisks.
'''
def main():
# Get an intger for the number of lines to print
num_lines = int(input('Enter the number of lines to print: '))
# call the recursive_lines function with the start of 1 and end of num_lines
recursive_lines('*', num_lines)
# define the recursive_lines function
# parameters: str pat, int num_lines
def recursive_lines(p_pat, p_stop):
# base case if len(p_pat) == p_stop
if len(p_pat) == p_stop:
print(p_pat)
else:
# print the pattern and return recursive lines p_pat + '*', p_stop
print(p_pat)
return recursive_lines(p_pat + '*', p_stop)
# Call the main function
main()
| true
|
630e3b1afa907f03d601774fa4aec19c8ae1fbbb
|
Shady-Data/05-Python-Programming
|
/studentCode/cashregister.py
| 1,718
| 4.3125
| 4
|
'''
Demonstrate the CashRegister class in a program that allows the user to select several
items for purchase. When the user is ready to check out, the program should display a list
of all the items he or she has selected for purchase, as well as the total price.
'''
# import the cash register and retail item class modules
import CashRegisterClass
import RetailItemClass as ri
from random import randint
# generate a list of retail item to test with
items = {
'Jacket': {'desc': 'Jacket', 'units' : 12, 'price' : 59.95},
'Designer Jeans': {'desc': 'Designer Jeans', 'units' : 40, 'price' : 34.95},
'Shirt': {'desc': 'Shirt', 'units' : 20, 'price' : 24.95}
}
# Create and empty list to store the items
retail_items = []
# generate an object for each entry
for key in items.keys():
# add the object to the list
retail_items.append(ri.RetailItem(items[key]['desc'], items[key]['units'], items[key]['price']))
def main():
# Instanstiate a Class Register object
register = CashRegisterClass.CashRegister()
# add an item to the cash register
register.purchase_item(retail_items[randint(0, 2)])
# display the items in the register
# register.show_items()
# add 5 more items to the register
for x in range(5):
register.purchase_item(retail_items[randint(0, 2)])
print('Show items before clear:')
# Display the details of the items purchased
register.show_items()
# display the total of the items
print(f'\n\tTotal: ${register.get_total():,.2f}')
# clear the register
register.clear()
print('\nShow Items after clear:')
# display the items in the register
register.show_items()
# call the main function
main()
| true
|
443db5f0cfbc98abc074444ad8fccdf4a891491c
|
Shady-Data/05-Python-Programming
|
/studentCode/CellPhone.py
| 2,681
| 4.53125
| 5
|
"""
Wireless Solutions, Inc. is a business that sells cell phones and wireless service.
You are a programmer in the company’s IT department, and your team is designing a program to manage
all of the cell phones that are in inventory. You have been asked to design a class that represents
a cell phone. The data that should be kept as attributes in the class are as follows:
• The name of the phone’s manufacturer will be assigned to the __manufact attribute.
• The phone’s model number will be assigned to the __model attribute.
• The phone’s retail price will be assigned to the __retail_price attribute.
The class will also have the following methods:
• An __init__ method that accepts arguments for the manufacturer, model number,
and retail price.
• A set_manufact method that accepts an argument for the manufacturer. This
method will allow us to change the value of the __manufact attribute after the object has been created, if necessary.
• A set_model method that accepts an argument for the model. This method will allow
us to change the value of the __model attribute after the object has been created, if
necessary.
• A set_retail_price method that accepts an argument for the retail price. This
method will allow us to change the value of the __retail_price attribute after the
object has been created, if necessary.
• A get_manufact method that returns the phone’s manufacturer.
• A get_model method that returns the phone’s model number.
• A get_retail_price method that returns the phone’s retail price.
"""
class CellPhone:
# define the __init__ method with 3 attributes
def __init__(self, p_manufacturer, p_model, p_msrp):
self.__manufact = p_manufacturer
self.__model = p_model
self.__retail_price = p_msrp
# define set_manufact to modify the __manufact attribute, if necessary
def set_manufact(self, p_manufact):
self.__manufact = p_manufact
# define set_model to modify the __model attribute, if necessary
def set_model(self, p_model):
self.__model = p_model
# define set_retail_price to modify the __retail_price attribute, if necessary
def set_retail_price(self, p_msrp):
self.__retail_price = p_msrp
# define get_manufact to return the __manufact attribute
def get_manufact(self):
return self.__manufact
# define get_model to return the __model attribute
def get_model(self):
return self.__model
# define get_retail_price to return the __retail_price attribute
def get_retail_price(self):
return self.__retail_price
| true
|
915a6111d78d3bd0566d040f9342ddb59239c467
|
Shady-Data/05-Python-Programming
|
/studentCode/Recursion/recursive_printing.py
| 704
| 4.46875
| 4
|
'''
1. Recursive Printing
Design a recursive function that accepts an integer argument, n, and prints the numbers 1
up through n.
'''
def main():
# Get an integer to print numbers up to
stop_num = int(input('At what number do you want this program to stop at: '))
# call the recursive print number and pass the stop number
recursive_print(1, stop_num)
# define the recursive_print function the start parameter the stop parameter
def recursive_print(p_start, p_stop):
# base case, print 1
if p_start == p_stop:
print(p_stop)
# recursive case
else:
print(p_start)
return recursive_print(p_start + 1, p_stop)
# call the main function
main()
| true
|
c4d39fadba7f479ce554198cd60c7ce4574c2d6b
|
Shady-Data/05-Python-Programming
|
/studentCode/Recursion/sum_of_numbers.py
| 874
| 4.40625
| 4
|
'''
6. Sum of Numbers
Design a function that accepts an integer argument and returns the sum of all the integers from 1 up
to the number passed as an argument. For example, if 50 is passed as an argument, the function will
return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate the sum.
'''
def main():
# get the stop number
stop_num = int(input('Enter the number to stop at: '))
# print the return of the sum_of_nums function with stop_num as an argument
print(sum_of_nums(stop_num))
# Debug check print sum of ints in range + 1
# print(sum([x for x in range(stop_num + 1)]))
# Define sum_of_nums() function
# parameters: p_stop
def sum_of_nums(p_stop):
# base case:
if p_stop == 0:
return 0
# recursive case:
else:
return p_stop + sum_of_nums(p_stop - 1)
# Call the main function
main()
| true
|
96387763eafc4c2ee210c866e43f30ebd9fbb6b5
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_4/14_pattern.py
| 264
| 4.25
| 4
|
#Write a program that uses nested loops to draw this pattern:
##
# #
# #
# #
# #
number = int(input("Enter a number : "))
for r in range (number):
print("#", end="",sep="")
for c in range (r):
print(" ", end="",sep="")
print("#",sep="")
| true
|
d4420e85272e424bdf66086eda6912615d805096
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_3/09_wheel_color.py
| 1,617
| 4.4375
| 4
|
#On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are
#as follows:
#• Pocket 0 is green.
#• For pockets 1 through 10, the odd-numbered pockets are red and the even-numbered
#pockets are black.
#• For pockets 11 through 18, the odd-numbered pockets are black and the even-numbered
#pockets are red.
#• For pockets 19 through 28, the odd-numbered pockets are red and the even-numbered
#pockets are black.
#• For pockets 29 through 36, the odd-numbered pockets are black and the even-numbered
#pockets are red.
#Write a program that asks the user to enter a pocket number and displays whether the
#pocket is green, red, or black. The program should display an error message if the user
#enters a number that is outside the range of 0 through 36.
number = int(input("enter a number : "))
if number >= 0 and number <= 36:
print("number is in range")
else:
print("out of range")
if number == 0:
print("green")
if number >= 1 and number < 10:
if number % 2 == 0 :
print("odd-numbered pockets are red")
else:
print("even-numbered pockets are black")
if number >= 11 and number <= 18:
if number % 2 == 0 :
print("even-numbered pockets are red")
else:
print("odd-numbered pockets are black")
if number >= 19 and number <= 28:
if number % 2 == 0 :
print("even-numbered pockets are black.")
else:
print("odd-numbered pockets are red")
if number >= 29 and number <= 36:
if number % 2 == 0:
print("even-numbered pockets are red")
else:
print("odd-numbered pockets are black")
| true
|
6411437fe4e73b46d8756a61d44f929a83c8dbf7
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_6/03_line_numbers.py
| 386
| 4.34375
| 4
|
#Write a program that asks the user for the name of a file. The program should display the
#contents of the file with each line preceded with a line number followed by a colon. The
#line numbering should start at 1.
count = 0
file = str(input("enter file name :"))
print("file name is :", file)
content = open(file, 'r')
for i in range(0, 10):
i += count + 1
print(f"{i} :",i)
| true
|
b09e8d2cd18d517e904889ecf2809f1f1392e7eb
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_4/12_population.py
| 1,321
| 4.71875
| 5
|
#Write a program that predicts the approximate size of a population of organisms. The
#application should use text boxes to allow the user to enter the starting number of organisms,
#the average daily population increase(as a percentage), and the number of days the
#organisms will be left to multiply. For example, assume the user enters the following values:
#Starting number of organisms: 2
#Average daily increase: 30%
#Number of days to multiply: 10
#The program should display the following table of data:
#Day Approximate Population
#1 2
#2 2.6
#3 3.38
#4 4.394
#5 5.7122
#6 7.42586
#7 9.653619
#8 12.5497
#9 16.31462
#10 21.209
size = 0
Starting_number_of_organisms = int(input("Starting_number_of_organisms : "))
daily_increase = int(input("daily increase : "))
Average_daily_increase = daily_increase / 100
print("Average daily increase :",Average_daily_increase)
number_of_days_to_multiply = int(input("number_of_days_to_multiply : "))
print("Day Approximate Population :")
for number_of_days_to_multiply in range (1,number_of_days_to_multiply + 1):
Starting_number_of_organisms = (Starting_number_of_organisms * Average_daily_increase) + Starting_number_of_organisms
print(f"{number_of_days_to_multiply} {Starting_number_of_organisms}")
| true
|
f5a8090ff67003d79e2f431256d4b277381c8dd7
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_3/01_Day.py
| 757
| 4.40625
| 4
|
#Write a program that asks the user for a number in the range of 1 through 7. The program
#should display the corresponding day of the week, where 1 = Monday, 2 = Tuesday,
#3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, and 7 = Sunday. The program should
#display an error message if the user enters a number that is outside the range of 1 through 7.
days_number = int(input("Enter a number : "))
if days_number == 1 :
print("monday")
elif days_number == 2 :
print("tuesday")
elif days_number == 3 :
print("wednesday")
elif days_number == 4 :
print("thursday")
elif days_number == 5 :
print("friday")
elif days_number == 6 :
print("saturday")
elif days_number == 7 :
print("sunday")
else:
print("out of days_number")
| true
|
e0b176c877b9b553dbcee2b6124cfde4dd4c128c
|
Vinod096/learn-python
|
/lesson_02/personal/For_loop/scrimba.py
| 220
| 4.15625
| 4
|
names = ['Jane','John','Alena']
names_1 = ['John','Jane','Adeev']
text = 'Welcome to the party'
names.extend(names_1)
for name in range(1):
names.append(input("enter name :"))
for name in names:
print(name,text)
| false
|
7feb19a5121eeb321f0b2a187852cae0becb4c4f
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_2/ingredient.py
| 1,022
| 4.40625
| 4
|
total_no_of_cookies = 48
cups_of_sugar = 1.5
cups_of_butter = 1
cups_of_flour = 2.75
no_of_cookies_req = round(int(input("cookies required :")))
print("no of cookies required in roundup : {0:2f} ".format(no_of_cookies_req))
req_sugar = (no_of_cookies_req / total_no_of_cookies) * cups_of_sugar
print("no of cups of sugar_required : {0:.2f}".format(req_sugar))
req_butter = (no_of_cookies_req / total_no_of_cookies) * cups_of_butter
print("no of cups of butter_required : {0:.2f}".format(req_butter))
flour_req = (no_of_cookies_req / total_no_of_cookies) * cups_of_flour
print("no of cups of flour_required : {0:.2f}".format(flour_req))
#Question :
#A cookie recipe calls for the following ingredients:
#• 1.5 cups of sugar
#• 1 cup of butter
#• 2.75 cups of flour
#The recipe produces 48 cookies with this amount of the ingredients. Write a program that
#asks the user how many cookies he or she wants to make, and then displays the number of
#cups of each ingredient needed for the specified number of cookies.
| true
|
dd42d5e406efde3b62d76588eeb37a7470edafe8
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_8/01_initials.py
| 463
| 4.5
| 4
|
#Write a program that gets a string containing a person’s first, middle, and last names,and then display their first, middle, and last initials. For example, if the user enters John William Smith the program should display J. W. S.
first_name = str(input("Enter First Name : "))
middle_name = str(input("Enter Middle Name : "))
last_name = str(input("Enter Last Name : "))
print("Initials of persons names : ", '\n',first_name[0],'\n', middle_name[0],'\n', last_name[0])
| true
|
ad1f65388986962de297bba5f1219809634fccd3
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_4/09_ocean.py
| 380
| 4.28125
| 4
|
#Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an
#application that displays the number of millimeters that the ocean will have risen each year
#for the next 25 years.
rising_oceans_levels_per_year = 1.6
years = 0
for i in range (1,26):
years = rising_oceans_levels_per_year * i
print(f"rising levels per {i} year : {years}")
| true
|
80906ba30bc751f48e177907ab2967803c269022
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_5/12_Maximum_of_Two_Values.py
| 867
| 4.625
| 5
|
#Write a function named max that accepts two integer values as arguments and returns the
#value that is the greater of the two. For example, if 7 and 12 are passed as arguments to
#the function, the function should return 12. Use the function in a program that prompts the
#user to enter two integer values. The program should display the value that is the greater
#of the two.
def value_1():
number_1 = int(input("enter value 1 : "))
return number_1
def value_2():
number_2 = int(input("enter value 2 : "))
return number_2
def max(value_1,value_2):
if value_1 > value_2 :
return value_1
else:
return value_2
def main():
number_1 = value_1()
number_2 = value_2()
max_value = max(number_1,number_2)
print("number 1 :",number_1)
print("number 2 :",number_2)
print("greater number :",max_value)
main()
| true
|
83b9e523b3ff90d47c7689f3293b77a16d05a965
|
Vinod096/learn-python
|
/lesson_02/personal/chapter_5/06_calories.py
| 1,078
| 4.65625
| 5
|
#A nutritionist who works for a fitness club helps members by evaluating their diets. As part
#of her evaluation, she asks members for the number of fat grams and carbohydrate grams
#that they consumed in a day. Then, she calculates the number of calories that result from
#the fat, using the following formula:
#calories from fat = fat grams * 9
#Next, she calculates the number of calories that result from the carbohydrates, using the
#following formula:
#calories from carbs= carb grams * 4
#The nutritionist asks you to write a program that will make these calculations.
def fat():
fat_grams = float(input("Enter fat grams :"))
calories_from_fat = fat_grams * 9
return calories_from_fat
def carbohydrates():
carb_grams = float(input("Enter Carbohydrates :"))
calories_from_carbs = carb_grams * 4
return calories_from_carbs
def calculations():
C_fat = fat()
C_carbohydrates = carbohydrates()
print("Calories from fat is :{0:.2f}".format(C_fat))
print("calories from carbohydrates :{0:.2f}".format(C_carbohydrates))
calculations()
| true
|
11a462649f8ebd34f0d29ab619e6d36bc98160af
|
Moandh81/python-self-training
|
/tuple/9.py
| 494
| 4.34375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to find the repeated items of a tuple.
mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "lion" , "zebra","duck" ,"bull", "sheep", "cat", "cow", "fox", "lion")
frequency = {}
for item in mytuple:
if item.lower() not in frequency:
frequency[item.lower()] = 1
else:
frequency[item.lower()] = frequency[item.lower()] + 1
for key,value in frequency.items():
if frequency[key] > 1:
print(key)
| true
|
ac6d44000cce88e231a9a85d082c8538b44fd515
|
Moandh81/python-self-training
|
/datetime/32.py
| 272
| 4.375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to calculate a number of days between two dates.
from datetime import date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
| true
|
fee021a37c322579ad36109a92c914eaf4a809b7
|
Moandh81/python-self-training
|
/functions/1.py
| 657
| 4.375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Write a Python function to find the Max of three numbers.
import re
expression = r'[0-9]+'
numberslist = []
number1 = number2 = number3 = ""
while re.search(expression, number1) is None:
number1 = input('Please input first number: \n')
while re.search(expression, number2) is None:
number2 = input('Please input second number: \n')
while re.search(expression, number3) is None:
number3 = input('Please input third number: \n')
numberslist.append(number1)
numberslist.append(number2)
numberslist.append(number3)
print(numberslist)
print("the maximum number is {}".format(max(numberslist)))
| true
|
4a43f7f498cda12296b75247c5b6d45941519527
|
Moandh81/python-self-training
|
/conditional-statements-and-loops/5.py
| 268
| 4.375
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program that accepts a word from the user and reverse it.
word = input("Please input a word : \n")
newword = ""
i = len(word)
while i > 0:
newword = newword + word[i-1]
i = i - 1
print(newword)
| true
|
c78566301e0cc885f89c65310e9245fb5072dce1
|
Moandh81/python-self-training
|
/dictionary/24.py
| 517
| 4.5
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to create a dictionary from a string. Go to the editor
# Note: Track the count of the letters from the string.
# Sample string : 'w3resource'
# Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
txt = input('Please insert a string : \n')
dictionary = {}
for letter in txt:
if letter not in dictionary.keys():
dictionary[letter] = 1
else:
dictionary[letter] = dictionary[letter] + 1
print(dictionary)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.