blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f43f14fe47b99787333551c200df24d211f2f466 | digant0705/Algorithm | /LeetCode/Python/156 Binary Tree Upside Down.py | 823 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Binary Tree Upside Down
=======================
Given a binary tree where all the right nodes are either leaf nodes with a
sibling (a left node that shares the same parent node) or empty, flip it upside
down and turn it into a tree where the original right nodes turned into left
leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \
3 1
'''
class Solution(object):
def upsideDownBinaryTree(self, root):
if not root or not root.left:
return root
newRoot = self.upsideDownBinaryTree(root.left)
root.left.left, root.left.right = root.right, root
root.left = root.right = None
return newRoot
| true |
bb74d28eb5e2fae422a278a02c920d856bd11b5d | digant0705/Algorithm | /LeetCode/Python/059 Spiral Matrix II.py | 1,968 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Spiral Matrix II
================
Given an integer n, generate a square matrix filled with elements from 1 to n^2
in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
'''
class Solution(object):
'''算法思路:
一圈一圈的生成
'''
def generateMatrix(self, n):
start, row, col, matrix = 1, 0, 0, [[0] * n for _ in xrange(n)]
while n > 0:
i = j = 0
for index, iterator in enumerate([
xrange(n),
xrange(1, n),
xrange(n - 2, -1, -1),
xrange(n - 2, 0, -1)]):
for x in iterator:
if index & 1:
i = x
else:
j = x
matrix[row + i][col + j] = start
start += 1
row += 1
col += 1
n -= 2
return matrix
class Solution(object):
"""算法思路:
同上,只不过是另外一种写法
"""
def generate(self, x, y, w, start, board):
i, j = 0, 0
for j in xrange(w):
board[x + i][y + j] = start
start += 1
for i in xrange(1, w):
board[x + i][y + j] = start
start += 1
if w > 1:
for j in xrange(w - 2, -1, -1):
board[x + i][y + j] = start
start += 1
for i in xrange(w - 2, 0, -1):
board[x + i][y + j] = start
start += 1
return start
def generateMatrix(self, n):
board = [[0] * n for _ in xrange(n)]
x, y, start = 0, 0, 1
while n > 0:
start = self.generate(x, y, n, start, board)
x += 1
y += 1
n -= 2
return board
s = Solution()
print s.generateMatrix(3)
| true |
422aa7064b6f08b428a782685507ecd3d6b8b98a | digant0705/Algorithm | /LeetCode/Python/117 Populating Next Right Pointers in Each Node II.py | 1,611 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Populating Next Right Pointers in Each Node II
==============================================
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution
still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
'''
class Solution(object):
'''算法思路:
同 166 第一种解法,但依旧用了 queue
'''
def connect(self, root):
if not root:
return
queue = [root]
while queue:
pre = None
for i in xrange(len(queue)):
peek = queue.pop(0)
peek.next, pre = pre, peek
[queue.append(c) for c in (peek.right, peek.left) if c]
class Solution(object):
'''算法思路:
先访问 当前节点,再访问 右孩子,最后访问 左孩子,依次连接
'''
def connect(self, root):
if not (root and (root.left or root.right)):
return
if root.left and root.right:
root.left.next = root.right
next = root.next
while next and not (next.left or next.right):
next = next.next
if next:
(root.right or root.left).next = next.left or next.right
map(self.connect, (root.right, root.left))
| true |
49948daded2dd54ec0580b90f49602a9f109b623 | digant0705/Algorithm | /LeetCode/Python/114 Flatten Binary Tree to Linked List.py | 903 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Flatten Binary Tree to Linked List
==================================
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
class Solution(object):
'''算法思路:
先序遍历,然后把遍历结果构成 Linked List
'''
def flatten(self, root):
stack, r = [], []
while stack or root:
if root:
r.append(root)
stack.append(root)
root = root.left
else:
root = stack.pop().right
tail = None
for i in xrange(len(r) - 1, -1, -1):
r[i].left, r[i].right, tail = None, tail, r[i]
| true |
f70831de914e8e30bc7d5b585d604621b153d989 | digant0705/Algorithm | /LeetCode/Python/044 Wildcard Matching.py | 2,354 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Wildcard Matching
=================
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
'''
def cache(f):
def method(obj, s, p, i, j):
key = '{}:{}'.format(i, j)
if key not in obj.cache:
obj.cache[key] = f(obj, s, p, i, j)
return obj.cache[key]
return method
class Solution(object):
'''算法思路:
DFS + cache
'''
def __init__(self):
self.cache = {}
@cache
def dfs(self, s, p, i, j):
m, n = map(len, (s, p))
if i == m and j == n:
return True
if i < m and j == n:
return False
if i == m and j < n:
return p[j] == '*' and self.dfs(s, p, i, j + 1)
if p[j] == '?' or s[i] == p[j]:
return self.dfs(s, p, i + 1, j + 1)
if p[j] == '*':
return (self.dfs(s, p, i, j + 1) or
self.dfs(s, p, i + 1, j + 1) or
self.dfs(s, p, i + 1, j))
return False
def isMatch(self, s, p):
if len(p) - p.count('*') > len(s):
return False
return self.dfs(s, p, 0, 0)
class Solution(object):
'''算法思路:
动态规划,同第 10 题差不多
'''
def isMatch(self, s, p):
m, n = map(len, (s, p))
if n - p.count('*') > m:
return False
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for j in range(n):
dp[0][j + 1] = p[j] == '*' and dp[0][j]
for i in range(m):
for j in range(n):
if s[i] == p[j] or p[j] == '?':
dp[i + 1][j + 1] = dp[i][j]
elif p[j] == '*':
dp[i + 1][j + 1] = dp[i + 1][j] or dp[i][j] or dp[i][j + 1]
return dp[-1][-1]
s = Solution()
print s.isMatch("", "*")
| true |
676462bbeb65b4c86a49a3e15fda440170e117cb | digant0705/Algorithm | /LeetCode/Python/281 Zigzag Iterator.py | 1,770 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Zigzag Iterator
===============
Given two 1d vectors, implement an iterator to return their elements
alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements
returned by next should be: [1, 3, 2, 4, 5, 6].
Follow up: What if you are given k 1d vectors? How well can your code be
extended to such cases?
Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases.
If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For
example, given the following input:
[1,2,3]
[4,5,6,7]
[8,9]
It should return [1,4,8,2,5,9,3,6,7].
'''
class ZigzagIterator(object):
'''算法思路:
记录遍历指针即可,对于 k 个,只需把 self.arrays 改成对应的 arrays 即可
'''
def __init__(self, v1, v2):
self.arrays = [v1, v2]
self.lenArrays = len(self.arrays)
self.arrayLengths = map(len, self.arrays)
self.pointers = [0] * self.lenArrays
self.total = sum(self.arrayLengths)
self.count = 0
self.cursor = 0
def incrCursor(self):
self.cursor = (self.cursor + 1) % self.lenArrays
def next(self):
while self.pointers[self.cursor] >= self.arrayLengths[self.cursor]:
self.incrCursor()
val = self.arrays[self.cursor][self.pointers[self.cursor]]
self.pointers[self.cursor] += 1
self.incrCursor()
self.count += 1
return val
def hasNext(self):
return self.count < self.total
i = ZigzagIterator([1, 2, 3], [4, 5, 6, 7])
while i.hasNext():
print i.next()
| true |
1b1ae8b841a23ef9411a169a2e41d7702ad2d7c3 | digant0705/Algorithm | /LeetCode/Python/048 Rotate Image.py | 1,873 | 4.15625 | 4 | # -*- coding: utf-8 -*-
'''
Rotate Image
============
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
'''
class Solution(object):
'''算法思路:
- o = (length - 1) / 2.0 旋转的中心为 (o, o)
- 可以根据 当前点 (row, col) 算出 将要翻转的点为 (col, 2 * o - row)
- 找出要翻转的圈的起点,然后进行一圈一圈的翻转
'''
def rotateCircle(self, matrix, o, start_row, start_col):
row, col, cnt, pre = (
start_row, start_col, 0, matrix[start_row][start_col])
while 1:
cnt += row == start_row and col == start_col
if cnt > 1:
return
x, y = int(col), int(2 * o - row)
matrix[x][y], pre = pre, matrix[x][y]
row, col = x, y
def rotate(self, matrix):
length = len(matrix)
if length <= 1:
return
o = (length - 1) / 2.0
for start_row in xrange(int(o) + 1):
for start_col in xrange(int(o) + (not length % 2)):
self.rotateCircle(matrix, o, start_row, start_col)
class Solution(object):
"""算法思路:
先把matrix沿着对角线折叠互换,然后把每一行reverse
"""
def rotate(self, matrix):
for x in xrange(len(matrix)):
for y in xrange(x):
matrix[x][y], matrix[y][x] = matrix[y][x], matrix[x][y]
for row in matrix:
low, high = 0, len(row) - 1
while low < high:
row[low], row[high] = row[high], row[low]
low += 1
high -= 1
s = Solution()
s.rotate([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
])
s.rotate([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
| false |
c7731d232c8a19ee8a5a62c6f095c7ef69f12e99 | digant0705/Algorithm | /LeetCode/Python/224 Basic Calculator.py | 2,347 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
Basic Calculator
================
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus
+ or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
'''
class Solution(object):
'''算法思路:
利用栈,既可以先把中缀表达式转换为后缀表达式,然后在计算,或者直接计算
该解法是通用解法,包含括号和四则运算,逆波兰表达式中栈自底向上符号优先级是递增的
note: RPN => Reversed Polish Notation,即逆波兰表达式
'''
def RPN(self, expression):
priority = {'+': 0, '-': 0, '*': 1, '/': 1}
stack, i, n, r = [], 0, len(expression), []
while i < n:
if expression[i].isdigit():
num = []
while i < n and expression[i].isdigit():
num.append(expression[i])
i += 1
r.append(int(''.join(num)))
continue
if expression[i] == '(':
stack.append('(')
elif expression[i] == ')':
while stack[-1] != '(':
r.append(stack.pop())
stack.pop()
elif expression[i] in priority:
while (stack and stack[-1] != '(' and
priority[expression[i]] <= priority[stack[-1]]):
r.append(stack.pop())
stack.append(expression[i])
i += 1
r += stack[::-1]
return r
def calculate(self, s):
rpn, stack = self.RPN(s), []
operations = {
'+': operator.add, '-': operator.sub,
'*': operator.mul, '/': operator.div}
for item in rpn:
if isinstance(item, int):
stack.append(item)
else:
b = stack.pop()
a = stack.pop()
stack.append(operations[item](a, b))
return stack[0]
s = Solution()
print s.calculate('1 + 1')
print s.calculate(' 2-1 + 2 ')
print s.calculate('(1+(4+5+2)-3)+(6+8)')
| false |
b1d4c792fa5bed9318d6b06ef5040f8033da7b92 | digant0705/Algorithm | /LeetCode/Python/371 Sum of Two Integers.py | 663 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Sum of Two Integers
===================
Calculate the sum of two integers a and b, but you are not allowed to use the
operator + and -.
Example:
Given a = 1 and b = 2, return 3.
"""
class Solution(object):
def add(self, a, b):
for _ in xrange(32):
a, b = a ^ b, (a & b) << 1
return a
def getSum(self, a, b):
s = self.add(a, b) & 0xFFFFFFFF
# if sum is negative, we should translate two's complement to
# the true form
if s & 0x80000000:
return -self.add(~(s & 0x7FFFFFFF) & 0x7FFFFFFF, 1)
return s
s = Solution()
print s.getSum(-9, 10)
| true |
35131f3bff52c30cf0ca3f99445ec08a53f020f6 | anatulea/codesignal_challenges | /Intro_CodeSignal/07_Through the Fog.py/31_depositProfit.py | 953 | 4.25 | 4 | '''
You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold.
Example
For deposit = 100, rate = 20, and threshold = 170, the output should be
depositProfit(deposit, rate, threshold) = 3.
Each year the amount of money in your account increases by 20%. So throughout the years, your balance would be:
year 0: 100;
year 1: 120;
year 2: 144;
year 3: 172.8.
Thus, it will take 3 years for your balance to pass the threshold, so the answer is 3.
'''
def depositProfit(deposit, rate, threshold):
count = 0
while deposit< threshold:
deposit = deposit + (deposit*rate)/100
count+=1
return count
import math
def depositProfit2(deposit, rate, threshold):
return math.ceil(math.log(threshold/deposit, 1+rate/100)) | true |
40da9655f1ceb1450d203efa31a6bfc9a3748220 | anatulea/codesignal_challenges | /Intro_CodeSignal/01_The Jurney Begins/02_centuryFromYear.py | 1,220 | 4.1875 | 4 | '''
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
centuryFromYear(year) = 17.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer year
A positive integer, designating the year.
Guaranteed constraints:
1 ≤ year ≤ 2005.
[output] integer
The number of the century the year is in.
'''
def centuryFromYear(year):
return (year + 99) // 100
# return (year-1)//100+1
# return int((year - 1) / 100) + 1
'''The Math.ceil() function always rounds a number up to the next largest integer.'''
# return math.ceil(year/100)
# if year % 100 == 0:
# return(int(year/100))
# else:
# return(int(year/100 + 1))
# my solution
def centuryFromYear2(year):
if 1>= year or year<= 100:
return 1
if year>= 2005:
return 21
# x = int(str(year)[:2])
if int(str(year)[2:]) == 00 or int(str(year)[2:]) == 0:
return int(str(year)[:-2])
else:
return int(str(year)[:-2])+1 | true |
67801342d06b60b610ee909bf60712796894cbad | anatulea/codesignal_challenges | /Python/11_Higher Order Thinking/73_tryFunctions.py | 1,391 | 4.40625 | 4 | '''
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extremely difficult to comprehend.
To understand what function is applied to x instead of the one that should have been applied, you decided to go ahead and compare the result with results of all the functions you could come up with. Given the variable x and a list of functions, return a list of values f(x) for each x in functions.
Example
For x = 1 and
functions = ["math.sin", "math.cos", "lambda x: x * 2", "lambda x: x ** 2"],
the output should be
tryFunctions(x, functions) = [0.84147, 0.5403, 2, 1].
'''
def tryFunctions(x, functions):
return [eval(f)(x) for f in functions]
# return [fun(x) for fun in map(eval,functions)]
'''eval(expression, globals=None, locals=None)
-expression - the string parsed and evaluated as a Python expression
-globals (optional) - a dictionary
-locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.
-The eval() method parses the expression passed to this method and runs python expression (code) within the program
''' | true |
7d95aafc8e3b783c05196c5ba11e448578bf5a9e | anatulea/codesignal_challenges | /Python/08_Itertools Kit/48_cyclicName.py | 1,147 | 4.71875 | 5 | '''
You've come up with a really cool name for your future startup company, and already have an idea about its logo. This logo will represent a circle, with the prefix of a cyclic string formed by the company name written around it.
The length n of the prefix you need to take depends on the size of the logo. You haven't yet decided on it, so you'd like to try out various options. Given the name of your company, return the prefix of the corresponding cyclic string containing n characters.
Example
For name = "nicecoder" and n = 15, the output should be
cyclicName(name, n) = "nicecoderniceco".
'''
from itertools import cycle
# Itertools is a module that provides various functions that work on iterators to produce complex iterators.
def cyclicName(name, n):
gen = cycle(name) # defining iterator
res = [next(gen) for _ in range(n)] # Using next function to take the first n char
return ''.join(res)
''' Infinite iterators
- count(start, step): This iterator starts printing from the “start” number and prints infinitely. If steps are mentioned, the numbers are skipped else step is 1 by default.
'''
| true |
ae12622ea7ab0959a7e0896b504f683487cac457 | anatulea/codesignal_challenges | /isIPv4Address.py | 1,229 | 4.125 | 4 | '''
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
Given a string, find out if it satisfies the IPv4 address naming rules.
Example
For inputString = "172.16.254.1", the output should be
isIPv4Address(inputString) = true;
For inputString = "172.316.254.1", the output should be
isIPv4Address(inputString) = false.
316 is not in range [0, 255].
For inputString = ".254.255.0", the output should be
isIPv4Address(inputString) = false.
There is no first number.'''
def isIPv4Address(inputString):
nums = inputString.split('.')
print(nums)
if len(nums) != 4:
return False
if '' in nums:
return False
for i in nums:
try:
n= int(i)
except ValueError:
return False
if len(i)>1 and int(i[0]) == 0:
return False
if int(i) > 255:
return False
return True
string = "0.254.255.0"
inputString= "0..1.0"
print(isIPv4Address(string))
print(isIPv4Address(inputString)) | true |
79efe0f71e3216d25af3d67500a29423af62a35f | anatulea/codesignal_challenges | /Intro_CodeSignal/03_Smooth Sailing/13_reverseInParentheses.py | 1,577 | 4.21875 | 4 | '''
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
Example
For inputString = "(bar)", the output should be
reverseInParentheses(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
reverseInParentheses(inputString) = "foorabbaz";
For inputString = "foo(bar)baz(blim)", the output should be
reverseInParentheses(inputString) = "foorabbazmilb";
For inputString = "foo(bar(baz))blim", the output should be
reverseInParentheses(inputString) = "foobazrabblim".
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim".
'''
def reverseInParentheses(s):
stack = []
for x in s:
if x == ")":
tmp = ""
while stack[-1] != "(":
tmp += stack.pop()
stack.pop() # pop the (
for item in tmp:
stack.append(item)
else:
stack.append(x)
return "".join(stack)
def reverseInParentheses2(s):
return eval('"' + s.replace('(', '"+("').replace(')', '")[::-1]+"') + '"')
def reverseInParentheses3(s):
for i in range(len(s)):
if s[i] == "(":
start = i
if s[i] == ")":
end = i
return reverseInParentheses3(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s
def reverseInParentheses4(s):
end = s.find(")")
start = s.rfind("(",0,end)
if end == -1:
return s
return reverseInParentheses4(s[:start] + s[start+1:end][::-1] + s[end+1:])
| true |
0f30ab84f246ce8c842d54dd760106bcb464304e | anatulea/codesignal_challenges | /Python/02_SlitheringinStrings/19_newStyleFormatting.py | 1,234 | 4.125 | 4 | '''
Implement a function that will turn the old-style string formating s into a new one so that the following two strings have the same meaning:
s % (*args)
s.format(*args)
Example
For s = "We expect the %f%% growth this week", the output should be
newStyleFormatting(s) = "We expect the {}% growth this week".
'''
def newStyleFormatting(s):
s = s.split('%%')
print(s)# s = ["We expect the %f", "growth this week"]
for i in range(len(s)):
while '%' in s[i]:
idx = s[i].find('%') # find the % index
# modify string "We expect the " + {} + the rest of string
s[i] = s[i][:idx] + '{}' + s[i][idx + 2:]
return '%'.join(s)
import re
def newStyleFormatting2(s):
return re.sub('%\w','{}', s.replace('%%','{%}')).replace('{%}','%')
def newStyleFormatting3(s):
s = re.sub('%%', '{%}', s)
# re.sub(pattern we look for, replacement, string, count=0, flags=0)
s = re.sub('%[dfFgeEGnnxXodcbs]', '{}', s)
return re.sub('{%}','%',s)
import re
def newStyleFormatting4(s):
return "%".join([re.sub("%([bcdeEfFgGnosxX])","{}",S) for S in s.split("%%")])
def newStyleFormatting5(s):
return '%'.join(re.sub('%\w', '{}', part) for part in s.split('%%')) | true |
5ef35cd82d9d5428fd4277db7190f95159b9c306 | tessadvries/DSF | /dsf-exercise12-snacknames-refactored.py | 344 | 4.28125 | 4 | friends = {
"Tessa" : " ",
"Manon" : " ",
"Stijn" : " ",
}
for key in friends:
length = len(key)
print(f'Hi {key}! Your name has {length} characters.')
friends[key] = input(f'{key}, what is your favorite snack? ')
value = friends[key]
print(friends)
for key, value in friends.items():
print(f'The favorite snack of {key} is {value}') | false |
d4d9a9ae96ebf4a33a9758802b9acdfeb555ccdc | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Exercises/12. recursion_palindrome.py | 401 | 4.25 | 4 | def palindrome(word, index=0, reversed_word=""):
if index == len(word):
if not reversed_word == word:
return f"{word} is not a palindrome"
return f"{word} is a palindrome"
else:
reversed_word += word[-(index + 1)]
return palindrome(word, index + 1, reversed_word)
print(palindrome("abcba"))
print(palindrome("peter"))
print(palindrome("ByyB")) | true |
8c4dd6b4f43c3047bcdc057c3c8037f9ed4f71ef | guilhermeborges84/Programacao | /Curso JLCP/Exercícios/Exercicio2.py | 701 | 4.15625 | 4 | #Definino as variáveis
nome = str(input("Digite o seu nome: "))
cargo = str(input("Digite o seu cargo: "))
concatenado = 'Nome:' + nome + ' ,' + ' Cargo:' + cargo
#Concatenando manualmente
print(f'Valores concatenados manualmente: {nome} {cargo}')
print(f'Juntando string usando variáveis: {concatenado}')
inserir = input('Deseja inserir um novo nome e cargo? S para SIM ou N para NÃO ')
while ( inserir =='s'):
nome = str(input("Digite o seu nome: "))
cargo = str(input("Digite o seu cargo: "))
concatenado = concatenado + ',' + 'Nome: ' + nome + ',' + 'Cargo: '+ cargo
inserir = input('Deseja inserir um novo nome e cargo? S para SIM ou N para NÃO ')
print( concatenado ) | false |
f3946cde9b458f7e24e47188ce809f6bcead79bf | satish3366/PES-Assignnment-Set-2 | /37_dist_operations.py | 791 | 4.3125 | 4 | dict1={'Empid':12,'Ename':'Vijay','Band':'B1'}
dict2={'Rollno':11,'Name':'Arshiya','Class':7}
dict3={'Kname':'Ashu','Kage':8,'Bgroup':'B+'}
if dict1>dict2 and dict1>dict3:
print ("dict1 is th biggest",dict1)
elif dict2>dict1 and dict2>dict3:
print ("dict2 is the biggest",dict2)
else:
print ("dict3 is the biggest",dict3)
dict1['Experience']=4
dict2['School']='KV bhrukunda'
print ("\ndict1 after adding new elements is",dict1)
print ("\ndict2 after adding new elements is",dict2)
print ("Length of dict1 is",len(dict1))
print ("Length of dict2 is",len(dict2))
print ("Length of dict3 is",len(dict3))
dict1Str=str(dict1)
dict2Str=str(dict2)
dict3Str=str(dict3)
dictStr=dict1Str+dict2Str+dict3Str
print ("the concatenated dicts as strings all together is",dictStr)
| false |
3a7baad4cf891fe0d8bb6a7b5fa11ce938cbfda8 | om-100/assignment2 | /11.py | 519 | 4.6875 | 5 | """Create a variable, filename. Assuming that it has a three-letter
extension, and using slice operations, find the extension. For
README.txt, the extension should be txt. Write code using slice
operations that will give the name without the extension. Does your
code work on filenames of arbitrary length?"""
def filename(name):
extension = name[-3:]
filename = name[:-3]
print(filename, extension, sep=" is filename and extension is ")
name = input("Enter a filename with extension: ")
filename(name) | true |
7d16b1a4caca082162ed41edb8d679beec2d3389 | LeonGuerreroM/Codigos-Python | /Binary_Power.py | 2,641 | 4.15625 | 4 | def binary_method(base, exponent, module):
'''Funcion que realiza la potenciación modular con el método binario
Entradas
base => base de la potencia
exponent => exponente de la potencia
module => módulo de la potenciación modular
Salidas
C => resultado de la potenciación modular '''
binary_exp = 0 #Guarda el equivalente binario de la potencia
#is_first = 1 #Indicador que se está trabjando con el bit mas significativo
first_bit = 0
C = 0
if module == 0:
print("El módulo no es válido")
return -1
elif module == 1:
return 0
#if exponent == 0:
# if module == 1: #quedo cubierto con mod 1
# return 0
# else: #queda cubierto con C=1. Este es mas directo pero el otro sigue el algoritmo
# return 1
binary_exp = bin(exponent)[2:] #Convierte el exponente a binario, como str
first_bit = binary_exp[:1]
binary_exp = binary_exp[1:]
if first_bit == '1': #Si el mas significativo es 1
C = base
else: #Si es 0, C = 1, a menos que sea mod 1, pero ese caso ya se cubrió
C = 1
#print(first_bit)
#print(binary_exp)
#print(C)
for i in binary_exp: #Recorre comenzando por el más significativo
'''if is_first == 1: #En caso de que sea el mas significativo
is_first = 0 Normalmente habría hecho esto, pero se desperdicia procesamiento preguntando a todos
if i == 1: Cuando simplemente se podría hacer fuera del for y no tomar el primer bit
C = M Hacer ese slice sería menos gasto de recursos que una validación por iteración
else: Despues del slice ya solo tenemos que hacer lo que si compete a este for
C = 1 Aprendizaje: Si solo tienes que hacer algo en la primera o ultima iteración, hazlo afuera
ya sea antes o despues y empieza o termina la iteración despúes o antes '''
C = C**2 #Siempre se eleva C al cuadrado
if C > module-1: #Si excede el campo del módulo se saca el residuo
C = C%module
if i == '1': #Si el bit es 1
#print("entré")
C = C*base #se multiplica por M
if C > module-1: #Si excede el campo del módulo se saca el residuo
C = C%module
#print("El resultado de {}^{} mod {} es {C}".format(base, exponent, module, C))
return C
result = binary_method(3, 158215211234689, 53)
if result != -1:
print("El resultado es {}".format(result)) | false |
13d759a3accaba9725d3b70f6a261fe9d9eca1a9 | owaisali8/Python-Bootcamp-DSC-DSU | /week_1/2.py | 924 | 4.125 | 4 | def average(x):
return sum(x)/len(x)
user_records = int(input("How many student records do you want to save: "))
student_list = {}
student_marks = []
for i in range(user_records):
roll_number = input("Enter roll number:")
name = input("Enter name: ")
age = input("Enter age: ")
marks = int(input("Enter marks: "))
while marks < 0 or marks > 100:
print("Marks range should be between 0 and 100")
marks = int(input("Enter correct marks: "))
student_marks.append(marks)
student_list[roll_number] = [name, age, marks]
print('\n')
print("{:<15} {:<15} {:<15} {:<15}".format(
'Roll Number', 'Name', 'Age', 'Marks'))
print()
for k, v in student_list.items():
name, age, marks = v
print("{:<15} {:<15} {:<15} {:<15}".format(k, name, age, marks))
print("\nAverage: ", average(student_marks))
print("Highest: ", max(student_marks))
print("Lowest: ", min(student_marks))
| true |
f7ccdb31cc184e3603f2f465c1d68f5c694ef9d7 | Ollisteka/Chipher_Breaker | /logic/encryptor.py | 2,968 | 4.3125 | 4 | #!/usr/bin/env python3
# coding=utf-8
import json
import sys
import tempfile
from copy import copy
from random import shuffle
def read_json_file(filename, encoding):
"""
Read data, written in a json format from a file, and return it
:param encoding:
:param filename:
:return:
"""
with open(filename, "r", encoding=encoding) as file:
return json.loads(file.read())
def generate_alphabet_list(start, end):
"""
Function makes a list, containing all the letters from start
to end included.
:type end: str
:type start: str
:return:
"""
return [x for x in map(chr, range(ord(start), ord(end) + 1))]
def make_alphabet(string):
"""
Function makes a list, containing all the letters from the range.
:param string: A-Za-z or А-Яа-яЁё
:return:
"""
letter_range = "".join(
x for x in string if x.islower() or x == '-').strip('-')
if len(letter_range) == 3:
return generate_alphabet_list(letter_range[0], letter_range[2])
defis = letter_range.find('-')
alphabet = generate_alphabet_list(
letter_range[defis - 1], letter_range[defis + 1])
for letter in letter_range:
if letter_range.find(letter) not in range(defis - 1, defis + 2):
alphabet.append(letter)
return alphabet
def generate_substitution(string):
"""
Generate new substitution, based on the given letter's range.
:param string: A-Za-z or А-Яа-яЁё
:return:
"""
alphabet = make_alphabet(string)
shuffled = copy(alphabet)
shuffle(shuffled)
return dict(zip(alphabet, shuffled))
def reverse_substitution(substitution):
"""
Exchange keys with values.
:type substitution: dict
:return:
"""
return {v: k for k, v in substitution.items()}
def code_text_from_file(filename, encoding, substitution):
"""
Code text from file
:param filename:
:param encoding:
:param substitution:
:return:
"""
# noinspection PyProtectedMember
if isinstance(filename, tempfile._TemporaryFileWrapper):
with filename as f:
f.seek(0)
text = f.read().decode(encoding)
return code(text, substitution)
with open(filename, 'r', encoding=encoding) as file:
return code(file.read(), substitution)
def code_stdin(substitution):
"""
Code text from stdin
:param substitution:
:return:
"""
return code(str.join("", sys.stdin), substitution)
def code(text, substitution):
"""
The function encrypts the text, assigning each letter
a new one from the substitution
:type text: str or Text.IOWrapper[str]
:type substitution: dict
:return:
"""
upper_letters = dict(zip([x.upper() for x in substitution.keys()],
[x.upper() for x in substitution.values()]))
_tab = str.maketrans(dict(substitution, **upper_letters))
return text.translate(_tab)
| true |
909f28e3de50e5b1b096fe162e5aaba387c273f1 | sophialuo/CrackingTheCodingInterview_4thEdition | /chapter8/8.1.py | 379 | 4.1875 | 4 | #8.1
#Write a method to generate nth Fibonacci number
def fib_recursion(n):
if n <= 1:
return 1
return fib_recursion(n-1) + fib_recursion(n-2)
#a more space and time efficient way
def fib_efficient(n):
first = 0
second = 1
for i in range(n):
temp = second
second += first
first = temp
return second
| false |
d453fea7cdea71dc9ca2cf967350e9d9bfb836e3 | FlyingSparrow/Python3_Learning | /Python3.4_Project/com/base/section3/basic_datatype.py | 1,517 | 4.15625 | 4 | #!/usr/bin/python3
print("==============变量示例=================")
counter = 100
miles = 1000.0
name = "runoob"
print(counter)
print(miles)
print(name)
print("==============字符串示例=================")
str = 'Runoob'
print(str)
print(str[0:-1])
print(str[0])
print(str[2:5])
print(str[2:])
print(str*2)
print(str+"TEST")
print("==============列表示例=================")
list = ['abcd', 786, 2.23, 'runoob', 70.2]
tinylist = [123, 'runoob']
print(list)
print(list[0])
print(list[1:3])
print(list[2:])
print(tinylist*2)
print(list+tinylist)
print("=============元组示例=================")
tuple = ('abcd', 786, 2.23, 'runoob', 70.2)
tinytuple = (123, 'runoob')
print(tuple)
print(tuple[0])
print(tuple[1:3])
print(tuple[2:])
print(tinytuple*2)
print(tuple+tinytuple)
print("============集合示例=================")
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student)
if('Rose' in student):
print('Rose 在集合中')
else:
print('Rose 不在集合中')
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a 和 b 的差集
print(a | b) # a 和 b 的并集
print(a & b) # a 和 b 的交集
print(a ^ b) # a 和 b 中不同时存在的元素
print("============字典示例=================")
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
tinydict = {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
print(dict['one'])
print(dict[2])
print(tinydict)
print(tinydict.keys())
print(tinydict.values()) | false |
15065a683fa733faa071b3f9e145100ca355951c | FlyingSparrow/Python3_Learning | /Python3.4_Project/com/base/section25/sample_23.py | 930 | 4.15625 | 4 | #!/usr/bin/python3
print("{0}简单计算器实现{1}".format('=' * 10, '=' * 10))
def add(x, y):
return x + y
def substract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print('divisor can not be zero')
return
else:
return x / y
print('选择运算:')
print('1、相加')
print('2、相减')
print('3、相乘')
print('4、相除')
choice = input('输入你的选择(1/2/3/4):')
num1 = int(input('输入第一个数字:'))
num2 = int(input('输入第二个数字:'))
if choice == '1':
print('{}+{}={}'.format(num1, num2, add(num1, num2)))
elif choice == '2':
print('{}-{}={}'.format(num1, num2, substract(num1, num2)))
elif choice == '3':
print('{}*{}={}'.format(num1, num2, multiply(num1, num2)))
elif choice == '4':
print('{}/{}={}'.format(num1, num2, divide(num1, num2)))
else:
print('非法输入')
| false |
f84cf15c04be752423408f06737cc5100c7f0cf4 | af94080/bitesofpy | /9/palindrome.py | 1,406 | 4.3125 | 4 | """A palindrome is a word, phrase, number, or other sequence of characters
which reads the same backward as forward"""
import os
import urllib.request
DICTIONARY = os.path.join('/tmp', 'dictionary_m_words.txt')
urllib.request.urlretrieve('http://bit.ly/2Cbj6zn', DICTIONARY)
def load_dictionary():
"""Load dictionary (sample) and return as generator (done)"""
with open(DICTIONARY) as f:
return (word.lower().strip() for word in f.readlines())
def is_palindrome(word):
"""Return if word is palindrome, 'madam' would be one.
Case insensitive, so Madam is valid too.
It should work for phrases too so strip all but alphanumeric chars.
So "No 'x' in 'Nixon'" should pass (see tests for more)"""
word = word.lower()
# remove anything other than alphanumeric
word = ''.join(filter(str.isalnum, word))
reverse_word = ''.join(reversed(word))
return word == reverse_word
def get_longest_palindrome(words=None):
"""Given a list of words return the longest palindrome
If called without argument use the load_dictionary helper
to populate the words list"""
if not words:
words = load_dictionary()
only_palins = filter(is_palindrome, words)
word_by_length = {word : len(word) for word in only_palins}
return sorted(word_by_length, key=word_by_length.get, reverse=True)[0]
| true |
2a482264dc15fc4c17fc27e08d9247351e47815a | chinmaygiri007/Machine-Learning-Repository | /Part 2 - Regression/Section 6 - Polynomial Regression/Polynomial_Regression_Demo.py | 1,317 | 4.25 | 4 | #Creating the model using Polynomial Regression and fit the data and Visualize the data.
#Check out the difference between Linear and Polynomial Regression
#Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the data
data = pd.read_csv("Position_Salaries.csv")
X = data.iloc[:,1].values.reshape(-1,1)
Y = data.iloc[:,2].values
#Since the data is too small no need to Split the data.
#Importing Linear Regression and training the model
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,Y)
#Visualizing the data(Linearly)
plt.scatter(X,Y,color="gray")
plt.plot(X,lin_reg.predict(X),color = "black")
plt.xlabel("Level")
plt.ylabel("Salary")
plt.title("Linear Regression")
plt.show()
#Implement Polynomial Features
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 5)
X_reg = poly_reg.fit_transform(X)
pol_reg = LinearRegression()
pol_reg.fit(X_reg, Y)
#Visualizing the data(Poly)
X_grid = np.arange(min(X),max(X),0.1)
X_grid = X_grid.reshape((len(X_grid),1))
plt.scatter(X,Y,color = "black")
plt.plot(X_grid,pol_reg.predict(poly_reg.fit_transform(X_grid)),color="black")
plt.show()
#Testing the Model
print(pol_reg.predict(poly_reg.fit_transform([[5.5]]).reshape(1,-1)))
| true |
96d90ae34f7e20c90adcc4637b04bdd885aa6865 | HimanshuKanojiya/Codewar-Challenges | /Disemvowel Trolls.py | 427 | 4.28125 | 4 | def disemvowel(string):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for items in vowels:
if items in string:
cur = string.replace(items,"") #it will replace the vowel with blank
string = cur #after completing the operation, it will update the current string
else:
continue #if vomel not find in string then it will continue the program
return string
| true |
7d1547f6d3d93fc3253321c5edd6509165493910 | JCarter111/Python-kata-practice | /Square_digits.py | 2,368 | 4.46875 | 4 | # Kata practice from codewars
# https://www.codewars.com/kata/546e2562b03326a88e000020/train/python
# Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
# codewars Kata for me to use in practising list comprehension type Python statements
import unittest
def square_digits(num):
# find square of every integer in num
# return these as an integer
# e.g. num = 823, return 1649
# placeholder pass
# number must be an integer
# integer number could be negative
# if number is not an integer
# raise an error
# note Boolean value for number is interpreted as 0 or 1
# but can cause code failure
# raise error if Boolean value provided
if not(isinstance(num,int)) or isinstance(num,bool):
raise TypeError("Please provide an integer number")
# num is an integer, convert to list or string
# use list of string to find every square value
squares = int("".join([str(int(x)**2) for x in str(num)]))
return squares
class squareDigits(unittest.TestCase):
# tests from kata
# test.assert_equals(square_digits(9119), 811181)
# test square is returned for one integer
def test_one_integer_square_returned(self):
self.assertEqual(square_digits(2),4)
# test larger integer returns squares
def test_integer_returns_squares(self):
self.assertEqual(square_digits(9119),811181)
# test what happens if num is larger than the maximum integer values
#def test_large_number_returns_squares(self):
# self.assertEqual(square_digits(21574864912),412549166436168114)
# error handling tests
# test that an error is raised if a non-integer number is
# provided
def test_noninteger_raises_error(self):
with self.assertRaises(TypeError):
square_digits(9.5)
with self.assertRaises(TypeError):
square_digits("hello")
with self.assertRaises(TypeError):
square_digits([6,7])
with self.assertRaises(TypeError):
square_digits(True)
#with self.assertRaises(TypeError):
# square_digits(2323232323231212312312424)
if __name__ == "__main__":
unittest.main() | true |
5280f17272181f7eb09eef6b47e975e8bb8b7063 | katgzco/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 860 | 4.15625 | 4 | #!/usr/bin/python3
"""
Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
"""
max_integer return the max integer of a list
"""
class TestMaxInteger(unittest.TestCase):
def test_integer(self):
"Test numbers cases"
self.assertEqual(max_integer([7, 4, 5, 6, 2]), 7)
self.assertEqual(max_integer([2, 4, 200, 6, 7]), 200)
self.assertEqual(max_integer([-2, -4, -5, -100, 0]), 0)
self.assertEqual(max_integer([2.3, 4.6, 5.3, 6, 32.3]), 32.3)
self.assertEqual(max_integer([45]), 45)
def test_void(self):
"Test empty"
self.assertEqual(max_integer([]), None)
def test_raise(self):
"Test error cases"
self.assertRaises(TypeError, max_integer, None)
self.assertRaises(TypeError, max_integer, {2, 8, 9})
| false |
bd3af2c85a29e8f785fc9f53d8370ca5b95cb1ee | ckkhandare/mini_python_part2 | /City&tree.py | 1,767 | 4.21875 | 4 | dict1={}
while True:
print(''' 1. Add new city and trees commonly found in the city.\n
2. Display all cities and the list of trees for all cities.\n
3. Display list of trees of a particular city.\n
4. Display cities which have the given tree.\n
5. Delete city\n
6. Modify tree list\n
7. Exit\n''')
choice=int(input("enter choice: "))
if choice==1:
city=input("enter city name: ")
if city in dict1:
print("city already exists")
tree = [item for item in input("Enter the tree items : ").split()]
dict1[city]=dict1[city]+tree
else:
tree = [item for item in input("Enter the tree items : ").split()]
dict1[city]=tree
elif choice==2:
print(dict1)
elif choice==3:
city=input('enter person name: ')
if city in dict1:
print(city,':',dict1[city])
else:
print('city does not exist')
elif choice==4:
for city in dict1:
if (dict1[city]!=[]):
print(city)
elif choice==5:
city=input('enter person name: ')
if city in dict1:
print(city,' will be permanently deleted')
conf=input('type y to continue and n to cancel: ')
if conf=='y':
del(dict1[city])
print('item deleted')
else:
print('item not deleted')
else:
print('city does not exist')
elif choice==6:
city=input("enter city name: ")
if city in dict1:
print("city already exists")
tree = [item for item in input("Enter the tree items : ").split()]
dict1[city]=dict1[city]+tree
else:
tree = [item for item in input("Enter the tree items : ").split()]
dict1[city]=tree
elif choice==7:
break
else:
print("invalid choice")
| false |
2d4ae931777f45b7bb6a1b549d838bf6b37ab4eb | LuciRamos/python | /pep8.py | 928 | 4.15625 | 4 | """
PEP 8
São propostas de melhorias para a linguagem Python
A ideia da PEP8 é que possamos escrever códigos Python de forma Pythônica.
[1] - Utilize Camel Case para nomes de classes; - Iniciais maiusculas e sem
[2] - Utilize nomes em minusculo, separados por underline para funções ou variáveis
[3] - Utilize 4 espaços para identação!
[4] - linhas em brancos
-Separar funções e definições de classes com duas linhas em brancos
-Método dentro de uma classe devem ser separados com uma única linha em branco
[5] - imports devem ser sempre feitos em linhas separadas;
import errado
import sys,os
import certo
import sys
import os
Imports deve ser colocados no topo do arquivo, logo depois de quaiquer comentário ou docstringos e
antes de constantes ou variáveis globais
[6] - Espaços em expressções e instruções
[7] - termine sempre uma instrução sempre com uma nova linha
"""
| false |
fc22ede62dbfff1d6ad38bc27c353d41def148fe | Talw3g/pytoolbox | /src/pytoolbox_talw3g/confirm.py | 1,356 | 4.5 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def confirm(question, default_choice='yes'):
"""
Adds available choices indicator at the end of 'question',
and returns True for 'yes' and False for 'no'.
If answer is empty, falls back to specified 'default_choice'.
PARAMETERS:
- question is mandatory, and must be convertible to str.
- default_choice is optional and can be:
| None: no preference given, user must enter yes or no
| 'yes'
| 'no'
If no valid input is found, it loops until it founds a suitable answer.
Exception handling is at the charge of the caller.
"""
valid = {'yes':True, 'y':True, 'ye':True, 'no':False, 'n':False}
default_choice = str(default_choice).lower()
if default_choice == 'none':
prompt = ' [y/n] '
elif default_choice == 'yes':
prompt = ' [Y/n] '
elif default_choice == 'no':
prompt = ' [y/N] '
else:
raise ValueError('invalid default answer: "%s"' % default_choice)
while True:
print(str(question) + prompt)
choice = input().lower()
if default_choice != 'none' and choice == '':
return valid[default_choice]
elif choice in valid:
return valid[choice]
else:
print("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
| true |
e7d9e99375459e1031bf9dd0c2059421978ef31b | KartikeyParashar/Algorithm-Programs | /calendar.py | 1,434 | 4.28125 | 4 | # To the Util Class add dayOfWeek static function that takes a date as input and
# prints the day of the week that date falls on. Your program should take three
# commandline arguments: m (month), d (day), and y (year). For m use 1 for January,
# 2 for February, and so forth. For output print 0 for Sunday, 1 for Monday, 2 for
# Tuesday, and so forth. Use the following formulas, for the Gregorian calendar (where
# / denotes integer division):
# y0 = y − (14 − m) / 12
# x = y0 + y0/4 − y0/100 + y0/400
# m0 = m + 12 × ((14 − m) / 12) − 2
# d0 = (d + x + 31m0/ 12) mod 7
month = int(input("Enter Month in integer(1 to 12): "))
date = int(input("Enter the Date: "))
year = int(input("Enter the year: "))
class Calendar:
def __init__(self,month,day,year):
self.month = month
self.day = day
self.year = year
def dayOfWeek(self):
y = self.year - (14-self.month)//12
x = y + y//4 - y//100 + y//400
m = self.month + 12*((14 - self.month)//12)-2
d = (self.day + x + 31*m//12)%7
return d
day = Calendar(month,date,year)
if day.dayOfWeek()==0:
print("Sunday")
elif day.dayOfWeek()==1:
print("Monday")
elif day.dayOfWeek()==2:
print("Tuesday")
elif day.dayOfWeek()==3:
print("Wednesday")
elif day.dayOfWeek()==4:
print("Thursday")
elif day.dayOfWeek()==5:
print("Friday")
elif day.dayOfWeek()==6:
print("Saturday")
| true |
b59b0b070037764fc71912183e64d047c53f9cf1 | aruntonic/algorithms | /dynamic_programming/tower_of_hanoi.py | 917 | 4.375 | 4 | def tower_of_hanoi(n, source, buffer, dest):
'''
In the classic problem of the wers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.
The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.
Write a program to move the disks from the first tower to the last using stacks.
'''
if n <= 0 :
return
tower_of_hanoi(n-1, source, dest, buffer)
dest.append(source.pop())
tower_of_hanoi(n-1, buffer, source, dest)
if __name__ == '__main__':
source = [5, 4, 3, 2, 1]
buffer = []
dest = []
print(source, buffer, dest)
tower_of_hanoi(5, source, buffer, dest)
print(source, buffer, dest)
| true |
f9f3819c0cacfd8d0aba22d64628ab343e94b5b7 | amulyadhupad/My-Python-practice | /square.py | 202 | 4.15625 | 4 | """ Code to print square of the given number"""
def square(num):
res =int(num) * int(num)
return res
num=input("Enter a number")
ans=square(num)
print("square of "+str(num)+" "+"is:"+str(ans)) | true |
e35bf120762ef57b77799846b2150a86de16c3de | robertyoung1993/Tester_home | /Basing/record_error.py | 766 | 4.21875 | 4 | """
记录错误
内置logging模块可以非常容易的记录错误信息
"""
import logging
# def foo(s):
# return 10 / int(s)
#
# def bar(s):
# return foo(s) * 2
#
# def main():
# try:
# bar('0')
# except Exception as e:
# logging.exception(e)
#
# main()
# print('END')
"""
抛出错误
"""
class FooError(ValueError):
pass
def fooo(s):
n = int(s)
if n == 0:
raise ValueError('invalid value: %s ' % s)
return 10 / n
def bar():
try:
fooo('0')
except ValueError as e:
print('ValueError!')
raise
bar()
# raise语句如果不带参数,就会把当前错误原样抛出。此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型
| false |
c93c2c8f1a4a7a0a2d8a69ad312ea8c06dc54446 | tuanvp10/eng88_python_oop | /animal.py | 555 | 4.25 | 4 | # Create animal class via animal file
class Animal:
def __init__(self): # self refers to this class
self.alive = True
self.spine = True
self.eyes = True
self.lungs = True
def breath(self):
return "Keep breathing to stay alive"
def eat(self):
return "Nom nom nom nom!"
def move(self):
return "Moving all around the world"
# Create a object of our Animal class
# cat = Animal() # Creating a object of our Animal class = cat
# print(cat.breath()) # Breathing for cat is abstracted | true |
617b0b81f3c5ca52ec255b528b15d6862aa34f52 | maria-gabriely/Maria-Gabriely-POO-IFCE-INFO-P7 | /Presença/Atividade 02/Lista_Encadeada.py | 227 | 4.25 | 4 | # 3) Lista Encadeada (A retirada e a inserção de elementos se faz em qualquer posição da Lista).
Lista3 = [1,2,3,4,'a','c','d']
print(Lista3)
x = 'b'
Lista3.insert(5,x)
print(Lista3)
Lista3.pop(2)
print(Lista3)
| false |
a6a9ca58f31c8161792d2c6ce7a73f1318bc8589 | diegocolombo1989/Trabalho-Python | /Aula20/exercicios/Resolução/exercicio1.py | 2,183 | 4.28125 | 4 | # Aula 20 - 05-12-2019
# Lista com for e metodos
# Com esta lista:
lista = [
['codigo','produto','valor','quantidade'],
[1,'Cevada',15.00,10],
[2,'Lupulo',150.50,200],
[3,'Malte',57.80,5000],
[4,'Levedura 1',10.65,500],
[5,'Extrato de Levedura',15.00,60],
[6,'Levedura 2',15.50,87]
]
# 2.1 - Faça uma função que pegue esta lista e retorne uma lista com biblioteca.
# 2.2 - Faça outra função para consultar o preço através do código passado
# por parametro. Esta função deve printar o nome do produto, a quantidade
# e o preço.
# Execute esta função dentro do while e quando digitar qualquer código que
# não tenha produto cadastrado o programa se encerra.
#
# ###############Procurar e reconhecer padrão!
# lista[0][0] : lista[1][0] codigo : 1
# lista[0][1] : lista[1][1] produto : cevada
# lista[0][2] : lista[1][2] valor : 15.00
# lista[0][3] : lista[1][3] quantidade : 10
# lista[0][0] : lista[2][0] codigo : 2
# lista[0][1] : lista[2][1] produto : lupulo
# lista[0][2] : lista[2][2] valor : 150.50
# lista[0][3] : lista[2][3] quantidade : 200
# lista[0][rapido] : lista[lento][rapido]
# ################################################
def lista_biblioteca(lista):
lista_bibl = []
for lento in range ( len(lista[1:]) ):
biblioteca = {}
for rapido in range( len(lista[0]) ):
biblioteca[ lista[0][rapido]] = lista[lento+1][rapido]
lista_bibl.append(biblioteca)
return lista_bibl
def consulta(lista,codigo):
for produto in lista:
if int(produto['codigo']) == codigo:
print(f"\nNome do produto: {produto['produto']}\n"
f"Quantidade em estoque: {produto['quantidade']}\n"
f"Preço: R$ {produto['valor']:.2f}\n")
return True
return False
lista1 = lista_biblioteca(lista)
sair = True
while sair:
codigo = int(input('Digite o código produto: '))
sair = consulta(lista1,codigo) | false |
0acbad19ec29c8ce0e13d9d44eff09759e921be0 | Patrick-J-Close/Introduction_to_Python_RiceU | /rpsls.py | 1,779 | 4.1875 | 4 | # Intro to Python course project 1: rock, paper, scissors, lizard, Spock
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# where each value beats the two prior values and beats the two following values
import random
def name_to_number(name):
# convert string input to integer value
if name == "rock":
number = 0
elif name == "Spock":
number = 1
elif name == "paper":
number = 2
elif name == "lizard":
number = 3
elif name == "scissors":
number = 4
else:
print("You did not enter a valid name")
return(number)
def number_to_name(number):
# convert integer input to string
if number == 0:
name = "rock"
elif number ==1:
name = "Spock"
elif number == 2:
name = "paper"
elif number == 3:
name = "lizard"
elif number == 4:
name = "scissors"
else:
print("a valid number was not given")
return(name)
def rpsls(player_choice):
# master function
#print a blank line to seperate consecutive games
print("")
# print player's choice
print("Player chooses", player_choice)
# convert player's choice to number
player_val = name_to_number(player_choice)
# compute random result
comp_val = random.randrange(0,5)
# convert comp_val from integer to sting and print
comp_choice = number_to_name(comp_val)
print("Computer chooses", comp_choice)
# determine winner
dif = (player_val - comp_val) % 5
if dif == 0:
print("It's a draw!")
elif dif == 1 or dif == 2:
print ("Player wins!")
elif dif == 3 or dif ==4:
print("Compuer wins!")
rpsls("rock")
rpsls("paper")
rpsls("scissors")
rpsls("lizard")
rpsls("Spock")
| true |
ee8ff8648e324b2ca1c66c4c030a68c816af1464 | Merrycheeza/CS3130 | /LabAss2/LabAss2.py | 1,331 | 4.34375 | 4 | ###################################
# #
# Class: CS3130 #
# Assignment: Lab Assignment 2 #
# Author: Samara Drewe #
# 4921860 #
# #
###################################
#!/usr/bin/env python3
import sys, re
running = True
# prints the menu
print("--")
print("Phone Number ")
print(" ")
while(running):
# asks for the number
print("Enter phone number: ", end = "")
phone = input()
# checks to see if it's a blank line
if(phone == ""):
running = False
break
else:
#takes out the parenthesis and spaces
phone1 = re.sub('[\s+\(\)]', '', phone)
# checks the length, if it is lesser or greater than 10 digits, it's not a phone number
if len(phone1) == 10:
# checks length again after taking out everything that isn't a number
if(len(re.sub('[^0-9]',"", phone1)) == 10):
print("Number is " + "(" + phone1[0:3] + ")" + " " + phone1[3:6] + " " + phone1[6:])
# if it is not 10 digits, there were characters that were not numbers in the phone number
else:
print("Characters other than digits, hypens, space and parantheses detected")
# length not 10 digits, not a phone number
else:
print("Sorry phone number needs exactly 10 digits")
print("--")
| true |
30e22c55bb0fe9bd5221270053564adbe4d83932 | ine-rmotr-projects/INE-Fractal | /mandelbrot.py | 854 | 4.21875 | 4 | def mandelbrot(z0:complex, orbits:int=255) -> int:
"""Find the escape orbit of points under Mandelbrot iteration
# If z0 isn't coercible to complex, TypeError
>>> mandelbrot('X')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/davidmertz/git/INE/unittest/01-Doctest/mandelbrot1.py", line 4, in mandelbrot
if abs(z) > 2.0:
TypeError: bad operand type for abs(): 'str'
# Orbits must be integer. Traceback abbreviated below
>>> mandelbrot(0.0965-0.638j, orbits=3.1)
Traceback (most recent call last):
TypeError: 'float' object cannot be interpreted as an integer
"""
z = z0
for n in range(orbits):
if abs(z) > 2.0:
return n
z = z * z + z0
return orbits
if __name__ == '__main__':
import doctest; doctest.testmod()
| true |
257f2d67b700463e128b2251d285e8ce53065b6f | bharath210/PythonLearning | /Assignments/FibonacciDemo.py | 388 | 4.15625 | 4 |
def fibb(n):
num1 = 0;
num2 = 1;
temp =0
if(n == 1):
print(num1)
else:
print(num1)
print(num2)
for i in range(2,n):
num3 = num2 + num1
# if n <= num3:
# break
print(num3)
temp = num3
num1 = num2
num2 = num3
x = int(input("Enter a number"))
fibb(x) | false |
0d24827c20ed97cbdf445f2691554cac1b99f8c8 | naochaLuwang/Candy-Vending-Machine | /tuto.py | 1,288 | 4.25 | 4 | # program to mimic a candy vending machine
# suppose that there are five candies in the vending machine but the customer wants six
# display that the vending machine is short of 1 candy
# And if the customer wants the available candy, give it to the customer else ask for another number of candy.
av = 5
x = int(input("Enter the number of candies you want: "))
for i in range(x):
if x > av:
remain = x - av
print("Total number of candies available is ", av)
print("We are short of ", remain, 'candies')
if remain != 0:
total = x - remain
print("Do you want", total, 'candies instead?')
ans = input("Enter yes/no: ")
if ans == 'yes':
for j in range(total):
print("Candy")
elif ans == 'no':
print("Do you want to continue or quit?")
choose = input("Enter 'C' to Continue or 'Q' to Quit: ")
if choose == 'C':
ans1 = int(input("Enter the number of Candies you want: "))
for k in range(ans1):
print("Candy")
else:
break
break
else:
print("candy")
print("Thank you for shopping with us. :)")
| true |
789ac887653860972e9788eb9bc2d7c4e6064abc | Sajneen-Munmun720/Python-Exercises | /Calculating the number of upper case and lower case letter in a sentence.py | 432 | 4.1875 | 4 | def case_testing(string):
d={"Upper_case":0,"Lower_case":0}
for items in string:
if items.isupper():
d["Upper_case"]+=1
elif items.islower():
d["Lower_case"]+=1
else:
pass
print("Number of upper case is:",d["Upper_case"])
print("Number of lower case is:", d["Lower_case"])
sentence=input("Enter a Sentence:")
case_letters=case_testing(sentence) | true |
edf7b53def0fffcecef3b00e4ea67464ba330d9c | Malcolm-Tompkins/ICS3U-Unit5-06-Python-Lists | /lists.py | 996 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on June 2, 2021
# Rounds off decimal numbers
def round_off_decimal(user_decimals, number_var):
final_digit = ((number_var[0] * (10 ** user_decimals)) + 0.5)
return final_digit
def main():
number_var = []
user_input1 = (input("Enter your decimal number: "))
try:
user_number = float(user_input1)
user_input2 = (input("Round how many decimals off: "))
try:
user_decimals = int(user_input2)
number_var.append(user_number)
round_off_decimal(user_decimals, number_var)
final_number = int
final_number = round_off_decimal(user_decimals, number_var)
print(final_number)
except Exception:
print("{} is not a positive integer".format(user_input2))
except Exception:
print("{} is not a decimal number".format(user_input1))
finally:
print("Done.")
if __name__ == "__main__":
main()
| true |
27b85920a9a7d8d9c2b42f5d3227ffb3f48acda8 | jorgegarba/CodiGo9 | /BackEnd/Semana4/Dia3/09-listas.py | 488 | 4.15625 | 4 | nombres = ["Juan","Jorge","Raul","Eusebio","Christian",100]
nombre = "Eusebio"
# para saber si el nombre esta en nuestro arreglo nombres
print(nombre in nombres)
# Buscar un nombre en esa lista
# for (let i = 0; i< nombres.lenght; i++){
# console.log(nombres[i])
# }
# Por cada nombrecito en nuestra lista nombres, enseñame el nombrecito
for nombrecito in nombres:
print(nombrecito)
print(nombre)
# for(let i=0; i<10; i++){
# console.log(i)
# }
for i in range(0,10):
print(i) | false |
3e78ea8629c13cefe4fdcbf42f475eb4da525b2a | vladbochok/university-tasks | /c1s1/labwork-2.py | 1,792 | 4.21875 | 4 | """
This module is designed to calculate function S value with given
accuracy at given point.
Functions:
s - return value of function S
Global arguments:
a, b - set the domain of S
"""
from math import fabs
a = -1
b = 1
def s(x: float, eps: float) -> float:
"""Return value of S at given point x with given accuracy - eps
Arguments:
x - should be real number at least -1 and at most 1.
eps - should be real number greater 0.
Don’t check if eps is positive number. If not so, do infinite loop.
For non relevant x the result may be inaccurate.
"""
el = x * x / 2
sum = 0
k = 0
x4 = -x * x * x * x
while fabs(el) >= eps:
sum += el
el *= x4 / ((4 * k + 3) * (4 * k + 4) * (4 * k + 5) * (4 * k + 6))
k += 1
sum += el
return sum
print("Variant №3", "Vladyslav Bochok", sep="\n")
print("Calculating the value of the function S with given accuracy")
try:
x = float(input(f"Input x - real number in the range from {a} to {b}: "))
eps = float(input("Input eps - real positive number: "))
# Check arguments for domain, calculate S, output
if a <= x <= b and eps > 0:
print("***** do calculations ...", end=" ")
result = s(x, eps)
print("done")
print(f"for x = {x:.6f}", f"for eps = {eps:.4E}", f"result = {result:.8f}", sep="\n")
else:
print("***** Error")
# Check x ans eps for domain, print error description
if x < a or x > b:
print(f"if x = {x:.6f} then S is not convergence to function F")
if eps <= 0:
print("The calculation cannot be performed if eps is not greater than zero. ")
except ValueError or KeyboardInterrupt:
print("***** Error", "Wrong input: x and eps should be float", sep="\n")
| true |
6f0bc83046ec214818b9b8cc6bc5962a5d819977 | thivatm/Hello-world | /Python/Counting the occurence of each word.py | 223 | 4.21875 | 4 | string=input("Enter string:").split(" ")
word=input("Enter word:")
from collections import Counter
word_count=Counter(string)
print(word_count)
final_count=word_count[word]
print("Count of the word is:")
print(final_count)
| true |
0cb00f6f4798c9bc5770f04b8a2a09cb0e3f0c43 | ssavann/Python-Data-Type | /MathOperation.py | 283 | 4.25 | 4 | #Mathematical operators
print(3 + 5) #addition
print(7 - 4) #substraction
print(3 * 2) #multiplication
print(6 / 3) #division will always be "Float" not integer
print(2**4) #power: 2 power of 4 = 16
print((3 * 3) + (3 / 3) - 3) #7.0
print(3 * (3 + 3) / 3 - 3) #3.0
| true |
c54d75b36108590ba19569ae24f6b72fd13b628b | Alankar-98/MWB_Python | /Functions.py | 239 | 4.15625 | 4 | # def basic_function():
# return "Hello World"
# print(basic_function())
def hour_to_mins(hour):
mins = hour * 60
return mins
print(hour_to_mins(float(input("Enter how many hour(s) you want to convert into mins: \n")))) | true |
ce788f6c65b9b8c4e3c47585b7024d2951b59d19 | GLARISHILDA/07-08-2021 | /cd_abstract_file_system.py | 928 | 4.15625 | 4 | # Write a function that provides a change directory (cd) function for an abstract file system.
class Path:
def __init__(self, path):
self.current_path = path # Current path
def cd(self, new_path): # cd function
parent = '..'
separator = '/'
# Absolute path
change_list = self.current_path.split(separator)
new_list = new_path.split(separator)
# Relative path
for item in new_list:
if item == parent:
#delete the last item in list
del change_list[-1]
else:
change_list.append(item)
# Add "/" before each item in the list and print as string
self.current_path = "/".join(change_list)
return self.current_path
path = Path('/a/b/c/d')
path.cd('../x')
print(path.current_path) | true |
a84755fd8627c33535f669980de25c072e0a3c83 | sandeshsonje/Machine_test | /First_Question.py | 555 | 4.21875 | 4 | '''1. Write a program which takes 2 digits, X,Y as input and generates a
2-dimensional array.
Example:
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Note: Values inside array can be any.(it's up to candidate)'''
row = int(input("Enter number of rows = "))
col = int(input("Enter number of cols = "))
arr=[]
for i in range(0,row):
arr1=[]
for j in range(0,col):
arr1.append(i*j)
arr.append(arr1)
print(arr)
| true |
f5e7a155de761f83f9ad7b8293bc5c81edda3f1f | Luciekimotho/datastructures-and-algorithms | /MSFT/stack.py | 821 | 4.1875 | 4 | #implementation using array
#class Stack:
# def __init__(self):
# self.items = []
# def push(self, item):
# self.items.append(item)
# def pop(self):
# return self.items.pop()
#implementation using lists
class Stack:
def __init__(self):
self.stack = list()
#insertion -> append item to the stack list
def push(self, item):
self.stack.append(item)
#delete -> pop item on the top of the stack, returns this item
def pop(self):
return self.stack.pop()
#return length of stack
def size(self):
return len(self.stack)
#initialize stack
s = Stack()
#adding items to the stack
s.push(56)
s.push(45)
s.push(34)
#Checking for size before and after the pop
print(s.size())
print(s.pop())
print(s.size())
| true |
eab5e0186698af32d9301abf155e1d0af25e5f6f | jzamora5/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 647 | 4.1875 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
"""
In a text file, there is a single character H. Your text editor can execute
only two operations in this file: Copy All and Paste. Given a number n,
write a method that calculates the fewest number of operations needed to
result in exactly n H characters in the file.
Returns an integer
If n is impossible to achieve, returns 0
"""
if not isinstance(n, int):
return 0
op = 0
i = 2
while (i <= n):
if not (n % i):
n = int(n / i)
op += i
i = 1
i += 1
return op
| true |
746c24e8e59f8f85af4414d5832f0ec1bf9a4f7c | joeblackwaslike/codingbat | /recursion-1/powerN.py | 443 | 4.25 | 4 | """
powerN
Given base and n that are both 1 or more, compute recursively (no loops) the
value of base to the n power, so powerN(3, 2) is 9 (3 squared).
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
"""
def powerN(base, n):
if n == 1:
return base
else:
return base * powerN(base, n - 1)
if __name__ == "__main__":
for base, n in [(3, 1), (3, 2), (3, 3)]:
print((base, n), powerN(base, n))
| true |
2bf855bce42dcf61cee814e5f33825db0913a26b | LingChenBill/python_first_introduce | /head_first_python/ch01/05_07_1_list_solving.py | 1,589 | 4.1875 | 4 | fav_movies = ["The Holy Grail", "The life of Brian"]
print(fav_movies)
print(fav_movies[0])
print(fav_movies[1])
print("For 迭代列表:")
for each_flick in fav_movies:
print(each_flick)
# 列表处理代码被称为“组”
print("也可考虑用while循环迭代:")
count = 0
while count < len(fav_movies):
print(fav_movies[count])
count = count + 1
print("列表内嵌列表:")
movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,
["Graham Chapman",
["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]]
print(movies)
print(movies[4][1][3])
print("遍历内嵌列表:")
for each_item in movies:
print(each_item)
print("检查某个特定标识符:")
names = ['Michael', 'Terry']
print(isinstance(names, list))
num_names = len(names)
print(isinstance(num_names, list))
print("遍历内嵌列表-判断是否内嵌列表一:")
for each_item in movies:
if isinstance(each_item, list):
for item in each_item:
print(item)
else:
print(each_item)
print("遍历内嵌列表-判断是否内嵌列表二:")
for each_item in movies:
if isinstance(each_item, list):
for item in each_item:
if isinstance(item, list):
for deep_item in item:
print(deep_item)
else:
print(item)
else:
print(each_item)
print("遍历内嵌列表-定义函数三:")
def print_lol(the_list):
for item in the_list:
if isinstance(item, list):
print_lol(item)
else:
print(item)
print_lol(movies)
| false |
d6fb1774f0abf4a7dfacc3630206cc2e8fda883c | shenxiaoxu/leetcode | /questions/1807. Evaluate the Bracket Pairs of a String/evaluate.py | 1,448 | 4.125 | 4 | '''
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:
Replace keyi and the bracket pair with the key's corresponding valuei.
If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?" (without the quotation marks).
Each key will appear at most once in your knowledge. There will not be any nested brackets in s.
Return the resulting string after evaluating all of the bracket pairs.
'''
class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = {k: v for k, v in knowledge}
cur = ''
ongoing = False
res = []
for c in s:
if c == '(':
ongoing = True
elif c == ')':
ongoing = False
res.append(d.get(cur,'?'))
cur = ''
elif ongoing:
cur+=c
else:
res.append(c)
return ''.join(res)
| true |
7902a7ed39635064d0e3e93aa1a0a24e1ac4a625 | nikonst/Python | /OOP/oop1.py | 1,247 | 4.125 | 4 | # OOP Basic Concepts
class Person:
species = "Human" # Class field
def __init__(self, name, gender):
self.name = name
self.gender = gender
def introduceYourself(self):
print("Hi! My name is ", self.name)
def myFavouriteMovie(self):
print("Terminator I")
class Employee(Person): # Inheritance
def __init__(self, name,gender,profession):
super().__init__(name, gender)
self.profession = profession
self.__salary = 1000 # Encapsulation
def sayProfession(self):
print("I am a ", self.profession)
def showSalary(self):
print("My salary is ", self.__salary)
def myFavouriteMovie(self): # Polymorphism
print("Terminator II")
def showFavouritMovie(p):
p.myFavouriteMovie()
p1 = Person("Mary","female")
p1.introduceYourself()
p2 = Employee("Nick","Male","Carpenter")
p2.introduceYourself()
p2.sayProfession()
print("----------------------")
print(p1.name)
#print(p2.__salary) # salary is a private field
p2.showSalary()
print("----------------------")
print(p1.species)
print(p2.species)
print("----------------------")
showFavouritMovie(p1)
showFavouritMovie(p2)
| false |
bfe9ecfe1e7c5e04be74a9ad86e0deed0535063e | nikonst/Python | /Core/lists/big_diff.py | 691 | 4.125 | 4 | '''
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) - 7
big_diff([7, 2, 10, 9]) - 8
big_diff([2, 10, 7, 2]) - 8
'''
import random
def b_diff(nums):
if len(nums) == 1:
diff = nums[0]
else:
diff = max(nums) - min(nums)
return diff
theList = []
listSize = random.randint(1,20)
for i in range(0,listSize):
theList.append(random.randint(0, 100))
print 'Size of list ', listSize,' The List : ',theList
print 'Big Difference: ',b_diff(theList) | true |
29dc483eabdfada41277bd0879d4d30db4c5e9e1 | nikonst/Python | /Core/lists/centered_average.py | 859 | 4.21875 | 4 | '''
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value. Use int division to produce the final average.
You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) - 3
centered_average([1, 1, 5, 5, 10, 8, 7]) - 5
centered_average([-10, -4, -2, -4, -2, 0]) - -3
'''
import random
def cent_avg(aList):
return (sum(aList) - min(aList) - max(aList)) / len(list)
list = []
listSize = random.randint(3,20)
for i in range(0,listSize):
list.append(random.randint(1,100))
print 'The Size of List is :', listSize
print 'The List : ', list
print 'Centered Averege = ', cent_avg(list)
| true |
e924c76da60630526344873dfd5523c3bf9bec7d | nikonst/Python | /Core/lists/max_end3.py | 792 | 4.40625 | 4 | '''
Given an array of ints length 3, figure out which is larger, the first or last element in the array,
and set all the other elements to be that value. Return the changed array.
max_end3([1, 2, 3]) - [3, 3, 3]
max_end3([11, 5, 9]) - [11, 11, 11]
max_end3([2, 11, 3]) - [3, 3, 3]
'''
def maxEnd3(nums):
newList = []
print '***', nums[len(nums)-1]
if nums[0] >= nums[len(nums)-1]:
for i in range(0,len(nums)):
newList.append(nums[0])
else:
for i in range(0,len(nums)):
newList.append(nums[len(nums)-1])
return newList
list =[]
x = input('Enter list number (0 - Stop) > ')
while x != 0:
list.append(x)
x = input('Enter list number (0 - Stop) > ')
print list
list = maxEnd3(list)
print list
| true |
2dde45ecac9827dc9804a3d4277054bb07e5be02 | Vaishnavi-cyber-blip/LEarnPython | /Online library management system.py | 1,658 | 4.1875 | 4 | class Library:
def __init__(self, list_of_books, library_name):
self.library_name = library_name
self.list_of_books = list_of_books
def display_books(self):
print(f"Library name is {self.library_name}")
print(f"Here is the list of books we provide:{self.list_of_books}")
def add_book(self):
print("Name of book?")
book = input().capitalize()
self.list_of_books.append(book)
print("Awesome! Here we have a new source of knowledge")
print(self.list_of_books)
def lend_book(self):
print("Enter your name:")
name = input()
# d1 = {}
print("Which book you want to lend?")
book = input().lower()
if book in self.list_of_books:
print(f"Now {name} is the owner of book: {book}")
self.list_of_books.remove(book)
else:
print("Currently not available")
def return_book(self):
print("Name of the book you want to return")
ham = input()
print("Hope you enjoyed reading!")
self.list_of_books.append(ham)
lst = ["hi", "bi", "mi", "vi"]
obj = Library(lst, "Read_Me")
if __name__ == '__main__':
while True:
print("Enter your requirements Sir/Mam: 1.Show Books[show] "
"2.Lend Books[lend] "
"3.Add Book[add] "
"4.Return Book[return]"
)
need = input().upper()
if need == "SHOW":
obj.display_books()
elif need == "LEND":
obj.lend_book()
elif need == "ADD":
obj.add_book()
else:
obj.return_book()
| true |
22685b80e601c73f188734b3d511d5de29f51708 | VesaKelani/python-exercises | /palindrome.py | 253 | 4.21875 | 4 |
wrd = input("Enter a word: ")
wrd = str(wrd)
rvs = wrd[::-1]
while rvs != wrd:
print("This word is not a palindrome")
wrd = input("Enter a word: ")
wrd = str(wrd)
rvs = wrd[::-1]
if rvs == wrd:
print("This word is a palindrome")
| false |
0d70416d7d6d50d3f69d38ab8bb6878b3e673667 | MarkVarga/python_to_do_list_app | /to_do_list_app.py | 1,819 | 4.21875 | 4 |
data = []
def show_menu():
print('Menu:')
print('1. Add an item')
print('2. Mark as done')
print('3. View items')
print('4. Exit')
def add_items():
item = input('What do you need to do? ')
data.append(item)
print('You have added: ', item)
add_more_items()
def add_more_items():
user_choice = input('Do you want to add anything else? Press Y/N: ')
if user_choice.lower() == 'y':
add_items()
elif user_choice.lower() =='n':
app_on()
elif user_choice.lower() != 'y' or user_choice.lower() != 'n':
print('Invalid choice')
add_more_items()
def remove_items():
item = input('What have you completed? ')
if item in data:
data.remove(item)
print(item, 'has been removed from your list')
remove_more_items()
else:
print('This item does not exist')
app_on()
def remove_more_items():
user_choice = input('Do you want to remove anything else? Press Y/N: ')
if user_choice.lower() == 'y':
remove_items()
elif user_choice.lower() =='n':
app_on()
else:
print('Invalid choice')
remove_more_items()
def show_items():
print('Here is your to-do-list: ')
for item in data:
print(item)
app_on()
def exit_app():
print('Thanks for using the app! See you later!')
def app_on():
show_menu()
user_input = input('Enter your choice: ')
print('You entered:', user_input)
if user_input == '1':
add_items()
elif user_input == '2':
remove_items()
elif user_input == '3':
show_items()
elif user_input == '4':
exit_app()
else:
print('Invalid choice. Please enter 1, 2, 3 or 4')
app_on()
app_on() | true |
ff3ccbf45d3be6f6933f03ec3be4ec8c03c15be1 | j-hmd/daily-python | /Object-Oriented-Python/dataclasses_intro.py | 600 | 4.1875 | 4 | # Data classes make the class definition more concise since python 3.7
# it automates the creation of __init__ with the attributes passed to the
# creation of the object.
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int
price: float
b1 = Book("A Mao e a Luva", "Machado de Assis", 356, 29.99)
b2 = Book("Dom Casmurro", "Machado de Assis", 230, 24.50)
b3 = Book("Capitaes da Areia", "Jorge Amado", 178, 14.50)
# The data class also provides implementations for the __repr__ and __eq__ magic functions
print(b1.title)
print(b2.author)
print(b1 == b2) | true |
975f43786306ca83189c8a7f310bec5b38c1ac84 | Pawan459/infytq-pf-day9 | /medium/Problem_40.py | 1,587 | 4.28125 | 4 | # University of Washington CSE140 Final 2015
# Given a list of lists of integers, write a python function, index_of_max_unique,
# which returns the index of the sub-list which has the most unique values.
# For example:
# index_of_max_unique([[1, 3, 3], [12, 4, 12, 7, 4, 4], [41, 2, 4, 7, 1, 12]])
# would return 2 since the sub-list at index 2 has the most unique values in it(6 unique values).
# index_of_max_unique([[4, 5], [12]])
# would return 0 since the sub-list at index 0 has the most unique values in it(2 unique values).
# You can assume that neither the list_of_lists nor any of its sub-lists will be empty.
# If there is a tie for the max number of unique values between two sub-lists, return the index of the first sub-list encountered(when reading left to right) that has the most unique values.
#PF-Prac-40
#PF-Prac-40
def findUniqueValue(li):
dic = dict()
for i in li:
try:
dic[i] += 1
except:
dic[i] = 1
return len(dic)
def index_of_max_unique(num_list):
#start writing your code here
index = 0
max_len = -1
for i in range(len(num_list)):
unique_values = findUniqueValue(num_list[i])
if max_len < unique_values:
index = i
max_len = unique_values
return index
num_list = [[1, 3, 3], [12, 4, 12, 7, 4, 4],
[41, 2, 4, 7, 1, 12], [1, 2, 3, 4, 5, 6]]
num_list1 = [[4, 5], [12], [3, 8]]
print("Number list:", num_list)
output = index_of_max_unique(num_list)
print("The index of sub list containing maximum unique elements is:", output)
| true |
9105402ce5b6bde25f2f0bc82d8ec5f523b63f17 | matckolck1/cosas | /anida.py | 316 | 4.125 | 4 | for i in range(3):
print ("a")
for j in range(3):
print ("b")
for i in range(2):
print("te quiero")
for m in range(3):
print("mucho")
for i in range(2):
print("te quiero")
for m in range(3):
print("mucho")
for t in range(1):
print("naranja")
| false |
fd86b2ae3b647afb8b1f7a0bcc081a8d7bf380e5 | buribae/is-additive-python | /is_additive.py | 1,143 | 4.15625 | 4 | import sys
import time
def secret(n):
return n+n
def primes_of(n):
"""Uses sieve of Eratosthenes to list prime numbers below input n
Args:
n: Maximum integer representing
Returns:
An array containing all prime numbers below n
Alternative:
Pyprimesieve https://github.com/jaredks/pyprimesieve
"""
if n < 2:
return None
sieve = {i:True for i in range(2,n+1)}
for j in range(2, n+1):
if sieve[j] == True:
m = 2
while j*m <= n:
sieve[j*m] = False
m+=1
return [x for x,y in sieve.items() if y == True]
def is_additive(primes):
"""Checks if secret(x+y) == secret(x) + secret(y) given x,y are prime numbers below n
"""
# Null Check
if primes == None:
return "No prime numbers below your input exist"
f1 = [secret(x)+secret(y) for x in primes for y in primes]
f2 = [secret(x+y) for x in primes for y in primes]
return f1 == f2
if __name__ == "__main__":
# Check argument type
try:
number = int(sys.argv[1])
start = time.time()
print is_additive(primes_of(number))
end = time.time()
print "elapsed %ss" % str(end-start)
except ValueError:
print("Only integer type is accepted") | false |
fa2bb3897975551b93f517e134139139cf29d417 | Dervun/Python-at-Stepik | /2/6.10/6.10.py | 1,416 | 4.3125 | 4 | """
Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк,
заканчивающихся строкой, содержащей только строку "end" (без кавычек).
Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j
равен сумме элементов первой матрицы на позициях (i-1, j), (i+1, j), (i, j-1), (i, j+1).
У крайних символов соседний элемент находится с противоположной стороны матрицы.
В случае одной строки/столбца элемент сам себе является соседом по соответствующему направлению.
"""
temp = input()
read = [] # Вторая форма глагола, прочитанная матрица
while temp != 'end':
read.append([int(i) for i in temp.split()])
temp = input()
length_of_line = len(read[0])
count_of_lines = len(read)
for i in range(count_of_lines):
for j in range(length_of_line):
print(read[i - 1][j] + read[(i + 1) - count_of_lines][j] +
read[i][j - 1] + read[i][(j + 1) - length_of_line], end=' ')
print()
| false |
ef4b1f9b167c368dbd47e7bd9c270db6326bc7af | Dervun/Python-at-Stepik | /1/11.5/11.5.py | 754 | 4.3125 | 4 | '''
Напишите программу, которая получает на вход три целых числа, по одному числу в строке,
и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число.
На ввод могут подаваться и повторяющиеся числа.
'''
arr = sorted([int(input()) for i in range(3)])
print(arr[2], arr[0], arr[1], sep='\n')
#other
'''
a = input()
b = input()
c = input()
arr = sorted([a, b, c])
print(arr[2], arr[0], arr[1], sep='\n')
'''
'''
arr = sorted([int(input()), int(input()), int(input())])
print(arr[2], arr[0], arr[1], sep='\n')
''' | false |
ebb25b6998bf21815faa79944082816c04d95cb0 | sesantanav/python_basics | /poo.py | 1,415 | 4.25 | 4 | # Programación Orientada o Objetos con Python
# Clases
class NuevaClase:
pass
class Persona:
def __init__(self):
self._nombre = ""
self._edad = 0
# Metódods de la clase
# setters
def setNombre(self, nombre):
self._nombre = nombre
def setEdad(self, edad):
self._edad = edad
# getters
def getNombre(self):
return self._nombre
def getEdad(self):
return self._edad
def getInfo(self):
print("Nombre : " + self._nombre )
print("Edad : {e}".format(e=self._edad))
class Estudiante(Persona):
def __init__(self):
Persona.__init__(self)
self.carrera = ""
def setCarrera(self, carrera):
self.carrera = carrera
def getCarrera(self):
return self.carrera
def infoEstudiante(self):
print("El nombre del estudiante es: " + self.getNombre() )
print("La edad del estudiante es: " + self.getEdad())
print("La carrera del estudiante es: " + self.carrera)
persona = Persona()
persona.setEdad(25)
persona.setNombre("Gonzalo")
print("El nombre es: " + persona.getNombre())
nombre = persona.getNombre()
print("Otra forma de obtener el nombre: " + nombre)
print("Nombre de la persona es {n}".format(n=nombre))
estudiante = Estudiante()
estudiante.setNombre("Favio")
estudiante.setEdad(25)
estudiante.getInfo()
estudiante.infoEstudiante()
| false |
1e7f67cd95ecd74857bcc0a2aeb4a45e6b13947d | harshonyou/SOFT1 | /week5/week5_practical4b_5.py | 440 | 4.125 | 4 | '''
Exercise 5:
Write a function to_upper_case(input_file, output_file) that takes two
string parameters containing the name of two text files. The function reads the content of the
input_file and saves it in upper case into the output_file.
'''
def to_upper_case(input_file, output_file):
with open(input_file) as x:
with open(output_file, 'w') as y:
print(x.read().upper(), file=y)
to_upper_case('ayy','exo1.txt') | true |
dd0b87ac56156e3f3f7397395752cd9f57d33972 | harshonyou/SOFT1 | /week7/week7_practical6a_6.py | 1,075 | 4.375 | 4 | '''
Exercise 6:
In Programming, being able to compare objects is important, in particular determining if two
objects are equal or not. Let’s try a comparison of two vectors:
>>> vector1 = Vector([1, 2, 3])
>>> vector2 = Vector([1, 2, 3])
>>> vector1 == vector2
False
>>> vector1 != vector2
True
>>> vector3 = vector1
>>> vector3 == vector1
True
As you can see, in the current state of implementation of our class Vector does not produce the
expected result when comparing two vectors. In the example above the == operator return
True if the two vectors are physically stored at the same memory address, it does not compare
the content of the two vectors.
Therefore, you need to implement a method equals(other_vector) that returns True
if the vectors are equals (i.e. have the same value at the same position), False otherwise.
'''
#Complete Answer Is Within Vector.py
def equal(self, matrix):
if not(isinstance(matrix,Vector)):
return 'TypeError'
if self._vector==matrix._vector:
return True
else:
return False | true |
13138f7e7f105cb917d3c28995502f01ace2c46a | harshonyou/SOFT1 | /week4/week4_practical3_5.py | 829 | 4.25 | 4 | '''
Exercise 5: Where’s that bug!
You have just started your placement, and you are given a piece of code to correct. The aim of
the script is to take a 2D list (that is a list of lists) and print a list containing the sum of each
list. For example, given the list in data, the output should be [6, 2, 10].
Modify the code below such that it gives the right result. In addition, you have been asked to
refactor the script into a function sum_lists(list_2D) that returns the list containing the
sums of each sub-list.
data = [[1,2,3], [2], [1, 2, 3, 4]]
output =[]
total = 0
for row in data:
for val in row:
total += val
output.append(total)
print(output)
'''
data = [[1,2,3], [2], [1, 2, 3, 4]]
output =[]
total = 0
for row in data:
for val in row:
total += val
output.append(total)
total=0
print(output) | true |
7209b64a1bfbca67fa750370a6b2a2f35f04085b | harshonyou/SOFT1 | /week3/week3_ex1_1.py | 870 | 4.125 | 4 | '''
Exercise 1: Simple while loopsExercise 1: Simple while loops
1. Write a program to keep asking for a number until you enter a negative number. At the end, print the sum of all entered numbers.
2. Write a program to keep asking for a number until you enter a negative number. At the end, print the average of all entered numbers.
3. Write a program to keep asking for a number until you enter a negative number. At the end, print the number of even number entered.
'''
Sum=0
total=0
evens=0
def printEXIT(a,b,c):
print("Sum of all the number entered:",a)
print("Average of all the number entered:",b)
print("Number of even number entered:",c)
exit()
while True:
x=input("Enter A Number: ")
total+=1
print("You have entered:", x if float(x)>=0 else printEXIT(Sum,Sum/total,evens))
Sum+=float(x)
evens+=1 if float(x)%2==0 else 0 | true |
ae485d7078b0a130d25f508fa3bbf2654b288fbd | carlosberrio/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/4-append_write.py | 312 | 4.34375 | 4 | #!/usr/bin/python3
"""Module for append_write method"""
def append_write(filename="", text=""):
"""appends a string <text> at the end of a text file (UTF8) <filename>
and returns the number of characters added:"""
with open(filename, 'a', encoding='utf-8') as file:
return file.write(text)
| true |
129c7dfb7e4704916d6a3c70c7b88de3f4ee5ab4 | carlosberrio/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,673 | 4.3125 | 4 | #!/usr/bin/python3
""" Module for matrix_divided method"""
def matrix_divided(matrix, div):
"""Divides all elements of a matrix by div
Args:
matrix: list of lists of numbers (int or float)
div: int or float to divide matrix by
Returns:
list: a new matrix list of lists
Raises:
TypeError: if div is not an int or float
ZeroDivisionError: if div is equal to 0
TypeError: if matrix or each row is not a list of lists
of int or floats
TypeError: if each row of the matrix is not of the same size
TypeError: if any element of the sublist is not an int or float
"""
if type(div) not in (int, float):
raise TypeError('div must be a number')
if div == 0:
raise ZeroDivisionError('division by zero')
if not isinstance(matrix, list) or len(matrix) == 0:
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
for row in matrix:
if not isinstance(row, list) or len(row) == 0:
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
if len(row) != len(matrix[0]):
raise TypeError('Each row of the matrix must have the same size')
for n in row:
if type(n) not in (int, float):
raise TypeError('matrix must be a matrix (list of lists) ' +
'of integers/floats')
return [[round(n / div, 2) for n in row] for row in matrix]
if __name__ == "__main__":
import doctest
doctest.testfile("tests/2-matrix_divided.txt")
| true |
ac98781df6169c661443e347c22760b6a88fad1c | KamalAres/Infytq | /Infytq/Day8/Assgn-55.py | 2,650 | 4.25 | 4 | #PF-Assgn-55
#Sample ticket list - ticket format: "flight_no:source:destination:ticket_no"
#Note: flight_no has the following format - "airline_name followed by three digit number
#Global variable
ticket_list=["AI567:MUM:LON:014","AI077:MUM:LON:056", "BA896:MUM:LON:067", "SI267:MUM:SIN:145","AI077:MUM:CAN:060","SI267:BLR:MUM:148","AI567:CHE:SIN:015","AI077:MUM:SIN:050","AI077:MUM:LON:051","SI267:MUM:SIN:146"]
def find_passengers_flight(airline_name="AI"):
#This function finds and returns the number of passengers travelling in the specified airline.
count=0
for i in ticket_list:
string_list=i.split(":")
if(string_list[0].startswith(airline_name)):
count+=1
return count
def find_passengers_destination(destination):
#Write the logic to find and return the number of passengers traveling to the specified destination
#pass
#Remove pass and write your logic here
count=0
for i in ticket_list:
string_list=i.split(":")
if(string_list[2].startswith(destination)):
count+=1
return count
def find_passengers_per_flight():
'''Write the logic to find and return a list having number of passengers traveling per flight based on the details in the ticket_list
In the list, details should be provided in the format:
[flight_no:no_of_passengers, flight_no:no_of_passengers, etc.].'''
#pass
#Remove pass and write your logic here
pass_list=[]
for i in ticket_list:
flight_no=i[:5]
no_of_passengers=find_passengers_flight(i[:5])
flight_no=flight_no+":"+str(no_of_passengers)
pass_list.append(flight_no)
#print(pass_list)
return list(set(pass_list))
def sort_passenger_list():
#Write the logic to sort the list returned from find_passengers_per_flight() function in the descending order of number of passengers
#pass
#Remove pass and write your logic here
sort_list=find_passengers_per_flight()
new=[]
for i in sort_list:
i=i.split(":")
#print(i)
#new.append(i
l=i[::-1]
#print(l)
new.append(l)
new.sort(reverse=True)
sort_list=new
new=[]
for i in sort_list:
new.append(i[::-1])
temp=""
sort_list=[]
for i in new:
temp=i[0]+":"+i[1]
sort_list.append(temp)
#print(new)
return sort_list
#Provide different values for airline_name and destination and test your program.
#print(find_passengers_per_flight())
#print(find_passengers_flight("AI"))
#print(find_passengers_destination("LON"))
print(sort_passenger_list())
| true |
5a195c58bc440fce91c4a7ebc3a1f9eeb61d1ce1 | Wallabeee/PracticePython | /ex11.py | 706 | 4.21875 | 4 | # Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
# a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
# Take this opportunity to practice using functions, described below.
def isPrime(num):
divisors = []
for x in range(1, num + 1):
if num % x == 0:
divisors.append(x)
if num ==1:
print(f"{num} is not a prime number.")
elif divisors[0] == 1 and divisors[1] == num:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
num = int(input("Enter a number: "))
isPrime(num) | true |
c565249554b9f07bcf3b5c79d607551ae97cc4fc | rene-d/edupython | /codes/pythagoricien.py | 570 | 4.15625 | 4 | # Recherche d'un triplet pythagoricien d'entiers consécutifs
# https://edupython.tuxfamily.org/sources/view.php?code=pythagoricien
# Créé par AgneS, le 17/06/2013 en Python 3.2
for i in range(100000): # On va tester avec la réciproque de Pythagore
# pour 3 nombres consécutifs compris entre 0 et 100001
a=i*i+(i+1)*(i+1) # Le carré de i peut être obtenu aussi en posant i**2 ou puissance(i, 2)
r=(i+2)*(i+2)
if r==a:
print ("les nombres",i,",",i+1,"et",i+2,"forment un triplet pythagoricien")
| false |
cb76ab641d274b65fb3c310584580943586eb178 | timewaitsfor/LeetCode | /knowledge/array_kn.py | 710 | 4.15625 | 4 | # 1. create an array
a = []
# 2. add element
# time complexity: O(1)
a.append(1)
a.append(2)
a.append(3)
# 3. insert element
# time complexity: O(N)
a.insert(2, 99)
# 4. access element
# time complexity: O(1)
tmp = a[2]
# 5. update element
a[2] = 88
# 6. remove element
# time complexity: O(N)
a.remove(88)
a.pop(1)
a.pop() # time complexity: O(1)
# 7. get array size
size = len(a)
# 8. iterate array
# time complexity: O(N)
for i in a:
pass
for idx,val in enumerate(a):
pass
for i in range(0, len(a)):
pass
# 9. find an element
# time complexity: O(N)
idx = a.index(2)
# 10. sort an array
# time complexity: O(NlogN)
a.sort() # from small to big
a.sort(reverse=True) # from big to small | false |
02e8b295591e79c057481be775219e2143915e4f | SaidhbhFoley/Promgramming | /Week04/even.py | 370 | 4.15625 | 4 | #asks the user to enter in a number, and the program will tell the user if the number is even or odd.
#Author: Saidhbh Foley
number = int (input("enter an integer:"))
if (number % 2) == 0:
print ("{} is an even number".format (number))
else:
print ("{} is an odd number".format (number))
i = 0
while i > 0:
print (i)
else:
print ("This has ended the loop")
| true |
8295f51f45e58fca6248eef8c1e1582988fd9e64 | IchijikuJP/Kesci_DataScienceIntroduction | /Python进阶/zip函数.py | 564 | 4.5625 | 5 | # zip()函数用于将可迭代对象作为参数, 将对象中对应的元素打包成一个个元组
# 然后返回由这些元组组成的对象, 这样可以节约内存
# 如果各个迭代器的元素个数不一致, 则返回列表长度与最短的对象相同
# zip()示例:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
z = zip(list1, list2)
print(z)
z_list = list(z)
print(z_list)
# 与zip相反, zip(*)可理解为解压, 返回二维矩阵式
un_zip = zip(*z_list)
un_list1, un_list2 = list(un_zip)
print(un_list1)
print(un_list2)
print(type(un_list2))
| false |
c158785cfd4d1ef3704194e7a1fea2d1a1210308 | tdchua/dsa | /data_structures/doubly_linkedlist.py | 2,805 | 4.34375 | 4 | #My very own implementation of a doubly linked list!
#by Timothy Joshua Dy Chua
class Node:
def __init__(self, value):
print("Node Created")
self.value = value
self.next = None
self.prev = None
class DLinked_List:
def __init__(self):
self.head = None
self.tail = None
def traverse(self):
curr_node = self.head
while(True):
if(curr_node != None):
print(curr_node.value)
curr_node = curr_node.next
else:
break
#For a doubly linked list the reverse traversal is much easier to implement
def reverse_traverse(self):
curr_node = self.tail
while(True):
if(curr_node != None):
print(curr_node.value)
curr_node = curr_node.prev
else:
break
return
def delete_node(self, value):
#The case for head removal
if(value == self.head.value):
self.head = self.head.next
else:
curr_node = self.head
while(True):
prev_node = curr_node
#If we have reached the end of the list
if(curr_node.next == None):
print("Node to delete...not found")
return
curr_node = curr_node.next
#The node to remove is curr_node
if(curr_node.value == value):
prev_node.next = curr_node.next
curr_node.next.prev = prev_node
return
def insert_node(self, value):
#In the DSA book, it was only mentioned that adding a node would be inserting it after the list's tail.
prev_node = None
if(self.head != None): #To check if there is no head
curr_node = self.head
while(True):
if(curr_node.next == None):
curr_node.prev = prev_node
curr_node.next = Node(value)
return
else:
prev_node = curr_node
curr_node = curr_node.next
else:
self.head = Node(value)
return
if __name__ == "__main__":
my_list = [i for i in range(10)]
#Here is where we instantiate a single linked list.
#We instantiate the head node first; we give it the first value
head = Node(my_list[0])
#We then instantiate the linked list
my_doubly_linked_list = DLinked_List()
#We connect the head pointer of the linked list to the first node
my_doubly_linked_list.head = head
for element in my_list[1:]:
my_doubly_linked_list.insert_node(element)
#We then traverse the link
print("Traversal")
curr_node = my_doubly_linked_list.head
my_doubly_linked_list.traverse()
#Reverse traversal
print("Reverse Traversal")
my_doubly_linked_list.reverse_traverse()
#Deleting a node
print("Node Deletion")
my_doubly_linked_list.delete_node(0)
my_doubly_linked_list.traverse()
#Inserting a node
print("Node Insertion")
my_doubly_linked_list.insert_node(16)
my_doubly_linked_list.traverse()
| true |
5ab07e8ffa079399d88e13fe33573387051cbc06 | rayanepimentel/CourseraUSP-Python-Parte01 | /Python/week02/Tipos de Dados/exercicioopcional.py | 1,225 | 4.15625 | 4 | '''
Nesta lista de exercícios vamos praticar os conceitos vistos até agora. Cada exercício deve ser resolvido em um arquivo separado e a seguir enviado através da web. A correção automática pode demorar alguns minutos. Você pode submeter a mesma resposta mais de uma vez.
Note que a correção verifica se o resultado corresponde exatamente ao que foi pedido no enunciado. Letras maiúsculas ou minúsculas, número de espaços e pontuação diferentes do pedido são tratados como erro.
Exercício 1
Uma empresa de cartão de crédito envia suas faturas por email com a seguinte mensagem:
Olá, Fulano de Tal
A sua fatura com vencimento em 9 de Janeiro no valor de R$ 350,00 está fechada.
'''
nomeCliente = input("Digite o nome do cliente: ")
diaVencimento = int(input("Digite o dia do vencimento: "))
mesVencimento = input("Digite o mês do vencimento: ")
valor = float(input("Digite o valor da fatura: "))
nome = nomeCliente.title()
mes = mesVencimento.title()
print("\n Olá, ", nome, "\n A sua fatura com vencimento em ", diaVencimento, "de ", mes, "no valor de R$ ", valor, "está fechada.")
#Utilizei title() para deixar a primeira letra maiúscula, mesmo colocando menúscula.
#E \n quebra de linha | false |
22aa6b4daeb05936eb5fd39b361e2945d02a5f64 | 786awais/assignment_3-geop-592-sharing | /Assignment 3 GEOP 592 | 2,512 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[50]:
#GEOP_592 Assigment_3
#Codes link: https://www.datarmatics.com/data-science/how-to-perform-logistic-regression-in-pythonstep-by-step/
#We are Provided with a data for 6800 micro-earthquake waveforms. 100 features have been extracted form it.
#We need to perform logistic regression analysis to find that if it is a micro-earthquake (1) or noise (0).
# In[1]:
#Import the module
from sklearn.datasets import make_classification
from matplotlib import pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np
# In[2]:
label = np.load('label.npy')
# In[3]:
features = np.load('features.npy')
# In[4]:
features.shape
# In[5]:
label.shape
# In[10]:
label[1:10]
# In[20]:
features[0:10,0:10]
# In[22]:
# Generate and dataset for Logistic Regression, This is given in the tutoriL, Not for our use in this assignmnet
x, y = make_classification(
n_samples=100,
n_features=2,
n_classes=2,
n_clusters_per_class=1,
flip_y=0.03,
n_informative=1,
n_redundant=0,
n_repeated=0
)
print(y)
# In[27]:
y.shape
# In[28]:
x.shape
# In[29]:
# Create a scatter plot
plt.scatter(x[:,1], y, c=y, cmap='rainbow')
plt.title('Scatter Plot of Logistic Regression')
plt.show()
# In[30]:
# Split the dataset into training and test dataset: Taking 5500 out of 6800 data points for training set, so 1300 will be used for test data points.
x_train, x_test, y_train, y_test = train_test_split(features, label, test_size = 1300, random_state=1)
# In[35]:
# Create a Logistic Regression Object, perform Logistic Regression
log_reg = LogisticRegression(solver='lbfgs',max_iter=500)
log_reg.fit(x_train, y_train)
# In[36]:
# Show to Coeficient and Intercept
print(log_reg.coef_)
print(log_reg.intercept_)
# In[37]:
# Perform prediction using the test dataset
y_pred = log_reg.predict(x_test)
# In[38]:
# Show the Confusion Matrix
confusion_matrix(y_test, y_pred)
# In[40]:
x_test.shape
# In[41]:
y_test.shape
# In[42]:
x_train.shape
# In[43]:
y_train.shape
# In[45]:
print(log_reg.score(x_test, y_test))
# In[49]:
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
# In[ ]:
# So, our classification for '0' and '1' is correct for 99% & 98% respectively with overall accuracy of 98%.
| true |
63b2b212b2e42f539fb802cc95633eae00c34a7f | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework1/problem2.py | 825 | 4.1875 | 4 | # jws2191
''' This program will, given an integer representing a number of years,
print the approximate population given the current population and the
approximate births, deaths, and immigrants per second. '''
# Step 1: store the current population and calculate the rates of births,
# deaths, and immigrations per year
current_population = 307357870
births_per_year = (60*60*24*365)/7
deaths_per_year = (60*60*24*365)/13
immigrants_per_year = (60*60*24*365)/35
#Step 2: take in number of years as input
s = input('Enter how many years into the future you would like to see the population?: ')
years = int(s)
# Step 3: adjust the population accordingly
new_population = current_population + years*(births_per_year - deaths_per_year + immigrants_per_year)
print("The new population is %d people." % new_population) | true |
773442a1cdd867d18af6c7578af1f5e208be9a7c | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework2/untitled.py | 552 | 4.28125 | 4 | '''
This is a basic dialog system that prompts the user to
order pizza
@author Joe Skimmons, jws2191
'''
def select_meal():
possible_orders = ["pizza" , "pasta" , "salad"]
meal = input("Hello, would you like pizza, pasta, or salad?\n")
while meal.lower() not in possible_orders:
meal = input("Sorry, we don't have " + meal + " today!\n")
def salad():
salad = input("Hello, would you like pizza, pasta, or salad?\n")
while salad.lower() != "salad":
salad = input("Sorry, we don't have " + meal + " today!\n")
select_meal()
salad() | true |
2bc4c6523788b6a8707aa33540d01b0fd2731743 | kevin-bot/Python-Kevin-pythom | /Script1.py | 577 | 4.125 | 4 |
#practica para asentuar los conocimientos de dias dom,22 de sep,21:54
'''1.DEFINIR una funcion max() que tome como argumento dos números y
devuelva el mayor de ellos'''
def funcion(numerouno,numerodos):
if numerouno < numerodos:
print(f" {numerodos} es mayor que {numerouno}")
elif numerouno>numerodos:
print(f"{numerouno} es mayor que {numerodos}")
else :
print(f"Son el mismo numero ")
if __name__ == '__main__':
num1 = float(input("ingresa un nemero: "))
num2 = float(input("ingresa otro nemero: "))
funcion(num1,num2)
| false |
6210f2e37e1ce5e93e7887ffa73c8769fae0a35a | garg10may/Data-Structures-and-Algorithms | /searching/rabinKarp.py | 1,862 | 4.53125 | 5 | #Rabin karp algorithm for string searching
# remember '^' : is exclusive-or (bitwise) not power operator in python
'''
The algorithm for rolling hash used here is as below. Pattern : 'abc', Text : 'abcd'
Consider 'abc' its hash value is calcualted using formula a*x^0 + b*x^1 + c*x^2, where x is prime
Now when we need to roll( i.e. find hash of 'bcd'), which should be b*x^0 + c*x^1 + d*x^2,
instead of calculating it whole , we just subract first character value and add next character value.
Value of first character would be a*X^0 --> a, so we subract a and divide by prime so that new position becomes
b*x^0 + c*x^1, now we need to add next character, which would be 'd'*x^(patternLength-1), so here 'd'*x^2 so it becomes
b*x^0 + c*x^1 + d*x^2, which is what we need. It's O(1) so very useful for long strings.
Note:
Here it's recommended to use high value of text characters, therefore use ASCII value for text not just 0,1,2
Also use prime number greater than 100, so that the hash function is good and less collisions are there
See for more information --> https://en.wikipedia.org/wiki/Rolling_hash
'''
def hashValue(pattern, prime):
value = 0
for index, char in enumerate(pattern):
value += ord(char) * (pow(prime,index))
return value
def find(pattern , text):
prime = 3
m = len(pattern)
n = len(text)
p = hashValue(pattern, prime)
t = hashValue(text[:m], prime)
for i in range(n-m+1):
#if hashes are equal
if p == t:
#check for each character, since two different strings can have same hash
for j in range(m):
if text[i + j] != pattern[j]:
break
if j == m-1:
print 'Pattern found at index %s'%(i)
#calculate rolling hash
if i < n-m: # i.e. still some text of lenth m is left
t = ((t - ord(text[i])) / prime) + (ord(text[i + m]) * (pow(prime, (m - 1))))
find('abc', '***abc***111***abc***') | true |
e1be3b9664e172dc71a2e3038a1908c5e49dd57b | Fueled250/Intro-Updated-Python | /intro_updated.py | 881 | 4.1875 | 4 | #S.McDonald
#My first Python program
#intro.py -- asking user for name, age and income
#MODIFIED: 10/18/2016 -- use functions
#create three functions to take care of Input
def get_name():
#capture the reply and store it in 'name' variable
name = input ("what's your name?")
return name
def get_age():
#capture the reply, convert to 'int' and store in 'age' variable
age = int(input ("How old are you?"))
return age
def get_income():
#capture the reply, convert to 'float' and store in 'income' variable
income = float(input ("what's your income?"))
return income
#create a main function
def main():
#call the other functions by their names
name = get_name() #return the value from function
age = get_age()
income = get_income()
print(name, age, income)
#call the main() function
main()
| true |
1c60d291a1d02ee0ebefd3544843c918179e5254 | aiswaryasaravanan/practice | /hackerrank/12-26-reverseLinkedList.py | 956 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def add(self,data):
if not self.head:
self.head=Node(data)
else:
cur=self.head
while cur.next:
cur=cur.next
cur.next=Node(data)
def reverse(self):
pre=None
cur=self.head
foll=cur.next
while cur.next:
cur.next=pre
pre=cur
cur=foll
foll=cur.next
cur.next=pre
self.head=cur
def printList(self):
cur=self.head
while cur.next:
print(cur.data)
cur=cur.next
print(cur.data)
linkedList = LinkedList()
linkedList.add(1)
linkedList.add(2)
linkedList.add(3)
linkedList.add(4)
linkedList.add(5)
linkedList.printList()
linkedList.reverse()
linkedList.printList() | true |
781b93dd583dc43904e9b3d5aa4d6b06eaa5705b | spno77/random | /Python-programs/oop_examples.py | 1,399 | 4.625 | 5 | """ OOP examples """
class Car:
""" Represent a car """
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descritive name"""
long_name = f"{self.year} {self.make} {self.model}"
return long_name
def read_odometer(self):
print(f"this car has {self.odometer_reading} miles")
def update_odometer(self,mileage):
if(mileage >= self.odometer_reading):
self.odometer_reading = mileage
else:
print("You cant roll back the odometer")
def increment_odometer(self,miles):
if(miles < 0):
print("You cant assign negative values")
else:
self.odometer_reading += miles
class Battery:
def __init__(self,battery_size = 75):
self.battery_size = battery_size
def describe_battery(self):
print(f"this car has a {self.battery_size}-kWh batery")
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles"""
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
new_car = ElectricCar("tesla","model s",2019)
new_car.battery.describe_battery()
new_car.battery.get_range() | true |
052193ea7c43ccaf0406b3c34cf08b906d6c74fd | GitDavid/ProjectEuler | /euler.py | 812 | 4.25 | 4 | import math
'''
library created for commonly used Project Euler problems
'''
def is_prime(x):
'''
returns True if x is prime; False if not
basic checks for lower numbers and all primes = 6k +/-1
'''
if x == 1 or x == 0:
return False
elif x <= 3:
return True
elif x % 2 == 0 or x % 3 == 0:
return False
elif x < 9:
return True
else:
r = math.floor(math.sqrt(x))
f = 5
while f <= r:
if (x % f == 0) or (x % (f + 2) == 0):
return False
f += 6
return True
def primes_up_to(x):
'''
returns list of all primes up to (excluding) x
'''
primes_list = []
for i in range(x - 1):
if is_prime(i):
primes_list.append(i)
return primes_list
| true |
7e767a59754cc8b272e876948793c1ac39d6642c | felipeonf/Exercises_Python | /exercícios_fixação/070.py | 419 | 4.1875 | 4 | ''' [DESAFIO] Faça um programa que mostre os 10 primeiros elementos da Sequência
de Fibonacci:
1 1 2 3 5 8 13 21...'''
termos = int(input('Digite a quantidade de termos que quer ver: '))
termo = 1
termo_anterior = 0
print(0,end=' ')
print(1,end=' ')
for num in range(3,termos+1):
termo3 = termo_anterior + termo
print(termo3,end=' ')
termo_anterior = termo
termo = termo3
| false |
940dce299d8c4c9ee07502c6daf12f9933a26ce0 | felipeonf/Exercises_Python | /exercícios_fixação/073.py | 281 | 4.125 | 4 | '''Crie um programa que preencha automaticamente (usando lógica, não apenas
atribuindo diretamente) um vetor numérico com 10 posições, conforme abaixo:
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9'''
lista = []
for num in range(9,-1,-1):
lista.append(num)
print(lista)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.