blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
53bc1949d4d989f076e481341e6c52fffb549da4 | mayakota/KOTA_MAYA | /Semester_1/Lesson_05/5.01_ex_02.py | 655 | 4.15625 | 4 | height = float(input("What is your height?"))
weight = float(input("What is your weight?"))
BMI = 0
condition = "undetermined"
def calcBMI(height,weight):
global BMI,condition
BMI = (weight/height) * 703
if BMI < 18.5 :
condition = "condition is Underweight"
elif BMI < 24.9 :
condition = "condition is Normal"
elif BMI < 29.9 :
condition = "Overweight"
elif BMI < 34.9 :
condition = "Obese"
elif BMI < 39.9 :
condition = "Very obese"
elif BMI > 39.9 :
condition = "Morbidly Obese"
calcBMI(height, weight)
print("Your BMI is", BMI)
print("Your condition is", condition)
| true |
9bfca2db61d14c15064ed7c42e3bdeb6714de64c | mayakota/KOTA_MAYA | /Semester_1/Lesson_05/5.02_ex06.py | 559 | 4.25 | 4 | def recursion():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if username == "username" and password == "password":
print("correct.")
else:
if password == "password":
print("Username is incorrect.")
recursion()
elif username == "username":
print("Password is incorrect.")
recursion()
else:
print("Username and password are incorrect.")
recursion()
recursion()
| true |
bf23188fb3c90c34da9d2b64ba6aeed16d623fd1 | shashankgargnyu/algorithms | /Python/GreedyAlgorithms/greedy_algorithms.py | 1,920 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains Python implementations of greedy algorithms
from Intro to Algorithms (Cormen et al.).
The aim here is not efficient Python implementations
but to duplicate the pseudo-code in the book as closely as possible.
Also, since the goal is to help students to see how the algorithm
works, there are print statements placed at key points in the code.
The performance of each function is stated in the docstring, and
loop invariants are expressed as assert statements when they
are not too complex.
This file contains:
recursive_activity_selector()
greedy_activity_selector()
"""
def recursive_activity_selector(s, f, k, n=None):
"""
Args:
s: a list of start times
f: a list of finish times
k: current position in
n: total possible activities
Returns:
A maximal set of activities that can be scheduled.
(We use a list to hold the set.)
"""
if n is None:
assert(len(s) == len(f)) # each start time must match a finish time
n = len(s) # could be len f as well!
m = k + 1
while m < n and s[m] < f[k]: # find an activity starting after our last
# finish
m = m + 1
if m < n:
return [m] + recursive_activity_selector(s, f, m, n)
else:
return []
def greedy_activity_selector(s, f):
"""
Args:
s: a list of start times
f: a list of finish times
Returns:
A maximal set of activities that can be scheduled.
(We use a list to hold the set.)
"""
assert(len(s) == len(f)) # each start time must match a finish time
n = len(s) # could be len f as well!
a = []
k = 0
for m in range(1, n):
if s[m] >= f[k]:
a.append(m)
k = m
return a
| true |
8f2a974d5aa0eb91db1b2978ced812678e34f69f | LYoung-Hub/Algorithm-Data-Structure | /wordDictionary.py | 2,039 | 4.125 | 4 | class TrieNode(object):
def __init__(self):
self.cnt = 0
self.children = [None] * 26
self.end = False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
curr = self.root
for ch in word:
idx = ord(ch) - 97
if not curr.children[idx]:
curr.children[idx] = TrieNode()
curr.cnt += 1
curr = curr.children[idx]
curr.end = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
return self.searchHelper(word, 0, self.root)
def searchHelper(self, word, idx, node):
if len(word) == idx:
return node.end
ch = word[idx]
if ch == '.':
if node.cnt == 0:
return False
else:
for n in node.children:
if n and self.searchHelper(word, idx + 1, n):
return True
return False
else:
loc = ord(ch) - 97
if not node.children[loc]:
return False
else:
return self.searchHelper(word, idx + 1, node.children[loc])
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
if __name__ == '__main__':
wordDict = WordDictionary()
wordDict.addWord('a')
wordDict.addWord('ab')
wordDict.addWord('a')
wordDict.search('a.')
wordDict.search('ab')
wordDict.search('.a')
wordDict.search('.b')
wordDict.search('ab.')
wordDict.search('.')
wordDict.search('..')
| true |
cf90416b58d12338fb6c626109ef0ecf11c0807f | sravanneeli/Data-structures-Algorithms | /stack/parenthesis_matching.py | 888 | 4.125 | 4 | """
Parenthesis Matching: whether braces are matching in a string
"""
from stack.stack_class import Stack
bracket_dict = {')': '(', ']': '[', '}': '{'}
def is_balanced(exp):
"""
Check whether all the parenthesis are balanced are not
:param exp: expression in string format
:return: True or False
"""
st = Stack(len(exp))
st.create()
for i in range(len(exp)):
if exp[i] == '(' or exp[i] == '[' or exp[i] == '{':
st.push(exp[i])
elif exp[i] == ')' or exp[i] == ']' or exp[i] == '}':
if st.is_empty():
return False
x = st.pop()
if bracket_dict[exp[i]] != x:
return False
return st.is_empty()
def main():
exp = '({a+b}*(c-d))'
print("The expression parenthesis are balanced or not ?", is_balanced(exp))
if __name__ == '__main__':
main()
| true |
7c811aba960dd8ebeb03863e298ba55f43a5ed3c | sravanneeli/Data-structures-Algorithms | /Sorting_Algorithms/merge_sort.py | 1,321 | 4.15625 | 4 | def merge(arr, start, mid, end):
temp = [0] * (end - start + 1)
i, j, k = start, mid + 1, 0
while i <= mid and j <= end:
if arr[i] < arr[j]:
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
j += 1
while i <= mid:
temp[k] = arr[i]
i += 1
k += 1
while j <= end:
temp[k] = arr[j]
j += 1
k += 1
for i in range(start, end + 1):
arr[i] = temp[i - start]
def merge_iter(a):
arr = a.copy()
n = len(arr)
p = 2
while p <= n:
i = 0
while i+p-1 < n:
low = i
high = i + p - 1
mid = (low + high) // 2
merge(arr, low, mid, high)
i += p
p *= 2
if p // 2 < n:
merge(arr, 0, (p//2)-1, n-1)
return arr
def mergesort(arr, start, end):
if start < end:
mid = (start + end) // 2
mergesort(arr, start, mid)
mergesort(arr, mid + 1, end)
merge(arr, start, mid, end)
def main():
arr = [11, 13, 7, 12, 16, 9, 24, 5, 10, 3]
print(f"Sorted array using iterative merge sort :{merge_iter(arr)}")
mergesort(arr, 0, len(arr)-1)
print("Sorted Array:", arr)
if __name__ == "__main__":
main()
| false |
46fe2a640740d758681f4cff963a0f8dc2bf87ff | lajospajtek/thought-tracker.projecteuler | /p302.py | 2,977 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: Latin1 -*-
# Problem 302
# 18 September 2010
#
# A positive integer n is powerful if p^(2) is a divisor of n for every prime
# factor p in n.
#
# A positive integer n is a perfect power if n can be expressed as a power of
# another positive integer.
#
# A positive integer n is an Achilles number if n is powerful but not a
# perfect power. For example, 864 and 1800 are Achilles numbers:
# 864 = 2^(5)·3^(3) and 1800 = 2^(3)·3^(2)·5^(2).
#
# We shall call a positive integer S a Strong Achilles number if both S and
# φ(S) are Achilles numbers.^(1)
# For example, 864 is a Strong Achilles number: φ(864) = 288 = 2^(5)·3^(2).
# However, 1800 isn't a Strong Achilles number because:
# φ(1800) = 480 = 2^(5)·3^(1)·5^(1).
#
# There are 7 Strong Achilles numbers below 10^(4) and 656 below 10^(8).
#
# How many Strong Achilles numbers are there below 10^(18)?
#
# ^(1) φ denotes Euler's totient function.
from math import sqrt, log
lim = 100000
#primes=[2,3]
#i = 3
##slim=int(sqrt(lim))+1
#slim=lim
##for i in range(5,lim,2):
#while i < slim:
# i += 2
# l = int(sqrt(i))
# for d in primes[1:l]:
# if i % d == 0: break
# else:
# primes.append(i)
# if i%10000 == 1 : print i
#print primes[999]
def is_powerful(n):
#if n in primes:
# return False
divs = []
q = int(sqrt(n))
for d in primes:
# print d
# if d > q: break
if n % d != 0: continue
rm = 0
e = 0
while True:
dv, rm = divmod(n,d)
# print ". ", n, d, dv, rm, e
if rm != 0: break
n = dv
e += 1
if e == 1:
divs = False
break
divs.append((d,e))
#print d, e
if divs == []: divs = [(n,1)]
return divs
def is_powerful2(n):
divs = []
q = n/2 #int(sqrt(n))
# print "n:", n, "q:", q
d = 2
dd = 1
e = 0
while d<=q:
dv, rm = divmod(n,d)
if rm == 0:
n = dv
e += 1
else:
if e == 1:
# print d, e, "breaking"
divs = False
break
elif e > 1:
# print d, e
divs.append((d,e))
e = 0
d += dd
dd = 2
if divs == []: divs = [(n,1)]
return divs
def is_achilles(n):
divs = is_powerful2(n)
rc = False
if divs != False:
rc = divs
exps = [d[1] for d in divs]
m = min(exps)
for e in exps:
if e%m != 0:
break
else:
rc = False
return rc
def printdivs(n, divs):
print n,
for d in divs:
print d[0], "^", d[1],
print
def totient(n, divs):
rc = n
for d in divs:
rc = rc * (d[0]-1) / d[0]
return rc
#v = 864
#v = 999500
#divs = is_achilles(v)
#print v, divs
#print totient(v, divs)
#exit()
ctr = 0
alist = []
for n in range(5,lim):
divs = is_achilles(n)
if divs == False: continue
alist.append(n)
t = totient(n, divs)
#tdivs = is_achilles(t)
#if tdivs == False: continue
if t in alist:
ctr += 1
print ctr, ":", n, divs, " - ", t
#print ctr, ":", n, divs, " - ", t, tdivs
#print alist
| false |
db069f0bdb81b54b5ca7ab589fd8db33bff0368b | lajospajtek/thought-tracker.projecteuler | /p057.py | 1,097 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: Latin1 -*-
# Problem 057
#
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
#
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
#
# By expanding this for the first four iterations, we get:
#
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
#
# The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example
# where the number of digits in the numerator exceeds the number of digits in the denominator.
#
# In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
# The continued fraction can be expressed recursively as:
# a_n+1 = 1 / (1 + a_n)
#
# ans: 153
from fractions import Fraction
from math import log, floor
n = 0
a = Fraction(3, 2)
for i in range(1, 1000):
a = 1 + (1 / (1 + a))
if floor(log(a.denominator, 10)) < floor(log(a.numerator, 10)):
n += 1
print n
| true |
4e612bc6b0425b59d37e9341cd4bc8783a2f2bad | sauravgsh16/DataStructures_Algorithms | /g4g/ALGO/Searching/Coding_Problems/12_max_element_in_array_which_is_increasing_and_then_decreasing.py | 1,725 | 4.15625 | 4 | ''' Find the maximum element in an array which is first increasing and then decreasing '''
'''
Eg: arr = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1]
Output: 500
Linear Search:
We can search for the maximum element and once we come across an element less
than max, we break and return max
'''
'''
Binary Search
We can modify the standard Binary Search algorithm for the given type of arrays.
1) If the mid element is greater than both of its adjacent elements,
then mid is the maximum.
2) If mid element is greater than its next element and smaller than the
previous element then maximum lies on left side of mid.
Example array: {3, 50, 10, 9, 7, 6}
3) If mid element is smaller than its next element and greater than the
previous element then maximum lies on right side of mid.
Example array: {2, 4, 6, 8, 10, 3, 1}
'''
def find_element(arr, low, high):
# Base Case: Only one element is present in arr[low..high]
if high == low:
return arr[low]
# If there are two elements and first is greater, then
# the first element is maximum
if high == low + 1 and arr[low] >= arr[high]:
return arr[low]
# If there are two elements and second is greater, then
# the second element is maximum
if high == low + 1 and arr[high] > arr[low]:
return arr[high]
mid = (low + high) / 2
if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]:
return mid
if arr[mid] > arr[mid - 1] and arr[mid] < arr[mid + 1]:
return find_element(arr, mid+1, high)
else:
return find_element(arr, low, mid-1)
arr = [1, 3, 50, 10, 9, 7, 6]
print find_element(arr, 0, len(arr)-1)
| true |
536926dbe1374a5bfac6d3fd62074cde4a1cab12 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Arrays/Sorting/14_union_and_intersection.py | 1,174 | 4.125 | 4 | '''
Union and Intersection of two sorted arrays
Input : arr1[] = {1, 3, 4, 5, 7}
arr2[] = {2, 5, 6}
Output : Union : {1, 2, 3, 4, 5, 6, 7}
Intersection : {3, 5}
'''
def union(arr1, arr2):
m = len(arr1)
n = len(arr2)
i = k = 0
result = []
while i < m and k < n:
while i < m and arr1[i] <= arr2[k]:
result.append(arr1[i])
i += 1
while k < n and arr2[k] < arr1[i]:
if arr2[k] in result:
k += 1
continue
else:
result.append(arr2[k])
k += 1
while i < m:
result.append(arr1[i])
i += 1
while k < n:
result.append(arr2[k])
k += 1
return result
def intersection(arr1, arr2):
m = len(arr1)
n = len(arr2)
i = k = 0
result = []
while i < m and k < n:
if arr1[i] < arr2[k]:
i += 1
elif arr2[k] < arr1[i]:
k += 1
else:
result.append(arr1[i])
i += 1
k += 1
return result
m = [1, 3, 4, 5, 7]
n = [2, 3, 5, 6]
print union(m, n)
print intersection(m, n)
| false |
b820d08879eecae30d95bcaa221be073f71a22ad | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/RN_7_check_each_internal_node_has_exactly_1_child.py | 1,372 | 4.15625 | 4 | ''' Check if each internal node has only one child '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# In Preorder traversal, descendants (or Preorder successors) of every node
# appear after the node. In the above example, 20 is the first node in preorder
# and all descendants of 20 appear after it. All descendants of 20 are smaller
# than it. For 10, all descendants are greater than it. In general, we can say,
# if all internal nodes have only one child in a BST, then all the descendants
# of every node are either smaller or larger than the node. The reason is simple,
# since the tree is BST and every node has only one child,
# all descendants of a node will either be on left side or right side,
# means all descendants will either be smaller or greater.
def has_only_one_child(pre):
INT_MIN = -2**32
INT_MAX = 2**32
prev = pre[0]
for i in range(1, len(pre)-1):
ele = pre[i]
if ele <= INT_MAX and ele >= INT_MIN:
if ele < prev:
INT_MAX = prev - 1
else:
INT_MIN = prev + 1
prev = ele
else:
return False
return True
# Other solutions
# 1) preorder = reverse (postorder) only if nodes contain one child
pre = [8, 3, 5, 7, 6]
print has_only_one_child(pre)
| true |
1507e2ab37a5f36e5ba8a20fd41acff2815e9fa8 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Checking_and_Printing/24_symmetric_tree_iterative.py | 1,250 | 4.28125 | 4 | ''' Check if the tree is a symmetric tree - Iterative '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check_symmetric(root):
if not root:
return True
if not root.left and not root.right:
return True
q = []
# Append left and right, since we don't need to check root node
q.append(root.left)
q.append(root.right)
while len(q) > 0:
left_node = q.pop(0)
right_node = q.pop(0)
if left_node.val != right_node.val:
return False
if left_node.left and right_node.right:
q.append(left_node.left)
q.append(right_node.right)
elif left_node.left or right_node.right:
return False
if left_node.right and right_node.left:
q.append(left_node.right)
q.append(right_node.left)
elif left_node.right or right_node.left:
return False
return True, count
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
print check_symmetric(root)
| true |
06354d4f46de16ca4d0162548992da2fe6061973 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Checking_and_Printing/26_find_middle_of_perfect_binary_tree.py | 900 | 4.15625 | 4 | ''' Find middle of a perfect binary tree without finding height '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
'''
Use two pointer slow and fast, like linked list
Move fast by 2 leaf nodes, and slow by one.
Once fast reaches leaf, print slow.
Recursively call next route.
'''
def find_middle_util(slow, fast):
# import pdb; pdb.set_trace()
if slow is None or fast is None:
return
if fast.left is None and fast.right is None:
print slow.val,
find_middle_util(slow.left, fast.left.left)
find_middle_util(slow.right, fast.left.left)
def find_middle(root):
find_middle_util(root, root)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
find_middle(root) | true |
748bccf48ef30c79bb9312e2d3be2c37c66cf459 | HarperHao/python | /mypython/第七章文件实验报告/001.py | 1,235 | 4.28125 | 4 | """统计指定文件夹大小以及文件和子文件夹数量"""
import os.path
totalSize = 0
fileNum = 0
dirNum = 0
def visitDir(path):
global totalSize
global fileNum
global dirNum
for lists in os.listdir(path):
sub_path = os.path.join(path, lists)
if os.path.isfile(sub_path):
fileNum = fileNum + 1
totalSize = totalSize + os.path.getsize(sub_path)
elif os.path.isdir(sub_path):
dirNum = dirNum + 1
visitDir(sub_path)
def sizeConvert(size):
K, M, G = 1024, 1024 ** 2, 1024 ** 3
if size >= G:
return str(size / G) + 'G Bytes'
elif size >= M:
return str(size / M) + 'M Bytes'
elif size >= K:
return str(size / K) + 'K Bytes'
else:
return str(size) + 'Bytes'
def main(path):
if not os.path.isdir(path):
print("error")
return
visitDir(path)
def output(path):
print('The total size of {} is:{} ({}) Bytes'.format(path, sizeConvert(totalSize), str(totalSize)))
print("The total number of files in {} is {}".format(path, fileNum))
print("The total number of directories in {} is {}".format(path, dirNum))
path = r'K:\编程'
main(path)
output(path)
| true |
6fecf6d2c96d29409c240b76a7a0844668b17594 | kalyanitech2021/codingpractice | /string/easy/prgm4.py | 701 | 4.25 | 4 | # Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
# Example:
# Input:
# S = i.like.this.program.very.much
# Output: much.very.program.this.like.i
# Explanation: After reversing the whole
# string(not individual words), the input
# string becomes
# much.very.program.this.like.i
# Expected Time Complexity: O(|S|)
# Expected Auxiliary Space: O(|S|)
def reverseWords(str, n):
words = str.split('.')
string = []
for word in words:
string.insert(0, word)
reverseStr = '.'.join(string)
return reverseStr
str = "i.like.this.program.very.much"
n = len(str)
print(reverseWords(str, n))
| true |
83b5224314c1eba5d985c0413b69960dc9c26c3a | pavel-malin/new_practices | /new_practice/decorators_practice/abc_decorators_meta.py | 654 | 4.1875 | 4 | ''' Using a subclass to extend the signature of its parent's abstract method
import abc
class BasePizza(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""
class Calzone(BasePizza):
def get_ingredients(self, with_egg=False):
egg = Egg() if with_egg else None
return self.ingredients + [egg]
'''
import abc
class BasePizza(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""
class DiesPizza(BasePizza):
@staticmethod
def get_ingredients():
return None
| true |
9216d686ad0deb206998db55005c4e4889c6332f | courtneyng/Intro-To-Python | /If-exercises/If-exercises.py | 681 | 4.125 | 4 | # Program ID: If-exercises
# Author: Courtney Ng, Jasmine Li
# Period 7
# Program Description: Using if statements
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November']
# months.append('December')
ans = input("Enter the name of a month: ")
if ans == "January" or "March" or "May" or "July" or "August" or "October" or "December":
print("No. of days: 31")
elif ans == "February":
print("No. of days: 28/29")
elif ans == "April" or "June" or "September" or "November":
print("No. of days: 30")
elif ans in months:
print ("found it")
else:
print("That is not a month.")
| true |
2d1e08e74910d00f238f27b705b7196a35dacdf9 | courtneyng/Intro-To-Python | /Tuples_and_Lists/A_List_Of_Numbers.py | 1,727 | 4.28125 | 4 | # Program ID: A_List_Of_Numbers
# Author: Courtney Ng
# Period: 7
# Program Description: List extensions in Python
# numList = [1, 1, 2, 3, 5, 8, 11, 19, 30, 49]
# product = 30*8*11*19*30*49
num1 = int(input("Enter the first number."))
numList = [100, 101, 102]
numList.append(num1)
numList.remove(100)
numList.remove(101)
numList.remove(102)
print(numList)
print("The amount of numbers is: 1")
# gathering variables
num2 = int(input("Add another number to the list"))
numList.append(num2)
num3 = int(input("Add another number to the list"))
numList.append(num3)
num4 = int(input("Add another number to the list"))
numList.append(num4)
num5 = int(input("Add another number to the list"))
numList.append(num5)
num6 = int(input("Add another number to the list"))
numList.append(num6)
num7 = int(input("Add another number to the list"))
numList.append(num7)
num8 = int(input("Add another number to the list"))
numList.append(num8)
num9 = int(input("Add another number to the list"))
numList.append(num9)
num10 = int(input("Add another number to the list"))
numList.append(num10)
print("This is the list of numbers:", numList)
print("The amount of numbers is: 10")
print("If you add all the numbers together the sum is:", sum(numList))
# sum = 0
# for x in range(0,9):
# sum = sum + list[x]
product = 1
for x in range(0, 9):
product = product * numList[x]
print("If you multiply all the numbers in the list the product is:", product)
# this will sort the numbers in order from least to highest
numList.sort()
print("The smallest number is:", numList.pop(0))
print("The largest number is:", numList.pop(8))
print("The new amount is: 8")
print(numList)
| true |
b4a981c76af3be316f3b22b2c0d979bd7386e73c | courtneyng/Intro-To-Python | /Tuples_and_Lists/list_extensions.py | 797 | 4.34375 | 4 | # Program ID: lists_extensions
# Author: Courtney Ng
# Period: 7
# Program Description: List extensions in Python
# Given list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# The new list extensions test
fruits.count('apple')
print(fruits.count('apple')) # Added a print statement to show output
fruits.count('tangerine')
print(fruits.count('tangerine'))
fruits.index('banana')
print(fruits.index('banana'))
fruits.index('banana', 4) # Find the next banana starting at pos 4
print(fruits.index('banana', 4))
fruits.reverse()
print(fruits)
fruits.append('grape') # Adds grape to the list
print(fruits)
fruits.sort() # Alphabetically sorts
print(fruits)
fruits.pop() # Takes a variable out and puts it back in
print(fruits.pop(3))
| true |
bcef00fbacb443c75b8a69a97c56d78924ce4d7d | pouya-mhb/University-Excersises-and-Projects | /Compiler Class/prefix suffix substring proper prefix subsequence/substring of a string.py | 454 | 4.53125 | 5 | #substring of a string
stringValue = input("Enter string : ")
def substring(stringValue):
print("The original string is : " + str(stringValue))
# Get all substrings of string
# Using list comprehension + string slicing
res = [stringValue[i: j] for i in range(len(stringValue))
for j in range(i + 1, len(stringValue) + 1)]
# printing result
print("All substrings of string are : " + str(res))
substring(stringValue)
| true |
d6cf7a9f246b4e57cc1f748eccfd1d24dc64575a | shiblon/pytour | /3/tutorials/recursion.py | 1,988 | 4.78125 | 5 | # vim:tw=50
"""Recursion
With an understanding of how to write and call
functions, we can now combine the two concepts in
a really nifty way called **recursion**. For
seasoned programmers, this concept will not be at
all new - please feel free to move on. Everyone
else: strap in.
Python functions, like those in many programming
languages, are _recurrent_: they can "call
themselves".
A |def| is really a sort of template: it tells you
*how something is to be done*. When you call it,
you are making it do something *specific*, because
you are providing all of the needed data as
arguments.
From inside of the function, you can call that
same template with something specific *and
different* - this is recursion.
For example, look at the |factorial| function in
the code window.
It starts with a **base case**, which is usually a
really easy version of the problem, where you know
the answer right away. For non-easy versions of the
problem, it then defines a **recursion**, where
it calls itself with a smaller version of the
problem and uses that to compute the answwer.
Exercises
- Uncomment the |print| statements inside of |factorial|
(above and below |smaller_problem|) to see what
is happening.
- Practice saying "recur" instead of "recurse",
which is not a word. Now practice feeling good
because you are right.
"""
__doc__ = """Introduction to Recursion
The "factorial" of something is formed by
multiplying all of the integers from 1 to the
given number, like this:
factorial(5) == 5 * 4 * 3 * 2 * 1
You can do this recursively by noting that, e.g.,
factorial(5) == 5 * factorial(4)
This can't go forever, because we know that
factorial(1) == 1
See below.
"""
def factorial(n):
if n <= 1:
return 1
# print("before recursion", n)
smaller_problem = factorial(n - 1)
# print("after recursion", n)
return n * smaller_problem
# This gets big fast
print("2! =", factorial(2))
print("7! =", factorial(7))
print("20! =", factorial(20))
| true |
d7771130f1ee54dc2d3924e8266c91c559bf4063 | shiblon/pytour | /3/tutorials/hello.py | 1,596 | 4.71875 | 5 | # vim:tw=50
"""Hello, Python 3!
Welcome to Python version 3, a very fun language
to use and learn!
Here we have a simple "Hello World!" program. All
you have to do is print, and you have output. Try
running it now, either by clicking *Run*, or
pressing *Shift-Enter*.
What happened? This tutorial contains a *Python 3
interpreter*. It starts at the top of your program
(or _script_) and does what you tell it to until
it reaches the bottom. Here, we have told it to
do exactly one thing: **print** a **string** (text
surrounded by quotation marks) to the output
window, and it has.
The word |print| is a special function in Python 3.
It instructs the interperter to output what you
tell it to. In this tutorial, we capture that
output in the window below the code so that you
can easily see it.
We will get very comfortable with this as the tutorial goes on. Meanwhile, let's talk about the tutorial itself:
- The Table of Contents is above, marked *TOC*.
- *Page-Up* and *Page-Down* keys can be used to navigate.
- Code can be run with the *Run* button or *Shift-Enter*.
- Check out the options in the *Run* menu (the arrow). Among other things,
you can see what you have changed from the original slide. The tutorial
will try to remember those changes for a long time.
Exercises
- Try removing each of the quotation marks in
turn. What happens?
- Change the string to say hello specifically to you.
- Print 'Hello, Python!' using two strings instead
of one, like this: |print('Hello', 'Python!')|.
What did |print| do for you automatically?
"""
print('Hello, Python!')
| true |
60b0ff336ec48cb60786c47528fa31777ffc8693 | shiblon/pytour | /tutorials/urls.py | 1,583 | 4.125 | 4 | # vim:tw=50
"""Opening URLs
The web is like a huge collection of files,
all jamming up the pipes as they fall off the
truck. Let's quickly turn our attention there,
and learn a little more about file objects while
we're at it.
Let's use |urllib|
(http://docs.python.org/2/library/urllib.html) to
open the Google Privacy Policy, so we can keep an
eye on how long it is getting.
The result of urllib.urlopen is a file-like object. It
therefore supports |read|, and it supports line-by-line
iteration. This is classic Python: define a simple
interface, then just make sure you provide the
needed functions. It doesn't have to _be_ a file
to _act_ like a file, and how it acts is all we
care about.
We'll continue in that spirit by writing our code
so that we can accept any iterable over lines,
which also makes it easy to test.
Exercises
- Open the web site as a file object, get all of the
words by using |str.split| on each line (|help|
will come in handy), then count and sum up.
"""
__doc__ = """Count the Words
Note that "count_words" does not specify a file
object, but rather something that can look like a
bunch of lines, because that's all it needs.
>>> count_words(['some words here\\n', 'some words there'])
6
"""
import urllib
def count_words(lines):
"""Counts all words in the 'lines' iterable."""
#
# TODO: Fill this in.
def main():
f = urllib.urlopen(
"https://www.google.com/intl/en/policies/privacy/")
print count_words(f) # I get 2571
f.close()
if __name__ == '__main__':
if not _testmod().failed:
print "Success!"
main()
| true |
503f1aa74c5d3c2dbd5f5b4e6f97cdbc67aeaa23 | abhisek08/Basic-Python-Programs | /problem22.py | 1,247 | 4.4375 | 4 | '''
You, the user, will have in your head a number between 0 and 100.
The program will guess a number, and you, the user, will say whether it is too high, too low, or your number.
At the end of this exchange, your program should print out how many guesses it took to get your number.
As the writer of this program, you will have to choose how your program will strategically guess.
A naive strategy can be to simply start the guessing at 1, and keep going (2, 3, 4, etc.) until you hit the number.
But that’s not an optimal guessing strategy. An alternate strategy might be to guess 50 (right in the middle of the range),
and then increase / decrease by 1 as needed. After you’ve written the program, try to find the optimal strategy!
(We’ll talk about what is the optimal one next week with the solution.)
'''
import random
import sys
a=random.randint(0,1)
print('the generated number is',a)
b=input('Is it too high,too low or your number: ')
if b=='your number':
sys.exit()
else:
count=1
while b!='your number':
a = random.randint(0, 3)
print('the generated number is', a)
b = input('Is it too high,too low or your number: ')
count+=1
print('The computer took {} guesses'.format(count)) | true |
6affb302816e8fcf5015596806c5082fa2d3d30d | abhisek08/Basic-Python-Programs | /problem5.py | 1,248 | 4.25 | 4 | '''
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
Extras:
Randomly generate two lists to test this
Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
List properties
'''
import random
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c=[]
d=0
while d<len(a):
if a[d] in b:
c.append(a[d])
d+=1
d=0
while d<len(b):
if b[d] in a:
c.append(b[d])
d+=1
print(set(c))
# randomly creating a list from a range of numbers using random module and random.sample(array,no. of reqd elements) function
a=random.sample(range(0,10),5)
b=random.sample(range(0,20),8)
print('the elements in a are: ',a)
print('the elements in b are: ',b)
c=[]
d=0
while d<len(a):
if a[d] in b:
c.append(a[d])
d+=1
d=0
while d<len(b):
if b[d] in a:
c.append(b[d])
d+=1
print('the unique elements in list a and b are: ',set(c)) | true |
107a32642f0def5ce58017a4d6156bebf1287a1c | abhisek08/Basic-Python-Programs | /problem16.py | 1,008 | 4.34375 | 4 | '''
Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wrong place is a “bull.”
Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
Once the user guesses the correct number, the game is over.
Keep track of the number of guesses the user makes throughout teh game and tell the user at the end.
Say the number generated by the computer is 1038. An example interaction could look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
Until the user guesses the number.
'''
import random
a=random.sample(range(1000,10000),1)
print('Welcome to the Cows and Bulls Game!')
user_input= int(input('Guess a 4 digit number: '))
| true |
cc0fe65d97a1914cc986b3dd480ff97bd8a53320 | wilsouza/RbGomoku | /src/core/utils.py | 1,504 | 4.28125 | 4 | import numpy as np
def get_diagonal(table, offset):
""" Get diagonal from table
Get a list elements referencing the diagonal by offset from main diagonal
:param table: matrix to get diagonal
:param offset: Offset of the diagonal from the main diagonal.
Can be positive or negative. Defaults to main diagonal (0).
:return: list elements from request diagonal
"""
diagonal = np.diag(table, k=offset).tolist()
return diagonal
def get_opposite_diagonal(table, offset):
""" Get diagonal from table
Get a list elements referencing the opposite
diagonal by offset from opposite diagonal
Positive get below, and negative get higher diagonal from opposite diagonal
0 1 2 3 4
0 a a a a .
1 a a a . b
2 a a . b b
3 a . b b b
4 . b b b b
:param table: matrix to get diagonal
:param offset: Offset of the opposite diagonal from the main diagonal.
Can be positive or negative. Defaults to opposite diagonal (0).
:return: list elements from request opposite diagonal
"""
column_inverted = table[:, ::-1]
transposed = column_inverted.transpose()
inverted_opp_diagonal = np.diag(transposed, k=-offset).tolist()
opposite_diagonal = inverted_opp_diagonal[::-1]
return opposite_diagonal | true |
7653c8e4c2176b8672a531988ef26c1331540b5d | bsundahl/IACS-Computes-2016 | /Instruction/Libraries/bryansSecondLibrary.py | 245 | 4.4375 | 4 | def factorial(n):
'''
This function takes an integer input and then prints out the factorial of that number.
This function is recursive.
'''
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1) | true |
7b5e3de71b6bdd958b6debafe5d0882503f87f20 | rahul-pande/ds501 | /hw1/problem1.py | 1,445 | 4.3125 | 4 | #-------------------------------------------------------------------------
'''
Problem 1: getting familiar with python and unit tests.
In this problem, please install python verion 3 and the following package:
* nose (for unit tests)
To install python packages, you can use any python package managment software, such as pip, conda. For example, in pip, you could type `pip install nose` in the terminal to install the package.
Then start implementing function swap().
You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.
'''
#--------------------------
def bubblesort( A ):
'''
Given a disordered list of integers, rearrange the integers in natural order using bubble sort algorithm.
Input: A: a list, such as [2,6,1,4]
Output: a sorted list
'''
for i in range(len(A)):
for k in range( len(A) - 1, i, -1):
if ( A[k] < A[k - 1] ):
swap( A, k, k - 1 )
#--------------------------
def swap( A, i, j ):
'''
Swap the i-th element and j-th element in list A.
Inputs:
A: a list, such as [2,6,1,4]
i: an index integer for list A, such as 3
j: an index integer for list A, such as 0
'''
#########################################
## INSERT YOUR CODE HERE
A[i], A[j] = A[j], A[i]
#########################################
| true |
7de333d37e0af493325591c525cef536290f13be | GameroM/Lists_Practice | /14_Lists_Even_Extract.py | 360 | 4.21875 | 4 | ## Write a Python program to print the numbers of a specified list after removing
## even numbers from it
x = [1,2,3,4,5,6,7,8,15,20,25,42]
newli = []
def evenish():
for elem in x:
if elem % 2 != 0:
newli.append(elem)
return newli
print('The original list is:', x)
print('The list without even numbers is',evenish())
| true |
0632f5713b13eb0b83c1866566125a069d4f997d | GameroM/Lists_Practice | /8_Lists_Empty_Check.py | 445 | 4.375 | 4 | ## Write a Python program to check if a list is empty or not
x = []
def creation():
while True:
userin=input('Enter values,type exit to stop:')
if userin == 'exit':
break
else:
x.append(userin)
return x
print('The list created from user input is:',creation())
if x == []:
print('The list created is empty')
else:
print('The list created is not empty')
| true |
8a8ccbf32880b637bba81516a69e23b3cabd2229 | blackseabass/Python-Projects | /Homework/week5_exercise2.py | 1,483 | 4.3125 | 4 | #!/usr/bin/env python
"""
File Name: week5_exercise2.py
Developer: Eduardo Garcia
Date Last Modified: 10/4/2014
Description: User plays Rock, Paper, Sciissors with
the computer
Email Address: garciaeduardo1223@gmail.com
"""
import random
def main():
print("Rock. Paper. Scissors." "\n" "Enter 1 for Rock, 2 for Paper or 3 for Scissors.", "\n")
answer()
def random_integer():
return random.randrange(1,3)
def answer():
player = int(input("Enter your choice: "))
while player != 1 and player != 2 and player != 3:
print("Invalid entry. Please try again.")
player = int(input("Enter 1, 2, or 3.: "))
display_answer(player)
def display_answer(player):
computer_answer = random_integer()
print("Computer picks: ", computer_answer, "\n")
winner(computer_answer, player)
def winner(computer, player):
if computer == player:
print("Draw. Try again.")
answer()
elif computer == 1 and player == 2:
print("Paper covers rock. Player wins!")
elif computer == 1 and player == 3:
print("Rock smashes scissors. Computer wins.")
elif computer == 2 and player == 1:
print("Paper covers rock. Computer wins.")
elif computer == 2 and player == 3:
print("Scissors cut paper. Player wins!")
elif computer == 3 and player == 1:
print("Rock smashes scissors. Player wins!")
elif computer == 3 and player == 2:
print("Scissors cut paper. Computer wins.")
main()
| true |
c8639d6ef1d7044f1a840f7446fc7cfb624a1209 | amitravikumar/Guvi-Assignments | /Program14.py | 283 | 4.3125 | 4 | #WAP to find the area of an equilateral triangle
import math
side = float(input("Enter the side: "))
def find_area_of_triangle(a):
return(round(((1/4) * math.sqrt(3) * (a**2)), 2))
result = find_area_of_triangle(side)
print("Area of equilateral triangle is ", result) | true |
5e5803c836e3d83613e880061b29d6862774836b | amitravikumar/Guvi-Assignments | /Program4.py | 309 | 4.3125 | 4 | #WAP to enter length and breadth of a rectangle and find its perimeter
length, breadth = map(float,input("Enter length and breadth with spaces").split())
def perimeter_of_rectangle(a,b):
return 2*(a+b)
perimeter = perimeter_of_rectangle(length,breadth)
print("Perimeter of rectangle is", perimeter) | true |
1971a9a13cc857df612840450c1fb3f455d8a034 | gitfolder/cct | /Python/calculator.py | 1,680 | 4.21875 | 4 | # take user input and validate, keep asking until number given, or quit on CTRL+C or CTR+D
def number_input(text):
while True:
try: return float(input(text))
except ValueError: print("Not a number")
except (KeyboardInterrupt, EOFError): raise SystemExit
def print_menu():
print("\n1. Add\n2. Substract\n3. Multiply\n4. Divide\n0. Exit")
return number_input("Select option : ")
# recursively calling this function to run
def select_option( opt ):
if opt == 0: return
elif opt == 1: add()
elif opt == 2: substract()
elif opt == 3: multiply()
elif opt == 4: divide()
else: print("Not an option")
select_option( print_menu() )
def add():
amount = number_input("Enter how many numbers you want to sum : ")
total = 0
for n in range(int(amount)):
total += number_input("Enter number {0} : ".format(n+1))
print( "\nSum result : " + str( total ))
def substract():
one = number_input("Provide first number : ")
two = number_input("Provide second number : ")
print( "\nSubstraction result : " + str( one-two))
def multiply():
amount = number_input("Enter how many numbers you want to multiply : ")
product = 1.0 if amount>0 else 0
for n in range(int(amount)):
product *= number_input("Enter number {0} : ".format(n+1))
print( "\nMultiplication result : " + str( product ))
def divide():
one = number_input("Provide first number : ")
two = number_input("Provide second number : ")
if two == 0: print("Cannot divide by zero")
else: print( "\nDivision result : " + str( one/two))
select_option( print_menu() ) # initial call | true |
45b822d5189e7e8317f7deb26deed12e7562d29e | jebarajganesh1/Ds-assignment- | /Practical 5.py | 1,415 | 4.1875 | 4 | #Write a program to search an element from a list. Give user the option to perform
#Linear or Binary search.
def LinearSearch(array, element_l):
for i in range (len(array)):
if array[i] == element_l:
return i
return -1
def BinarySearch(array, element_l):
first = 0
array.sort()
last = len(array)-1
done = False
while (first <= last) and not done:
mid = (first+last)//2
if array[mid] == element_l:
done = True
else:
if element_l < array[mid]:
last = last - 1
else:
first = first + 1
return done
array = [45,78,23,17,453,7]
print(array)
element_l = int(input("Enter the element you want to search : "))
print("Select 'L' for Linear Search and 'B' for Binary Search")
yourChoice = str(input("Enter your choice : "))
if yourChoice == 'L':
result = LinearSearch(array, element_l)
print(result)
if result == 1:
print("Element is present.")
else :
print("Element not present.")
else:
result = BinarySearch(array, element_l)
print(result)
if result == -1:
print("Element not present.")
else :
print("Element is present.")
| true |
cfa2dee09f7d4b7dec7c328f8cef5f085e17dd95 | Amirreza5/Class | /example_comparison02.py | 218 | 4.125 | 4 | num = int(input('How many numbers do you want to compare: '))
list_num = list()
for i in range(0, num):
inp_num = int(input('Please enter a number: '))
list_num.append(inp_num)
list_num.sort()
print(list_num) | true |
5436a11b86faa2784d2a3aab6b9449bbca9df2fd | mynameismon/12thPracticals | /question_6#alt/question_6.py | 1,755 | 4.125 | 4 | <<<<<<< HEAD
# Create random numbers between any two values and add them to a list of fixed size (say 5)
import random
#generate list of random numbers
def random_list(size, min, max):
lst = []
for i in range(size):
lst.append(random.randint(min, max))
return lst
x = random_list(5, 1, 100)
# the list of random numbers
print("The list of random numbers is:")
print(x)
l = int(input("Enter a number you would like to insert"))
# enter the index to be inserted in x
i = int(input("Enter the index to be inserted"))
# insert the number in the list
x.insert(i, l)
print("The list after insertion is:")
print(x)
# Would you like to delete a number from the list?
y = input("Would you like to delete a number from the list? (y/n)")
if y == "y":
# enter the index to be deleted
j = int(input("Enter the index to be deleted"))
# delete the number from the list
x.pop(j)
print("The list after deletion is:")
print(x)
else:
print("Thank you for using the program")
=======
def generate(n=5):
import random
a=int(input("Enter base number : "))
b=int(input("Enter ceiling number : "))
for i in range(0,n) :
x=round(a+(b-a)*random.random(),2)
list1.append(x)
print(list1)
global val
val=float(input("Enter value to be removed: "))
temp(val)
def update(pos,num) :
list1.insert(pos-1,num)
print(list1)
def temp(val) :
list1.remove(val)
print(list1)
global num
global pos
num=int(input("Enter value to be inserted : "))
pos=int(input("Enter position from start of previous value (1 onward) : "))
update(pos,num)
n=int(input("Enter length of list : "))
list1=[]
generate(n)
>>>>>>> 964a130e5215f229fac07a4e9133df869309fe82
| true |
2b7b16fe2ba676de0de95fd695afa8ab9af61544 | RicaBenhossi/Alura-Learning | /Python/01-DataStructure_Python/route_linked_list.py | 2,136 | 4.15625 | 4 | from data_structure.linked_list import LinkedList
class Store:
def __init__(self, name, address) -> None:
self.name = name
self.address = address
def __repr__(self) -> str:
return '{}\n {}'.format(self.name, self.address)
def show_result(lnk_list: LinkedList) -> None:
print()
print('Whole list')
lnk_list.print_list()
print(f'Amount of store listed: {lnk_list.quantity}')
print()
print('-' * 80)
print()
def main():
store1 = Store('Mercadinho', 'Rua das Laranjeiras, 12')
store2 = Store('Horti Fruti', 'Rua do Pomar, 300')
store3 = Store('Padaria', 'Rua das Flores, 600')
store4 = Store('Supermercado', 'Alameda Santos, 400')
store5 = Store('Mini Mercado', 'Rua da Fazenda, 900')
store6 = Store('Quitanda', 'Avenida Rio Branco, 34')
lnk_list = LinkedList()
print('Inserting at begining')
lnk_list.insert_at_beginning(store1)
lnk_list.insert_at_beginning(store2)
lnk_list.insert_at_beginning(store3)
show_result(lnk_list)
print('Insert in a position')
lnk_list.insert(1, store4)
lnk_list.insert(0, store5)
lnk_list.insert(lnk_list.quantity, store6)
print('Inserted on position 1, 0 and 6')
# Should be:
# store5
# store4
# store1
# store2
# store3
# store6
show_result(lnk_list)
print('Remove from begining')
removed_item = lnk_list.remove_from_beginning()
print(f'Removed item {removed_item}')
print()
removed_item = lnk_list.remove_from_beginning()
print(f'Removed item {removed_item}')
show_result(lnk_list)
print('Remove from any position')
store_removed_position = lnk_list.remove(2)
print(f'Store of position 2 (removed) is\n{store_removed_position}')
show_result(lnk_list)
print('Remove from position 0')
removed_item = lnk_list.remove(0)
print(f'Removed store on position 0: {removed_item}')
show_result(lnk_list)
print('Getting the store located by index 1')
store_index = lnk_list.item(1)
print(store_index)
# the class tha implements linked lists in python is LIST
main()
| false |
18ab5a5323df219b155c0681ce69e45a3b8dd2fc | Baltiyski/HackBulgaria | /Programming0-1/week01/02-If-Elif-Else-Simple-Problems/calculator.py | 485 | 4.21875 | 4 | a = input("Enter a: ");
a = int(a);
b = input("Enter b: ");
b = int(b);
oper = input("Enter operation : ");
result = 0;
if(oper == "+"):
result = a + b;
print("Result is: ")
print(result)
elif(oper == "-"):
result = a - b;
print("Result is: ")
print(result)
elif(oper == "*"):
result = a * b;
print("Result is: ")
print(result)
elif(oper == "/"):
result = a / b;
print("Result is: ")
print(result)
else:
print("Wrong operation");
| false |
542c400ed5a8bfb88006ce3b2c7f881088720131 | YANYANYEAH/jianzhi-offor-python | /16_数值的整数次方.py | 1,609 | 4.40625 | 4 | # -*- coding:utf-8 -*-
# // 面试题16:数值的整数次方
# // 题目:实现函数double Power(double base, int exponent),求base的exponent
# // 次方。不得使用库函数,同时不需要考虑大数问题。
# tips: 考虑特殊条件,比如 exponent 为负数, 此时结果需要取倒数
# 当结果去倒数的时候,需要考虑分母为0的情况,0^n = 0或者1,n^0 = 1
# 此处需要考虑 简单的方法,比如a^n = a^(n/2) * a^(n/2) 此时需要考虑n为奇数还是偶数
# def get_result(base, exponent):
# if exponent == 0:
# return 1
# elif exponent == 1:
# return base
# else:
# if exponent%2 ==1:
# result = get_result(base, exponent/2)
# result = result * result * base
# else:
# result = get_result(base, exponent/2)
# return result
# 此时考虑位运算,加速,每移一位相当于开方
def get_result(base, exponent):
if exponent == 0:
return 1
elif exponent == 1:
return base
else:
result = get_result(base, exponent >> 1)
result *= result
if exponent & 1 == 1:
result *= base
return result
def get_value(base, exponent):
if base == 0:
return 0
elif exponent < 0:
result = get_result(base,-exponent)
return 1.0/result
else:
result = get_result(base, exponent)
return result
if __name__ == '__main__':
base = input("input base:")
exponent = input("input exponent:")
print get_value(base, exponent) | false |
f58cd8b8c7c7f9f8175fb0816e0ae8073d6101d1 | magdeevd/gb-python | /homework_5/third.py | 1,052 | 4.15625 | 4 | def main():
"""
3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов
(не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
Выполнить подсчет средней величины дохода сотрудников.
"""
salaries = {}
with open('files/third.txt') as file:
for line in file:
name, salary = line.split()
salaries[name] = float(salary)
less_than_20000 = [name for name, salary in salaries.items() if salary < 20000]
average_salary = sum(salaries.values()) / len(salaries)
print(f'Сотрудники с окладом меньше 20000: {", ".join(less_than_20000)}')
print(f'Средняя зарплата: {average_salary}')
if __name__ == '__main__':
main()
| false |
38ac39d0e0b2827c8bc495ffd72b551ac1bda54e | JulhaMouraR/BiotecGirls | /Hackathon.py | 878 | 4.1875 | 4 | import sqlite3
conn = sqlite3.connect('estudantes.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS students(
UserID VARCHAR(20) NOT NULL,
username VARCHAR(60) NOT NULL,
firstname VARCHAR(60) NOT NULL,
email VARCHAR(60) NOT NULL,
password VARCHAR(80) NOT NULL);
''')
#gravando no bd
conn.commit()
#solicitando dados
p_1 = input('UserID: ')
p_2 = input('username: ')
p_3 = input('firstname: ')
p_4 = input('email: ')
p_5 = input('password: ')
#inserindo informações
cursor.execute('''
INSERT INTO students(UserID, username, firstname, password)
VALUES(?,?,?,?)
''', (p_1, p_2, p_3, p_4, p_5))
print('Dados inseridos com sucesso!!!')
#gravando no bd
conn.commit()
#verificando inversão
#lendo os dados
cursor.execute("""
SELECT*FROM students;
""")
print('lendo dados inseridos')
for linha in cursor.fetchall():
print(linha)
cursor.close()
| false |
6a3ca57e16621b671baeb4343ed1a82c6da2f4c9 | jonathanjaimes/python | /5.7_perimetro.py | 1,564 | 4.15625 | 4 |
#En esta primera función se ingresan los datos necesarios.
def tomaDatos():
punto1 = input("Ingrese el nombre del primer punto: ")
x1 = float(input(f"Ingrese la primera coordenada del punto {punto1}: "))
y1 = float(input(f"Ingres la segunda coordenada del punto {punto1}: "))
punto2 = input("Ingrese el nombre del primer punto: ")
x2 = float(input(f"Ingrese la primera coordenada del punto {punto2}: "))
y2 = float(input(f"Ingres la segunda coordenada del punto {punto2}: "))
punto3 = input("Ingrese el nombre del primer punto: ")
x3 = float(input(f"Ingrese la primera coordenada del punto {punto3}: "))
y3 = float(input(f"Ingres la segunda coordenada del punto {punto3}: "))
return punto1, punto2, punto3, x1, y1, x2, y2, x3, y3
#En esta segunda función, realizamos las operaciones respectivas.
def distancia(x1, x2, x3, y1, y2, y3):
distancia1 = (((x2-x1)**2) + ((y2-y1)**2))**(1/2)
distancia2 = (((x3-x2)**2) + ((y3-y2)**2))**(1/2)
distancia3 = (((x3-x1)**2) + ((y3-y1)**2))**(1/2)
distanciaTotal = distancia1 + distancia2 + distancia3
return distanciaTotal
#En esta última función se imprimen los resultados obtenidos a partir de la segunda función.
def salida(x1, x2, x3, y1, y2, y3, punto1, punto2, punto3, distanciaTotal):
print(f"La distancia entre los puntos {punto1}, {punto2}, {punto3} es {distanciaTotal}")
punto1, punto2, punto3, x1, y1, x2, y2, x3, y3 = tomaDatos()
distanciaTotal = distancia(x1, x2, x3, y1, y2, y3)
salida(x1, x2, x3, y1, y2, y3, punto1, punto2, punto3, distanciaTotal) | false |
2300e2a3c3ccb603907e2bcbd895f25cbbca504d | Enfioz/enpands-problems | /weekdays.py | 535 | 4.34375 | 4 | # Patrick Corcoran
# A program that outputs whether or not
# today is a weekday or is the weekend.
import datetime
now = datetime.datetime.now()
current_day = now.weekday
weekend = (5,7)
if current_day == weekend:
print("It is the weekend, yay!")
else:
print("Yes, unfortunately today is a weekday.")
time_diff = datetime.timedelta(days = 4)
future_day = now + time_diff
weekend = (5,7)
if future_day == weekend:
print("It is the weekend, yay!")
else:
print("Yes, unfortunately today is a weekday.")
| true |
6c511888f1cfcb208e0aa3a03d5c2cbfe2e7b015 | Aninda05/Java-only | /lambda.py | 308 | 4.1875 | 4 | print("*****THE SUM OF SQUARES USING LAMBDA*****\n")
x=int(input("Enter the first number:"))
y=int(input("Enter the second number:"))
z=int(input("Enter the third number:"))
def fuc(x,y,z):
a=lambda x:x*x
b=lambda x,y:x+y*y
c=lambda y,z:y+z*z
return(c(b(a(x),y),z))
print"The result is: ",fuc(x,y,z)
| false |
617d4aa7fd56d6511a28954c6bfd384c8b9251d1 | andreeaanbrus/Python-School-Assignments | /Assignment 1/8_setB.py | 893 | 4.25 | 4 | '''
Determine the twin prime numbers p1 and p2 immediately larger than the given non-null
natural number n. Two prime numbers p and q are called twin if q-p = 2.
'''
def read():
x = int(input("Give the number: "))
return x
def isPrime(x):
if(x < 2):
return False
if(x > 2 and x % 2 == 0):
return False
for d in range(3, int(x / 2), 2):
if(x % d == 0):
return False
return True
def twin(x, y):
if(y - x == 2):
return True
return False
def printNumbers(a, p1):
print("The twin prime numbers immediately larger than the given number",a,"are", p1)
def determineTwinPrimeNumbers(x):
n = x + 1
ok = False
while(not ok):
if(isPrime(n) and isPrime(n + 2)):
return (n, n+2)
n = n + 1
a = read()
printNumbers(a, determineTwinPrimeNumbers(a))
| true |
cc608e03490880b23f1cb4e53a781670cb898d01 | vlad-bezden/py.checkio | /oreilly/reverse_every_ascending.py | 1,364 | 4.40625 | 4 | """Reverse Every Ascending
https://py.checkio.org/en/mission/reverse-every-ascending/
Create and return a new iterable that contains the same elements
as the argument iterable items, but with the reversed order of
the elements inside every maximal strictly ascending sublist.
This function should not modify the contents of the original iterable.
Input: Iterable
Output: Iterable
Precondition: Iterable contains only ints
"""
from typing import List
def reverse_ascending(items: List[int]) -> List[int]:
result = []
cursor = 0
for i in range(1, len(items)):
if items[i] <= items[i - 1]:
result.extend(reversed(items[cursor:i]))
cursor = i
result = result + [*reversed(items[cursor:])]
return result
if __name__ == "__main__":
assert list(reverse_ascending([1, 2, 3, 4, 5])) == [5, 4, 3, 2, 1]
assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [
10,
7,
5,
4,
8,
7,
2,
3,
1,
]
assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1]
assert list(reverse_ascending([])) == []
assert list(reverse_ascending([1])) == [1]
assert list(reverse_ascending([1, 1])) == [1, 1]
assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1]
print("PASSED!!!")
| true |
d0ef4d781f2518afb1210abedf14239e6b06c0e2 | vlad-bezden/py.checkio | /oreilly/remove_all_after.py | 1,247 | 4.65625 | 5 | """Remove All After.
https://py.checkio.org/en/mission/remove-all-after/
Not all of the elements are important.
What you need to do here is to remove all of the
elements after the given one from list.
For illustration, we have an list [1, 2, 3, 4, 5]
and we need to remove all the elements that go after 3 -
which is 4 and 5.
We have two edge cases here:
(1) if a cutting element cannot be found, then the list shoudn't be changed;
(2) if the list is empty, then it should remain empty.
Input: List and the border element.
Output: Iterable (tuple, list, iterator ...).
"""
from typing import List
def remove_all_after(items: List[int], border: int) -> List[int]:
return items[:items.index(border) + 1] if border in items else items
if __name__ == "__main__":
assert list(remove_all_after([1, 2, 3, 4, 5], 3)) == [1, 2, 3]
assert list(remove_all_after([1, 1, 2, 2, 3, 3], 2)) == [1, 1, 2]
assert list(remove_all_after([1, 1, 2, 4, 2, 3, 4], 2)) == [1, 1, 2]
assert list(remove_all_after([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7]
assert list(remove_all_after([], 0)) == []
assert list(remove_all_after([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7]
print("PASSED!!!")
| true |
56e4820a3eb210789a5b4d86cf4386d4028edb91 | vlad-bezden/py.checkio | /oreilly/how_deep.py | 1,704 | 4.5625 | 5 | """How Deep.
https://py.checkio.org/en/mission/how-deep/
You are given a tuple that consists of integers and other tuples,
which in turn can also contain tuples.
Your task is to find out how deep this structure is or how deep
the nesting of these tuples is.
For example, in the (1, 2, 3) tuple the depth of nesting is 1.
And in the (1, 2, (3,)) tuple the depth of nesting is 2,
since one of the elements of the first tuple is also a tuple.
And in the (1, 2, (3, (4,))) tuple the depth of nesting is 3,
since one of the elements of the first tuple is a tuple,
but since inside it contains another tuple, it increases the depth by one,
so the nesting depth turns out to be 3.
It’s important to note that an empty tuple also increases
the depth of the structure, that is, () - indicates the nesting depth 1,
((),) - indicates the nesting depth 2.
Input: Tuple of tuple of tuple...
Output: Int.
Precondition: Given iterables have to be well founded.
"""
from typing import Any, Iterable, Tuple, Union
T = Union[int, Tuple[Any]]
def how_deep(structure: Tuple[T, ...]) -> int:
return 1 + max(
(how_deep(t) for t in structure if isinstance(t, Iterable)), default=0
)
if __name__ == "__main__":
assert how_deep((1, 2, 3)) == 1
assert how_deep((1, 2, (3,))) == 2
assert how_deep((1, 2, (3, (4,)))) == 3
assert how_deep(()) == 1
assert how_deep(((),)) == 2
assert how_deep((((),),)) == 3
assert how_deep((1, (2,), (3,))) == 2
assert how_deep((1, ((),), (3,))) == 3
assert how_deep((1, 2, ((3,), (4,)))) == 3
assert how_deep((((), (), ()),)) == 3
print("PASSED!!!")
| true |
4ea6cc426ebeeaf6f594465a48a6bfb836555467 | vlad-bezden/py.checkio | /mine/perls_in_the_box.py | 2,354 | 4.65625 | 5 | """Pearls in the Box
https://py.checkio.org/en/mission/box-probability/
To start the game they put several black and white pearls in
one of the boxes. Each robot has N moves, after which the
initial set is being restored for the next game.
Each turn, the robot takes a pearl out of the box and puts one
of the opposite color back. The winner is the one who
takes the white pearl on the Nth move.
Our robots don't like uncertainty, that's why they want to
know the probability of drawing a white pearl on the Nth move.
The probability is a value between 0 (0% chance or will not happen)
and 1 (100% chance or will happen). The result is a float
from 0 to 1 with two decimal digits of precision (±0.01).
You are given a start set of pearls as a string that contains
"b" (black) and "w" (white) and the number of the move (N).
The order of the pearls does not matter.
Input: The start sequence of the pearls as a string and the move number as an integer.
Output: The probability for a white pearl as a float.
Example:
checkio('bbw', 3) == 0.48
checkio('wwb', 3) == 0.52
checkio('www', 3) == 0.56
checkio('bbbb', 1) == 0
checkio('wwbb', 4) == 0.5
checkio('bwbwbwb', 5) == 0.48
Precondition: 0 < N ≤ 20
0 < |pearls| ≤ 20
"""
def checkio(marbles, step):
n = len(marbles)
def move(w, b, step):
if step == 1:
return w / n
p1 = 0 if b == 0 else move(w + 1, b - 1, step - 1)
p2 = 0 if w == 0 else move(w - 1, b + 1, step - 1)
return w / n * p2 + b / n * p1
return round(move(marbles.count("w"), marbles.count("b"), step), 2)
if __name__ == "__main__":
result = checkio("wbb", 3)
assert result == 0.48, f"1st {result=}"
result = checkio("wwb", 3)
assert result == 0.52, f"2nd {result=}"
result = checkio("www", 3)
assert result == 0.56, f"3rd {result=}"
result = checkio("bbbb", 1)
assert result == 0, f"4th {result=}"
result = checkio("wwbb", 4)
assert result == 0.5, f"5th {result=}"
result = checkio("bwbwbwb", 5)
assert result == 0.48, f"6th {result=}"
result = checkio("w" * 20, 20)
assert result == 0.57, f"7th {result=}"
result = checkio("b" * 20, 20)
assert result == 0.43, f"8th {result=}"
print("PASSED!")
| true |
7956966c7aa9ffed8da7d23e75d98ae1867c376a | vlad-bezden/py.checkio | /electronic_station/similar_triangles.py | 2,498 | 4.28125 | 4 | """Similar Triangles
https://py.checkio.org/en/mission/similar-triangles/
This is a mission to check the similarity of two triangles.
You are given two lists as coordinates of vertices of each triangle.
You have to return a bool. (The triangles are similar or not)
Example:
similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True
similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False
similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True
Input:
Two lists as coordinates of vertices of each triangle.
Coordinates is three tuples of two integers.
Output:
True or False.
Precondition:
-10 ≤ x(, y) coordinate ≤ 10
"""
from __future__ import annotations
from math import dist
from typing import List, Tuple
from dataclasses import dataclass
from itertools import combinations
Coords = List[Tuple[int, int]]
@dataclass
class Triangle:
a: float
b: float
c: float
def __init__(self, coord: Coords):
"""Calculate degrees between a and b sides"""
self.a, self.b, self.c = sorted(
dist(c1, c2) for c1, c2 in combinations(coord, 2)
)
def is_similar(self, other: Triangle) -> bool:
"""Check if triangles are similar."""
return (
round(self.a / other.a, 2)
== round(self.b / other.b, 2)
== round(self.c / other.c, 2)
)
def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool:
return Triangle(coords_1).is_similar(Triangle(coords_2))
if __name__ == "__main__":
assert (
similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]) is True
), "basic"
assert (
similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 3), (5, 0)]) is False
), "different #1"
assert (
similar_triangles([(0, 0), (1, 2), (2, 0)], [(2, 0), (4, 4), (6, 0)]) is True
), "scaling"
assert (
similar_triangles([(0, 0), (0, 3), (2, 0)], [(3, 0), (5, 3), (5, 0)]) is True
), "reflection"
assert (
similar_triangles([(1, 0), (1, 2), (2, 0)], [(3, 0), (5, 4), (5, 0)]) is True
), "scaling and reflection"
assert (
similar_triangles([(1, 0), (1, 3), (2, 0)], [(3, 0), (5, 5), (5, 0)]) is False
), "different #2"
assert (
similar_triangles([(2, -2), (1, 3), (-1, 4)], [(-10, 10), (-1, -8), (-4, 7)])
is True
)
print("PASSED!!!")
| true |
d880c75abc5b1980a6e0bd5b2435c647963a08d1 | vlad-bezden/py.checkio | /oreilly/median_of_three.py | 1,986 | 4.125 | 4 | """Median of Three
https://py.checkio.org/en/mission/median-of-three/
Given an List of ints, create and return a new List
whose first two elements are the same as in items,
after which each element equals the median of the three elements
in the original list ending in that position.
Input: List of ints.
Output: List of ints.
Output:
median_three_sorted([1, 2, 3, 4, 5, 6, 7]) => 0.000359
median_three_zip([1, 2, 3, 4, 5, 6, 7]) => 0.000379
median_three_sorted([1]) => 0.000080
median_three_zip([1]) => 0.000119
median_three_sorted([]) => 0.000060
median_three_zip([]) => 0.000105
Conclusion:
Using sorted works faster when there are less items in the list. With more items
both sorted and zip have almost the same time.
"""
from statistics import median
from typing import Callable, List, Sequence
from dataclasses import dataclass
from timeit import repeat
@dataclass
class Test:
data: List[int]
expected: List[int]
TESTS = [
Test([1, 2, 3, 4, 5, 6, 7], [1, 2, 2, 3, 4, 5, 6]),
Test([1], [1]),
Test([], []),
]
def median_three_sorted(items: List[int]) -> List[int]:
return [
v if i < 2 else sorted(items[i - 2 : i + 1])[1]
for i, v in enumerate(items)
]
def median_three_zip(items: List[int]) -> List[int]:
return items[:2] + [*map(median, zip(items, items[1:], items[2:]))]
def validate(funcs: Sequence[Callable[[List[int]], List[int]]]) -> None:
for test in TESTS:
for f in funcs:
result = f(test.data)
assert result == test.expected, f"{f.__name__}({test}), {result = }"
print("PASSED!!!")
if __name__ == "__main__":
funcs = [median_three_sorted, median_three_zip]
validate(funcs)
for test in TESTS:
for f in funcs:
t = repeat(stmt=f"f({test.data})", repeat=3, number=100, globals=globals())
print(f"{f.__name__}({test.data}) => {min(t):.6f}")
print()
| true |
d8803c10cf12c5afb6898dd2c5cce4e7be0adeed | vlad-bezden/py.checkio | /oreilly/chunk.py | 1,083 | 4.4375 | 4 | """Chunk.
https://py.checkio.org/en/mission/chunk/
You have a lot of work to do, so you might want to split it into smaller pieces.
This way you'll know which piece you'll do on Monday,
which will be for Tuesday and so on.
Split a list into smaller lists of the same size (chunks).
The last chunk can be smaller than the default chunk-size.
If the list is empty, then you shouldn't have any chunks at all.
Input: Two arguments. A List and chunk size.
Output: An List with chunked List.
Precondition: chunk-size > 0
"""
from typing import List
def chunking_by(items: List[int], size: int) -> List[List[int]]:
return [items[s : s + size] for s in range(0, len(items), size)]
if __name__ == "__main__":
assert list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3)) == [[5, 4, 7], [3, 4, 5], [4]]
assert list(chunking_by([3, 4, 5], 1)) == [[3], [4], [5]]
assert list(chunking_by([5, 4], 7)) == [[5, 4]]
assert list(chunking_by([], 3)) == []
assert list(chunking_by([4, 4, 4, 4], 4)) == [[4, 4, 4, 4]]
print("PASSED!!!")
| true |
a1241876f32a8cbcfa522b6393ae8ba20837549b | vlad-bezden/py.checkio | /elementary/split_list.py | 885 | 4.375 | 4 | """Split List
https://py.checkio.org/en/mission/split-list/
You have to split a given array into two arrays.
If it has an odd amount of elements,
then the first array should have more elements.
If it has no elements, then two empty arrays should be returned.
example
Input: Array.
Output: Array or two arrays.
Example:
split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]]
split_list([1, 2, 3]) == [[1, 2], [3]]
"""
def split_list(items: list) -> list:
i = (len(items) + 1) // 2
return [items[:i], items[i:]]
if __name__ == "__main__":
assert split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]]
assert split_list([1, 2, 3]) == [[1, 2], [3]]
assert split_list([1, 2, 3, 4, 5]) == [[1, 2, 3], [4, 5]]
assert split_list([1]) == [[1], []]
assert split_list([]) == [[], []]
print("PASSED!!!")
| true |
93b69fd2a07e076c8d968d862e19bb1831aa6aab | vlad-bezden/py.checkio | /mine/skew-symmetric_matrix.py | 2,305 | 4.1875 | 4 | """Skew-symmetric Matrix
https://py.checkio.org/en/mission/skew-symmetric-matrix/
In mathematics, particularly in linear algebra, a skew-symmetric matrix
(also known as an antisymmetric or antimetric) is a square matrix A
which is transposed and negative. This means that it satisfies the
equation A = −AT. If the entry in the i-th row and j-th column is aij,
i.e. A = (aij) then the symmetric condition becomes aij = −aji.
You should determine whether the specified square matrix is skew-symmetric or not.
Input: A square matrix as a list of lists with integers.
Output: If the matrix is skew-symmetric or not as a boolean.
Example:
checkio([
[ 0, 1, 2],
[-1, 0, 1],
[-2, -1, 0]]) == True
checkio([
[ 0, 1, 2],
[-1, 1, 1],
[-2, -1, 0]]) == False
checkio([
[ 0, 1, 2],
[-1, 0, 1],
[-3, -1, 0]]) == False
Precondition: 0 < N < 5
Output:
checkio_product 0.0713
checkio_product 0.0430
checkio_product 0.0354
checkio_zip 0.0296
checkio_zip 0.0299
checkio_zip 0.0291
checkio_allclose 0.7690
checkio_allclose 0.7574
checkio_allclose 0.7623
"""
from timeit import timeit
from itertools import product
from numpy import allclose, array
def using_product(matrix):
return not any(
matrix[i][j] + matrix[j][i] for i, j in product(range(len(matrix)), repeat=2)
)
def using_zip(matrix):
return matrix == [[-x for x in row] for row in zip(*matrix)]
def using_allclose(matrix):
return allclose(matrix, -array(matrix).T)
def using_classic(matrix):
n = len(matrix)
return not any(matrix[i][j] + matrix[j][i] for i in range(n) for j in range(i, n))
if __name__ == "__main__":
tests = [
([[0, 1, 2], [-1, 0, 1], [-2, -1, 0]], True),
([[0, 1, 2], [-1, 1, 1], [-2, -1, 0]], False),
([[0, 1, 2], [-1, 0, 1], [-3, -1, 0]], False),
]
for func in [using_product, using_zip, using_allclose, using_classic]:
for data, result in tests:
assert func(data) is result
t = timeit(stmt=f"func({data})", number=10_000, globals=globals())
print(f"{func.__name__} {t:.4f}")
print("PASSED!")
| true |
b1dee53024fb0e1420d3d3443eb26f6f2c949bf1 | linkel/MITx-6.00.1x-2018 | /Week 1 and 2/alphacount2.py | 1,218 | 4.125 | 4 | s = 'kpreasymrrs'
longest = s[0]
longestholder = s[0]
#go through the numbers of the range from the second letter to the end
for i in (range(1, len(s))):
#if this letter is bigger or equal to the last letter in longest variable then add it on (meaning alphabetical order)
if s[i] >= longest[-1]:
longest = longest + s[i]
#if this letter is smaller, meaning not in order, and so far longest is longer than my holder, then save longest into the holder and restart longest at my pointer
elif s[i] < longest[-1] and (len(longestholder) < len(longest)):
longestholder = longest
longest = s[i]
#if the letter is not in alpha order and longest ain't the longer one between it and holder then just start over
elif s[i] < longest[-1]:
longest = s[i]
#this last check is necessary for the case where we find the longest and it ends with the last letter, so it doesn't hit my elif check
if len(longestholder) < len(longest):
longestholder = longest
print("Longest substring in alphabetical order is: " + longestholder)
#holy dingdongs man. Took me a full hour, and I had to look up that python can compare letters by their ascii value and get a bool. pretty convenient | true |
fc17ad2770c01b01220527948074999663a5cb0e | amir-mersad/ICS3U-Unit5-01-Python | /function.py | 885 | 4.46875 | 4 | #!/usr/bin/env python3
# Created by: Amir Mersad
# Created on: November 2019
# This program converts temperature in degrees Celsius
# to temperature degrees Fahrenheit
def celsius_to_fahrenheit():
# This program converts temperature in degrees Celsius
# to temperature degrees Fahrenheit
# Input
celsius_degree = input("Please enter the temperature in degrees Celsius: ")
# Process
try:
# The numbers need to be float because we cannot
# multiply float by an int
celsius_degree = float(celsius_degree)
fahrenheit_degree = 1.8 * celsius_degree + 32.0
# Output
print("\nThe temperature in degrees fahrenheit is", fahrenheit_degree)
except(Exception):
print("Wrong input!!!")
def main():
# This function calls other functions
celsius_to_fahrenheit()
if __name__ == "__main__":
main()
| true |
3fe8ff6ea8a307276a311b01f494c3e92175868d | corridda/Studies | /Articles/Python/pythonetc/year_2018/september/operator_and_slices.py | 2,069 | 4.5 | 4 | """Оператор [] и срезы"""
"""В Python можно переопределить оператор [], определив магический метод __getitem__.
Так, например, можно создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:"""
class Cycle:
def __init__(self, lst):
self._lst = lst
def __getitem__(self, index):
return self._lst[
index % len(self._lst)
]
print(Cycle(['a', 'b', 'c'])[100]) # 'b'
print(Cycle(['a', 'b', 'c'])[1000]) # 'b'
print(Cycle(['a', 'b', 'c'])[1001]) # 'c'
print(Cycle(['a', 'b', 'c'])[1002], '\n') # 'a'
"""Необычное здесь заключается в том, что оператор [] поддерживает уникальный синтаксис.
С его помощью можно получить не только [2], но и [2:10], [2:10:2], [2::2] и даже [:].
Семантика оператора такая: [start:stop:step], однако вы можете использовать его любым иным образом
для создания кастомных объектов.
Но если вызывать с помощью этого синтаксиса __getitem__, что он получит в качестве индексного параметра?
Именно для этого существуют slice-объекты."""
class Inspector:
def __getitem__(self, index):
print(index)
Inspector()[1]
Inspector()[1:2]
Inspector()[1:2:3]
Inspector()[:]
# Можно даже объединить синтаксисы кортежей и слайсов:
Inspector()[:, 0, :]
# slice ничего не делает, только хранит атрибуты start, stop и step.
s = slice(1, 2, 3)
print(f"type(s): {type(s)}")
print(f"s.start: {s.start}")
print(f"s.stop: {s.stop}")
print(f"s.step: {s.step}")
print(f"Inspector()[s]: {Inspector()[s]}")
| false |
b779876874fbc28d28cdf052cd11ff1e6f8c314c | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/e-g/float__test.py | 618 | 4.15625 | 4 | """class float([x])"""
# https://www.programiz.com/python-programming/methods/built-in/float
"""Return a floating point number constructed from a number or string x."""
print(f"float(): {float()}")
print(f"float(10.5): {float(10.5)}")
s = ' -2.5\n'
print(f"float(' -2.5'): {float(s)}")
print(f"float('NaN'): {float('NaN')}")
print(f"float('Infinity'): {float('Infinity')}")
print(f"float('-Infinity'): {float('-Infinity')}")
print(f"float('1e-003'): {float('1e-003')}")
print(f"float(1_000_000): {float(1_000_000)}")
try:
print(f"float('abc'): {float('abc')}")
except ValueError as e:
print(repr(e))
| false |
22806e83c0bf42cbab9b17e32580e80e3d0ad87a | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/dict__test.py | 673 | 4.1875 | 4 | """class dict"""
# https://www.programiz.com/python-programming/methods/built-in/dict
"""
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Create a new dictionary. The dict object is the dictionary class. See dict
and Mapping Types — dict for documentation about this class.
"""
def main():
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
print(f"a == b == c == d == e: {a == b == c == d == e}")
if __name__ == "__main__":
main()
| false |
a642a315921776c3d5920bd3e9f649a888462773 | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/list_test.py | 2,003 | 4.46875 | 4 | """class list([iterable])"""
# https://www.programiz.com/python-programming/methods/built-in/list
"""Rather than being a function, list is actually a mutable sequence type, as documented in Lists
and Sequence Types — list, tuple, range.
The list() constructor creates a list in Python.
Python list() constructor takes a single argument:
iterable (Optional) - an object that could be a sequence (string, tuples) or collection (set, dictionary)
or iterator object.
If no parameters are passed, it creates an empty list.
If iterable is passed as parameter, it creates a list of elements in the iterable."""
class PowTwo:
def __init__(self, max):
self.max = max
def __iter__(self):
self.num = 0
return self
def __next__(self):
if (self.num >= self.max):
raise StopIteration
result = 2 ** self.num
self.num += 1
return result
# Example 1: Create list from sequence: string, tuple and list
# empty list
print(f"list(): {list()}")
# vowel string
vowelString = 'aeiou'
print(f"vowelString: {vowelString}")
print(f"list(vowelString): {list(vowelString)}\n")
# vowel tuple
vowelTuple = ('a', 'e', 'i', 'o', 'u')
print(f"vowelTuple: {vowelTuple}")
print(f"list(vowelTuple): {list(vowelTuple)}\n")
# vowel list
vowelList = ['a', 'e', 'i', 'o', 'u']
print(f"vowelList: {vowelList}")
print(f"list(vowelList): {list(vowelList)}\n")
# Example 2: Create list from collection: set and dictionary
# vowel set
vowelSet = {'a', 'e', 'i', 'o', 'u'}
print(f"vowelSet: {vowelSet}")
print(f"list(vowelSet): {list(vowelSet)}\n")
# vowel dictionary
vowelDictionary = {'a': 1, 'e': 2, 'i': 3, 'o':4, 'u':5}
print(f"vowelDictionary: {vowelDictionary}")
# Note: Keys in the dictionary are used as elements of the returned list.
print(f"list(vowelDictionary): {list(vowelDictionary)}\n")
# Example 3: Create list from custom iterator object
powTwo = PowTwo(5)
powTwoIter = iter(powTwo)
print(f"list(powTwoIter): {list(powTwoIter)}")
| true |
3ec93bc3e2bbb8ec2f59a612ac2ad112aa1f4930 | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.8. Generator expressions/example.py | 230 | 4.25 | 4 | # A generator expression is a compact generator notation in parentheses.
# A generator expression yields a new generator object.
a = (x**2 for x in range(6))
print(f"a: {a}")
print(f"type(a): {type(a)}")
for i in a:
print(i)
| true |
c46fa1c8b803ed58abbfeb86d53d0b47f76c0c7d | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/h-i/hasattr_test.py | 597 | 4.21875 | 4 | """hasattr(object, name)"""
# https://www.programiz.com/python-programming/methods/built-in/hasattr
print(f"'int' has 'real': {hasattr(int, 'real')}\n")
class A:
def __init__(self, a, b):
self.a = a
self.b = b
obj_1 = A(1, 2)
obj_2 = 15
print(f"hasattr(obj_1, 'a'): {hasattr(obj_1, 'a')}")
print(f"hasattr(obj_1, 'b'): {hasattr(obj_1, 'b')}")
print(f"getattr(obj_2, 'a'): {hasattr(obj_2, 'a')}\n")
class Person:
age = 23
name = 'Adam'
person = Person()
print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
| false |
d866a29053b2e57c7dacf0d44ebaa0078138305a | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/a-b/all__test.py | 1,808 | 4.25 | 4 | """all(iterable)"""
# https://www.programiz.com/python-programming/methods/built-in/all
"""Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:"""
def all_func(iterable):
for element in iterable:
if not element:
return False
return True
def main():
list = [1, 2, 3, 4, 5]
empty_list = []
list_2 = [0, 1, 2, 3]
list_3 = [3 < 2, True]
print(f"all_func(list): {all_func(list)}")
print(f"all(list): {all(list)}\n")
print(f"all_func(empty_list): {all_func(empty_list)}")
print(f"all(empty_list): {all(empty_list)}\n")
# 0 == False
print(f"all_func(list_2): {all_func(list_2)}")
print(f"all(list_2): {all(list_2)}\n")
print(f"all_func(list_3): {all_func(list_3)}")
print(f"all(list_3): {all(list_3)}\n")
# How all() works for strings?
s = "This is good"
print(f"s: {s}")
print(f"all(s): {all(s)}\n")
# 0 is False
# '0' is True
s = '000'
print(f"s: {s}")
print(f"all(s): {all(s)}\n")
s = ''
print(f"s: {s}")
print(f"all(s): {all(s)}\n")
# How all() works with Python dictionaries?
"""In case of dictionaries, if all keys (not values) are true or the dictionary is empty,
all() returns True. Else, it returns false for all other cases.."""
d = {0: 'False', 1: 'False'}
print(f"d: {d}")
print(f"all(d): {all(d)}\n")
d = {1: 'True', 2: 'True'}
print(f"d: {d}")
print(f"all(d): {all(d)}\n")
d = {1: 'True', False: 0}
print(f"d: {d}")
print(f"all(d): {all(d)}\n")
d = {}
print(f"d: {d}")
print(f"all(d): {all(d)}\n")
# 0 is False
# '0' is True
d = {'0': 'True'}
print(f"d: {d}")
print(f"all(d): {all(d)}\n")
if __name__ == "__main__":
main()
| true |
5315e68a06067a3ab9a99178ab86ce613dc163fb | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/divmod__test.py | 816 | 4.21875 | 4 | """divmod(a, b)"""
# https://www.programiz.com/python-programming/methods/built-in/divmod
"""Take two (non complex) numbers as arguments and return a pair of numbers consisting
of their quotient and remainder when using integer division.
With mixed operand types, the rules for binary arithmetic operators apply.
For integers, the result is the same as (a // b, a % b).
For floating point numbers the result is (q, a % b),
where q is usually math.floor(a / b) but may be 1 less than that.
In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b,
and 0 <= abs(a % b) < abs(b)."""
def main():
print(f"divmod(17, 5): {divmod(17, 5)}")
print(f"divmod(17.3, 5): {divmod(17.3, 5)}")
print(f"divmod(7.5, 2.5): {divmod(7.5, 2.5)}")
if __name__ == "__main__":
main()
| true |
f312b493d986a88f5f05e4ef2c0db055aa8a8c8d | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/min_test.py | 2,432 | 4.25 | 4 | """min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])"""
# https://www.programiz.com/python-programming/methods/built-in/min
"""Return the smallest item in an iterable or the smallest of two or more arguments.
If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned.
If two or more positional arguments are provided, the smallest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function
like that used for list.sort(). The default argument specifies an object to return
if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
If multiple items are minimal, the function returns the first one encountered.
This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0]
and heapq.nsmallest(1, iterable, key=keyfunc).
"""
try:
print(f"min([]): {min([])}")
except ValueError as e:
print(repr(e))
print(f"min([], default='empty sequance'): {min([], default='empty sequance')}\n")
# Example 1: Find minimum among the given numbers
# using min(arg1, arg2, *args)
print(f'Minimum is: {min(1, 3, 2, 5, 4)}')
# using min(iterable)
num = [3, 2, 8, 5, 10, 6]
print(f'Minimum is: {min(num)}\n')
# Example 2: Find number whose sum of digits is smallest using key function
def sum_of_digits(num: int) -> int:
sum = 0
while num > 0:
temp = divmod(num, 10)
sum += temp[1]
num = temp[0]
return sum
# using min(arg1, arg2, *args, key)
print(f'Minimum is: {min(100, 321, 267, 59, 40, key=sum_of_digits)}')
# using min(iterable, key)
num = [15, 300, 2700, 821, 52, 10, 6]
print(f'Minimum is: {min(num, key=sum_of_digits)}\n')
"""Here, each element in the passed argument (list or argument) is passed to the same function sumDigit().
Based on the return value of the sumDigit(), i.e. sum of the digits, the smallest is returned."""
# Example 3: Find list with minimum length using key function
num = [15, 300, 2700, 821]
num1 = [12, 2]
num2 = [34, 567, 78]
# using min(iterable, *iterables, key)
print(f'Minimum is: {min(num, num1, num2, key=len)}')
"""In this program, each iterable num, num1 and num2 is passed to the built-in method len().
Based on the result, i.e. length of each list, the list with minimum length is returned.""" | true |
bf573e2b7eafe79adde1e52d40e21d5d393b043e | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.4. Displays for lists, sets and dictionaries/example.py | 218 | 4.125 | 4 | # The comprehension consists of a single expression followed by at least one for clause
# and zero or more for or if clauses.
a = [x**2 for x in range(11) if x % 2 == 0]
print(f"a: {a}")
print(f"type(a): {type(a)}")
| true |
e5de070bfe40a82008d8d9e6ed6986c618dc7043 | corridda/Studies | /Articles/Python/pythonetc/year_2018/october/python_etc_oct_23.py | 1,278 | 4.1875 | 4 | """https://t.me/pythonetc/230"""
"""You can modify the code behavior during unit tests not only by using mocks and other advanced techniques
but also with straightforward object modification:"""
import random
import unittest
from unittest import TestCase
# class Foo:
# def is_positive(self):
# return self.rand() > 0
#
# def rand(self):
# return random.randint(-2, 2)
#
#
# class FooTestCase(TestCase):
# def test_is_positive(self):
# foo = Foo()
# foo.rand = lambda: 1
# self.assertTrue(foo.is_positive())
#
#
# if __name__ == '__main__':
# unittest.main()
"""That's not gonna work if rand is property or any other descriptor.
In that case, you should modify the class, not the object.
However, modifying Foo might affect other tests, so the best way to deal with it is to create descendant."""
class Foo:
def is_positive(self):
return self.rand > 0
@property
def rand(self):
return random.randint(-2, 2)
class FooTestCase(TestCase):
def test_is_positive(self):
class TestFoo(Foo):
@property
def rand(self):
return 1
foo = TestFoo()
self.assertTrue(foo.is_positive())
if __name__ == '__main__':
unittest.main() | true |
beb99591beb990888eb58b3d949b3b44a21bcb2f | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/s-z/tuple_test.py | 724 | 4.40625 | 4 | """ tuple([iterable])
class type(object)
class type(name, bases, dict)"""
# https://www.programiz.com/python-programming/methods/built-in/tuple
"""Rather than being a function, tuple is actually an immutable sequence type, as documented
in Tuples and Sequence Types — list, tuple, range.
If an iterable is passed, corresponding tuple is created. If the iterable is omitted, empty tuple is created."""
# Example: How to creating tuples using tuple()?
t1 = tuple()
print('t1=', t1)
# creating a tuple from a list
t2 = tuple([1, 4, 6])
print('t2=', t2)
# creating a tuple from a string
t1 = tuple('Python')
print('t1=',t1)
# creating a tuple from a dictionary
t1 = tuple({1: 'one', 2: 'two'})
print('t1=',t1)
| true |
8341587ff2d172282ab6b00a82ea56380f062e4f | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 5. Data Structures/5.6. Looping Techniques/Looping Techniques.py | 1,713 | 4.15625 | 4 | import math
# looping through dictionaries -> items()
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k,v in knights.items():
print(k, ':', v)
# looping through a sequence ->
# the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questions = ['name', 'quest', 'favorite color']
answers = ['Lancelot', 'The Holy Grail', 'blue']
for q, a in zip(questions, answers):
print(f'What is your {q}? It is {a}.')
# To loop over a sequence in reverse, first specify the sequence in a forward direction
# and then call the reversed() function.
print('reversed list: ', end='')
for i in reversed([1, 2, 3]):
print(i, '', end='')
# the sorted() function which returns a new sorted list while leaving the source unaltered.
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
print('\nsorted list: ', end='')
for i in sorted(basket):
print(i, '', end='')
# It is sometimes tempting to change a list while you are looping over it;
# however, it is often simpler and safer to create a new list instead
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
print('\nsorted(filtered_data):', sorted(filtered_data))
print('filtered_data:', filtered_data)
# You can always simply delete the unnecessary data by 'del'
print(f'raw_data: {raw_data}')
del raw_data
try:
print(f'raw_data: {raw_data}')
except NameError as e:
print(e)
| true |
b099a789095e0219156d5cc73d690a738c42ed79 | corridda/Studies | /Articles/Python/pythonetc/year_2018/september/autovivification.py | 1,204 | 4.15625 | 4 | from collections import defaultdict
"""collections.defaultdict позволяет создать словарь, который возвращает значение по умолчанию,
если запрошенный ключ отсутствует (вместо выбрасывания KeyError).
Для создания defaultdictвам нужно предоставить не просто дефолтное значение, а фабрику таких значений.
Так вы можете создать словарь с виртуально бесконечным количеством вложенных словарей,
что позволит использовать конструкции вроде d[a][b][c]...[z].
Такое поведение называется «автовивификацией», этот термин пришёл из Perl."""
def infinite_dict():
return defaultdict(infinite_dict)
def main():
d = infinite_dict()
d[1][2][3][4] = 10
print(f"d: {d}")
d1 = dict(d[1][2][3][5])
print(f"d: {d}")
print(f"d1: {d1}")
d1['a'] = 'abc'
print(f"d1: {d1}")
print(f"d: {d}")
if __name__ == '__main__':
main() | false |
846c4d29e4c35d7bcfef67418034cd9647ef2e2c | swyatik/Python-core-07-Vovk | /Task 6/Home Work 2/6.2.7.py | 1,227 | 4.28125 | 4 | """Змінити послідовність стовпців матриці так,
щоб елементи її першого рядка були відсортовані за зростанням.
"""
from random import randint
# function of prints a matrix
def printMatrix(matrix):
for item in matrix:
for jtem in item:
print("%4d " % j, end="")
print()
column = 10
row = 5
matrix = [[] for i in range(row)]
for item in matrix:
for j in range(column):
item.append(randint(1, 20))
print('\nMatrix to sorting elements:')
print(f'{"_" * 5 * column}')
printMatrix(matrix)
# відсортований кортеж (елемент, його індекс)
sortRowIndex = sorted([(matrix[0][i], i) for i in range(column)])
# замінюємо елементи матриці на основі кортежу(sortRowIndex)
for i in range(row):
for j in range(int(column/2) if column % 2 == 0 else int(column/2) + 1):
temp = matrix[i][j]
matrix[i][j] = matrix[i][sortRowIndex[j][1]]
matrix[i][sortRowIndex[j][1]] = temp
print('\nMatrix after sorting elements:')
print(f'{"_" * 5 * column}')
printMatrix(matrix)
| false |
6b3f8316bc32ae76e7975953ae2839bc47a0d317 | swyatik/Python-core-07-Vovk | /Task 4/2_number_string.py | 293 | 4.15625 | 4 | number = 1234
strNumber = str(number)
product = int(strNumber[0]) * int(strNumber[1]) * int(strNumber[2]) * int(strNumber[3])
reversNumber = int(strNumber[::-1])
print('Product of number %d is %15d' % (number, product))
print('Inverse number to number %d is %8d' % (number, reversNumber)) | true |
56403e728de4d373716f254eeda78713f902edf3 | swyatik/Python-core-07-Vovk | /Task 8/8.2.5.py | 1,683 | 4.125 | 4 | """Задано два символьних рядка із малих і великих латинських літер та цифр.
Розробити програму, яка будує і друкує в алфавітному порядку множину літер,
які є в обох масивах, і множини літер окремо першого і другого масивів.
"""
def printSetSort(userSet):
usrSetSort = sorted(userSet)
for i in range(len(usrSetSort)):
if i == 0: print('{', end='')
if i < len(usrSetSort) - 1: print(f'{usrSetSort[i]}, ', end='')
else: print(f'{usrSetSort[i]}}}')
def main():
while True:
userString1 = input("String 1: ")
if userString1 == '':
print(' Error: the line must not be empty! try again. ')
else:
while True:
userString2 = input("String 2: ")
if userString2 == '':
print(' Error: the line must not be empty! try again. ')
else:
break
userString1 = set([leter for leter in userString1 if leter.isalpha()])
userString2 = set([leter for leter in userString2 if leter.isalpha()])
break
intersect = userString2.intersection(userString1)
print(f'{" "*5}The set of letters that are in both arrays:')
printSetSort(intersect)
print(f'{" "*5}The set of letters of the first arrays:')
printSetSort(userString1)
print(f'{" "*5}The set of letters of the second arrays:')
printSetSort(userString2)
if __name__ == "__main__":
main() | false |
fe02d0c885670f821eae1389a3b1f62f3921801a | swyatik/Python-core-07-Vovk | /Task 1/11_total_points.py | 1,650 | 4.15625 | 4 |
# Функція, що перевіряє чи рядок число int or float.
# Повертає tuple (true or false, тип даних в рядку)
def check_int_float(string):
if string == '':
return (True, 'int')
if string[0] == '-':
return (False, '')
if string.isdigit():
return (True, 'int')
else:
try:
float(string)
return (True, 'float')
except:
return (False, '')
# Запитуємо в користувача число
# та перевіряємо його на відповідність (введені дані мають бути числом >=0)
def ask_and_check():
number = None
while True:
string_input = input('Input number: ')
true, number_type = check_int_float(string_input)
if true:
if number_type == 'int':
if string_input == '':
number = 0
else:
number = int(string_input)
break
else:
print(' ERROR: Incorrect data entry. Must be an integer greater than zero or zero....')
else:
print(' ERROR: Incorrect data entry. Must be an integer greater than zero or zero....')
return number
print('How many wins?')
wins = ask_and_check()
print('How many draws?')
draws = ask_and_check()
print('How many losses?')
losses = ask_and_check()
number_of_points = wins*3 + draws
print('The number of points a football team: {}*3 + {}*1 + {}*0 = {}'.format(wins, draws, losses, number_of_points))
| false |
e4f868c12aec7eb4028611d46bf578e5e7619556 | bakunobu/exercise | /python_programming /Chapter_1.3/stats.py | 1,067 | 4.5625 | 5 | """ Обобщая упражнение о равномерных случайных числах,
составьте программу stats.ру, получающую в аргументе
командной строки целое число n и использующую функцию
random.random ( ) для вывода n равномерно случайных
чисел от О до 1, а затем выводящую их среднее,
минимальное и максимальное значения """
import random
def random_min_max_mean(n: int) -> None:
"""
Generates n random nums
Prints min, max and mean of a list
Args:
=====
n: int
number of numbers to be generated
Return:
=======
None: None
Prints results
"""
total = 0
min_x = 1
max_x = 0
for x in range(n):
x = random.random()
total += x
min_x = min(min_x, x)
max_x = max(max_x, x)
print('Mean: {:.3f}\nmin: {:.3f}\nmax: {:.3f}'.format(total / n, min_x, max_x)) | false |
03b684e80451215ec5a507b100db38088ec81c19 | bakunobu/exercise | /1400_basic_tasks/chap_3/3.45.py | 1,405 | 4.46875 | 4 | """
Меня вынесла формулировка.
На самом деле задание сводится к тому, что имеется последовательность
длиной 180 символов, в которой индекс есть у каждой пары чисел, например
номер элемента|->|индекс
1 -> 0
2 -> 0
3 -> 1
4 -> 1
5 -> 2
6 -> 2
и т.д.
"""
import doctest
# k = int(input())
# a
def find_index(k: int) -> int:
"""
>>> find_index(1)
0
>>> find_index(2)
0
>>> find_index(3)
1
>>> find_index(4)
1
>>> find_index(5)
2
>>> find_index(6)
2
>>> find_index(180)
89
"""
return((k - 1) // 2)
# b
def find_num(k:int) -> int:
"""
>>> find_num(1)
10
>>> find_num(2)
10
>>> find_num(3)
11
>>> find_num(4)
11
>>> find_num(5)
12
>>> find_num(6)
12
>>> find_num(180)
99
"""
return((k - 1) // 2 + 10)
# c_1
def find_even(k:int) -> int:
"""
>>> find_even(2)
0
>>> find_even(4)
1
>>> find_even(6)
2
>>> find_even(180)
89
"""
return((k - 2) // 2)
#c_2
def find_odd(k:int) -> int:
"""
>>> find_odd(1)
0
>>> find_odd(3)
1
>>> find_odd(5)
2
>>> find_odd(179)
89
"""
return((k-1) // 2)
if __name__ == "__main__":
doctest.testmod() | false |
01479006da67767f219e8d241f421c50d12df092 | bakunobu/exercise | /python_programming /Chapter_1.1_and_1.2/dragon_curve.py | 1,795 | 4.5 | 4 | """
Составьте программу, выводящую инструкции по рисованию кривых дракона в порядке от О до 5.
"""
def inverse_replacer(my_str:str, a:str, b:str) -> str:
"""
Replaces a wit b and b with a in my_str
Args:
=====
my_str: str
the sequence of symbols
a: str
if my_str[i] == a: my_str[i].replace(a, b)
b: str
if my_str[i] == b: my_str[i].replace(b, a)
Return:
=======
new_str: str
a result of replacement
"""
my_str = list(my_str)
for i in range(len(my_str)):
if my_str[i] == a:
my_str[i] = b
elif my_str[i] == b:
my_str[i] = a
return(''.join(my_str[::-1]))
def draw_curve(n: int) -> str:
# A simple helper for the dragon curve drawing
# Args:
# =====
# Return:
# =======
# hint: str
# an instruction
curves = []
for x in range(n):
if x == 0:
curve = 'F'
curves.append(curve)
elif x == 1:
curve = curves[x-1] + 'L' + 'F'
curves.append(curve)
elif x == 2:
curve = curves[x-1] + 'L' + inverse_replacer(curves[x-1], 'L', 'R')
curves.append(curve)
else:
if x % 2 == 0:
curve = curves[x-1] + 'L' + inverse_replacer(curves[x-1], 'R', 'L')
curves.append(curve)
else:
curve = curves[x-1] + 'L' + inverse_replacer(curves[x-1], 'L', 'R')
curves.append(curve)
return(curves)
curves = draw_curve(5)
for curve in curves:
print(curves.index(curve), curve, sep=': ')
| false |
e5ac3cabe485c1b6b7ced5c4bbb77415d9a67b7a | bakunobu/exercise | /python_programming /Chapter_1.1_and_1.2/box_muler.py | 1,211 | 4.28125 | 4 | """
Один способ создания случайного числа в соответствии с распределением Гаусса подразумевает использование формулы Бокса-Мюллера.
Составьте программу, выводящую значение согласно стандартному Гауссову распределению.
"""
import math
import random
import random
def box_muller_trans(v:float, u: float) -> float:
"""
A Box-Muller transformation for random number generation
Args:
=====
v: float
a random number
u: float
a random number
Return:
========
w: float
a result of Box-Muller transformation
"""
expr_1 = math.sin(2 * math.pi * v)
expr_2 = (-2 * math.log(u)) ** 0.5
return(expr_1 * expr_2)
def gaussian_random_digits() -> float:
"""
Generates a Normal Distributed random number using
Box-Muller transformation
Args:
None
Return:
w: float
a random number
"""
v = random.random()
u = random.random()
w = box_muller_trans(v, u)
return(w)
# test
gaussian_random_digits() | false |
a7681c1f46b63a681c59f7d052e11850177112a1 | bakunobu/exercise | /python_programming /Chapter_1.1_and_1.2/day_of_a_week.py | 1,311 | 4.34375 | 4 | """
Составьте программу, получающую дату и выводящую день недели, выпадающий на эту дату.
Программа должна получать три аргумента командной строки: m (месяц), d (день) и у (год).
Значение 1 переменной m соответствует январю, 2 -февралю и т.д.
В вы воде О соответствует воскресенью, 1 -понедельнику, 2 -вторнику и т.д.
"""
days_dict = {1: 'понедельник',
2: 'вторник',
3: 'среда',
4: 'четверг',
5: 'пятница',
6: 'суббота',
7: 'воскресенье'}
def check_day(m:int, d:int, y:int) -> int:
"""
Converts a date to a day of a week (Grigorian)
Args:
=====
m: int
month
d: int
day
y: int
year
Return:
=======
d_0: int
1 for Monday etc
"""
y_0 = y - (14 - m) / 12
x = y_0 + y_0 / 4 - y_0 / 100 + y_0 / 400
m_0 = m + 12 * ((14 - m) / 12) - 2
d_0 = (d + int(x) + (31 * m_0) / 12) % 7
return(int(d_0))
day = check_day(2, 15, 2000)
print(days_dict[day]) | false |
307fa5db59cf3b748e45f8cf80cb9ac4688e4133 | mervealgi/python-tutorials | /day2.py | 1,239 | 4.375 | 4 | #INTRODUCTION TO PYTHON DAY2
###LOGICAL OPERATIONS
a, b = True , False
print(type(a))
print(a or b) #will be True
print(a and b) #will be False
print(not a) #will be False
print (a != b) #will be True,bcs re not equal
print(a == b) #will be False, bcs re not equal
###SLICING
array1 = "PYTHON"
print(array1[0]) #P
print(array1[3]) #H
print(array1[-1]) #N
print(array1[-4]) #T
print(array1[:]) #will print all #PYTHON
print(array1[0:6]) #will print from 0 to 5th but not 6th
print(array1[1:3]) #YT
print(array1[0:]) #from 0 to all
print(array1[4:]) #ON
print(array1[:3]) #from begin to 3th but not 3th #PYT
print(array1[:6]) #PYTHON
print(array1[::-1]) #NOHTYP
city = "Porto"
print(city[0:5:1]) #start:end:step #Porto
print(city[1:5:2]) # o t
print(city[0:5:2]) #P r o
print("t" in city) #will be True
print("p" in city) #will be False bcs we have upper P
print("or" in city) #will be True
print("po" in city) #will be False bcs we have upper Po
ai = "artificial" + " " + "intelligence"
print(ai)
###LETTERS
word1 = "machine learning"
print(word1.capitalize()) #Machine learning
print(word1.upper()) #MACHINE LEARNING
print(word1.replace("machine","deep")) #deep learning
print(word1.strip()) #????????????
| false |
7b3534f75029b8193313f08afaec998f015a71ec | TNEWS01/projets | /Formation_Python/Listes.py | 2,064 | 4.28125 | 4 | # -------------------
# Les listes
# -------------------
# Créer une liste et lui assigner le nom de variable ma_liste
ma_liste = [1,2,3]
print(ma_liste)
# -------------------
ma_liste = ['Une chaine',23,100.232,'o']
print(ma_liste)
# -------------------
# Nombre d'éléments dans la liste
ma_liste = ['un','deux','trois',4,5]
print(ma_liste)
print(len(ma_liste))
# -------------------
# Afficher l'élément à l'index 0
print(ma_liste[0])
# -------------------
# Afficher l'élément à l'index 1 et les suivants
print(ma_liste[1:])
# -------------------
# Tout afficher jusqu'à l'index 3
print(ma_liste[:3])
# -------------------
newlist = ma_liste + ['nouvel élément']
print(newlist)
# -------------------
# Dupliquer les entrées de la liste
dblist = ma_liste * 2
print(dblist)
# -------------------
# Créer une nouvelle liste
list1 = [1,3,2,5,4]
# Append
list1.append('ajoute moi !')
print(list1)
# Assigner l'élément extrait, rappelez-vus que l'index de l'élément extrait par défaut est -1
objsupprim = list1.pop()
print(objsupprim)
print(list1)
# Inversion - Ceci est permanent
list1.reverse()
print(list1)
# Utiliser sort pour trier la liste (dans ce cas par ordre alphabétique, pour des nombres en ordre ascendant)
# Ceci est permanent
list1.sort()
print(list1)
# -------------------
# Listes imbriquées
# Création de trois listes
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Faire une liste de listes va créer une matrice
matrice = [lst_1,lst_2,lst_3]
print(matrice)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Afficher le premier élément de l'objet matrice
print(matrice[0])
# Afficher le premier élément du premier élément de l'objet matrice
print(matrice[0][0])
# -------------------
# Listes en compréhension
# Construire une liste en compréhension en déconstruisant une boucle for à l'intérieur de []
col_un = [ligne[0] for ligne in matrice]
print(col_un)
# [1, 4, 7]
# -------------------
# -------------------
# -------------------
# -------------------
# -------------------
# -------------------
| false |
b6e3692dd74e0baea8f85aec440d2c1831d360a4 | Bobby981229/Python-Learning | /Day 02 - Language Element/String_Type.py | 533 | 4.40625 | 4 | """
字符串运算符
判断是否为小写字母: 'a' <= char <= 'z'
判断是否为大写字母: 'A' <= char <= 'Z'
判断是否为字母: 'a' <= char <= 'z' or 'A' <= char <= 'Z'
判断是否为中文: '\u4e00' <= char <= '\u9fa5'
判断是否为数字: '0' <= char <= '9'
"""
# 统计字符串中小写字母的个数
str1 = "Hello, World !"
count = 0
# 遍历循环查找字符串中的小写字母
for char in str1:
if 'a' <= char <= 'z':
count += 1
print('字符串中小写字母的格式为: ', count)
| false |
0c3a027118d292cce1b372a295e646165e4a2459 | Bobby981229/Python-Learning | /Day 07 - Data Structures_List/Operator.py | 2,372 | 4.25 | 4 | """
运算符
"""
s1 = 'hello ' * 3
print(s1) # hello hello hello
s2 = 'world'
s1 += s2 # 拼接字符串 s1 = s1 + s2
print(s1) # hello hello hello world
print('ll' in s1) # True, ll在hello中
print('good' in s1) # False, good在hello中
str2 = 'abc123456'
# 从字符串中取出指定位置的字符(下标运算)
print(str2[2]) # c, 从零开始
# 字符串切片(从指定的开始索引到指定的结束索引)
print(str2[2:5]) # c12
print(str2[2:]) # c123456
print(str2[2::2]) # c246
print(str2[::2]) # ac246
print(str2[::-1]) # 654321cba
print(str2[-3:-1]) # 45
print('\n****************************************************\n')
str1 = 'hello, world!'
# 通过内置函数len计算字符串的长度
print(len(str1)) # 13
# 获得字符串首字母大写的拷贝
print(str1.capitalize()) # Hello, world!
# 获得字符串每个单词首字母大写的拷贝
print(str1.title()) # Hello, World!
# 获得字符串变大写后的拷贝
print(str1.upper()) # HELLO, WORLD!
# 从字符串中查找子串所在位置
print(str1.find('or')) # 8
print(str1.find('shit')) # -1
# 与find类似但找不到子串时会引发异常
# print(str1.index('or'))
# print(str1.index('shit'))
# 检查字符串是否以指定的字符串开头
print(str1.startswith('He')) # False
print(str1.startswith('hel')) # True
# 检查字符串是否以指定的字符串结尾
print(str1.endswith('!')) # True
print(str1.endswith('A')) # False
# 将字符串以指定的宽度居中并在两侧填充指定的字符
print(str1.center(50, '*'))
# 将字符串以指定的宽度靠右放置左侧填充指定的字符
print(str1.rjust(50, '*'))
str2 = 'abc123456'
# 检查字符串是否由数字构成
print(str2.isdigit()) # False
# 检查字符串是否以字母构成
print(str2.isalpha()) # False
# 检查字符串是否以数字和字母构成
print(str2.isalnum()) # True
str3 = ' jackfrued@126.com '
print(str3)
print(str3.strip()) # 获得字符串修剪左右两侧空格之后的拷贝
print('\n****************************************************\n')
a, b = 5, 10
print('%d * %d = %d' % (a, b, a * b)) # 用占位符来计算 a * b
a, b = 5, 10
print('{0} * {1} = {2}'.format(a, b, a * b)) # 用字符串提供的方法来完成字符串的格式
a, b = 5, 10
# print(a * b)
print(f'{a} * {b} = {a * b}') # 用语法糖来简化上面的代码
| false |
974397c2a0980ada4e92b3e13b38483b803dbee9 | Bobby981229/Python-Learning | /Day 11 - Introduction to OOP/Print_Obj.py | 767 | 4.21875 | 4 | """
打印对象
在类中放置__repr__魔术方法
该方法返回的字符串就是用print函数打印对象的时候会显示的内容
"""
class Student:
"""学生"""
def __init__(self, name, age):
"""初始化方法"""
self.name = name
self.age = age
def study(self, course_name):
"""学习"""
print(f'{self.name}正在学习{course_name}.')
def play(self):
"""玩耍"""
print(f'{self.name}正在玩游戏.')
def __repr__(self):
return f'{self.name}: {self.age}'
stu1 = Student('刘尚远', 21)
print(stu1) # 刘尚远: 21
students = [stu1, Student('Bobby', 20), Student('Jack', 19)] # 将参数存进列表中
print(students) # [刘尚远: 21, Bobby: 20, Jack: 19]
| false |
5c3e9eca8a134aa837b3a06ac22fb4acc2c8973f | Bobby981229/Python-Learning | /Day 10 - Data Structures_Dictionary/Dictionary_Calculation.py | 1,030 | 4.15625 | 4 | """
字典的运算
"""
person = {'name': '刘尚远', 'age': 21, 'weight': 68, 'home': '西影路46号'}
# 检查name和tel两个键在不在person字典中
print('name & tel in person:', 'name' in person, 'tel' in person) # True False
print()
# 通过age修将person字典中对应的值修改为22
if 'age' in person: # 如果age存在person中, 则修改age的值
person['age'] = 22
print('修改后的age:', person.get('age'))
for key, value in person.items():
print('修改后的person:', key, value)
print()
# 通过索引操作向person字典中存入新的键值对
person['tel'] = '13122334455'
person['signature'] = '你的男朋友是一个盖世垃圾,他会踏着五彩祥云去赢取你的闺蜜'
print('name & tel', 'name' in person, 'tel' in person) # True True
print()
# 检查person字典中键值对的数量print('键值对个数:', len(person)) # 6
# 对字典的键进行循环并通索引运算获取键对应的值
for key in person:
print(f'{key}: {person[key]}')
| false |
8aa5fbf8d58db8094e0dab793af65cab51b378e8 | aakinlalu/Mini-Python-Projects | /dow_csv/dow_csv_solution.py | 1,713 | 4.125 | 4 | """
Dow CSV
-------
The table in the file 'dow2008.csv' has records holding the
daily performance of the Dow Jones Industrial Average from the
beginning of 2008. The table has the following columns (separated by
commas).
DATE OPEN HIGH LOW CLOSE VOLUME ADJ_CLOSE
2008-01-02 13261.82 13338.23 12969.42 13043.96 3452650000 13043.96
2008-01-03 13044.12 13197.43 12968.44 13056.72 3429500000 13056.72
2008-01-04 13046.56 13049.65 12740.51 12800.18 4166000000 12800.18
2008-01-07 12801.15 12984.95 12640.44 12827.49 4221260000 12827.49
2008-01-08 12820.9 12998.11 12511.03 12589.07 4705390000 12589.07
2008-01-09 12590.21 12814.97 12431.53 12735.31 5351030000 12735.31
1. Read the data from the file, converting the fields to appropriate data
types.
2. Print out all the rows which have a volume greater than 5.5 billion.
Bonus
~~~~~
1. Print out the rows which have a difference between high and low of
greater than 4% and sort them in order of that spread.
"""
import csv
data = []
with open("dow2008.csv", "rb") as fp:
r = csv.reader(fp)
r.next()
for row in r:
data.append([
row[0],
float(row[1]),
float(row[2]),
float(row[3]),
float(row[4]),
int(row[5]),
float(row[6]),
])
# print out the rows > 5.5 billion
for row in data:
if row[5] > 5500000000:
print row
# print out the rows with 4% change
new_data = []
for row in data:
if (row[2]-row[3])/row[2] > 0.04:
new_data.append(row)
new_data.sort(key=lambda row: (row[2]-row[3])/row[2])
print
print
for row in new_data:
print row
| true |
99728de2ec99c6e60ff42a3a7811f5268028031d | jhoover4/algorithms | /cracking_the_coding/chapter_1-Arrays/7_rotate_matrix.py | 2,120 | 4.40625 | 4 | import unittest
from typing import List
def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Problem: Rotate an M x N matrix 90 degrees.
Answer:
Time complexity: O(MxN)
"""
if not matrix or not matrix[0]:
raise ValueError("Must supply valid M x N matrix.")
col_len = len(matrix)
row_len = len(matrix[0])
new_matrix = [[] for _ in range(row_len)]
for row in range(col_len):
for i, item in enumerate(matrix[row]):
new_matrix[i].insert(0, item)
return new_matrix
def rotate_matrix_in_place(matrix: List[List[int]]) -> List[List[int]]:
"""
Problem: Rotate an M x N matrix 90 degrees in place (no new data structure)
Answer:
Time complexity: O(MxN)
"""
# TODO: Finish this
if not matrix or not matrix[0]:
raise ValueError("Must supply valid M x N matrix.")
col_len = len(matrix)
row_len = len(matrix[0])
new_matrix = [[] for _ in range(row_len)]
for row in range(col_len):
for i, item in enumerate(matrix[row]):
new_matrix[i].insert(0, item)
return new_matrix
class Test(unittest.TestCase):
def test_has_rotated_square(self):
test_matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
rotated_matrix = [
[21, 16, 11, 6, 1],
[22, 17, 12, 7, 2],
[23, 18, 13, 8, 3],
[24, 19, 14, 9, 4],
[25, 20, 15, 10, 5]
]
self.assertEqual(rotate_matrix(test_matrix), rotated_matrix)
def test_has_rotated_rectangle(self):
test_matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
[17, 18, 19, 20]
]
rotated_matrix = [
[17, 13, 9, 5, 1],
[18, 14, 10, 6, 2],
[19, 15, 11, 7, 3],
[20, 16, 12, 8, 4],
]
self.assertEqual(rotated_matrix, rotate_matrix(test_matrix))
| true |
a0909167df71ff56d79b4f59e3fa22a9aea8d5b4 | jifrivly/Python | /calculator.py | 775 | 4.125 | 4 | num1 = float(input("Enter a number : "))
num2 = float(input("Enter a number : "))
def add(x, y):
return x+y
def sub(x, y):
return x-y
def mul(x, y):
return x*y
def div(x, y):
if y == 0:
return "0 division not accepted"
else:
return x/y
print("Choose an option : \n1 : Addition\n2 : Subtraction\n3 : Multiplication\n4 : Divition")
opr = raw_input(" Select your operation : ")
if opr == "1":
print "Sum of ", num1, " & ", num2, " = ", add(num1, num2)
elif opr == "2":
print "Differents of ", num1, " & ", num2, " = ", sub(num1, num2)
elif opr == "3":
print num1, " * ", num2, " = ", mul(num1, num2)
elif opr == "4":
print num1, " / ", num2, " = ", div(num1, num2)
else:
print "Please select a valid choise..."
| false |
31b15085fa9411fb18e684b4de113a5336d12fe9 | lofajob/PyLes | /lessons/Podoba/ls4/3or4.py | 343 | 4.3125 | 4 | i = 10
while i > 0:
print i
if i>5:
print "Bigger than 5!"
elif i%2 !=0:
print "this is ODD number"
print "and i <= 5"
else:
print "i <= 5"
print "this is EVEN nember, not ODD"
print "special number! :)"
i=i-1
print "we are after 'while' loop"
print "the end"
| false |
3708eda29bf47b6a2ab23eb56e8f95b9f88e4a5e | ChaitDevOps/Scripts | /PythonScripts/ad-lists.py | 1,018 | 4.5 | 4 | #!/usr/bin/python
# ad-lists.py
# Diving a little deeper into Lists.
#.append() Appends an element to the 'END' of the exisitng list.
from __future__ import print_function
l = [1,2,3]
l.append([4])
print(l)
#.extend() extends list by appending elements from the iterable
l = [4,5,6]
l.extend([7,8,9])
print(l)
# .index() - Returns the index of whatever element is placed as an argument.
# Note: If the the element is not in the list an error is returned
print(l.index(5))
# .insert() - insert takes in two arguments: insert(index,object) This method places the object at the index supplied
l.insert(7,10) # if No index is supplied, it errors out.
print("Here is insert:",l)
print("Length of List l:" ,
len(l))
# .pop() - Pops off the last element of the list.
ele = l.pop()
print(ele)
# .remove - The remove() method removes the first occurrence of a value
x=[8,9,10]
x.remove(9)
print(x)
# .reverse - reverse the list, replaces your list.
x.reverse()
print(x)
# .sort - will sort you List.
x.sort()
print(x)
| true |
85769cf60c277a432a21b44b95e3814d23511666 | ChaitDevOps/Scripts | /PythonScripts/lambda.py | 556 | 4.15625 | 4 | #!/usr/bin/python
# Lambda Expressions
# lambda.py
# Chaitanya Bingu
# Lamba expressions is basically a one line condensed version of a function.
# Writing a Square Function, we will break it down into a Lambda Expression.
def square(num):
result = num**2
print result
square(2)
def square(num):
print num**2
square(4)
def cube(num):
print num**3
cube(2)
# Converting this to Lambda
square2 = lambda num: num**2
print square2(10)
adder = lambda x,y: x+y
print adder(10,10)
len_check = lambda item: len(item)
print len_check("Arsenal Rules!")
| true |
9f44f5d1b42a232efb349cd9a484b1eb0d68372f | ChaitDevOps/Scripts | /PythonScripts/advanced_strings.py | 2,053 | 4.4375 | 4 | #!/usr/bin/python
# Chait
# Advanced Strings in Python.
# advanced_strings.py
from __future__ import print_function
# .capitalize()
# Converts First Letter of String to Upper Case
s = "hello world"
print(s.capitalize())
# .upper() and .lower()
print(s.upper())
print(s.lower())
# .count() and .find()
# .count() -- Will cound the number of times the argument was present in the variable/string
# .find() - Will find the position of the argument. will quit after first find.
print(s.count('o'))
print(s.find('o'))
# .center()
# The center() method allows you to place your string 'centered' between a provided string with a certain length
print(s.center(20,'z'))
# .expandtabs()
# expandtabs() will expand tab notations \t into spaces:
print("FirstName\tLastName".expandtabs())
# isalnum() will return True if all characters in S are alphanumeric
# isalpha() wil return True if all characters in S are alphabetic
# islower() will return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise
# isspace() will return True if all characters in S are whitespace.
# istitle() will return True if S is a title cased string and there is at least one character in S,
# i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.
# isupper() will return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.
# endswith() Another method is endswith() which is essentially the same as a boolean check on s[-1]
s="hello"
print(s.isalnum())
print(s.isalpha())
print(s.islower())
print(s.isupper())
print(s.istitle())
print(s.endswith('o'))
## Built in Reg-ex
# .split() Excludes the seperator.
s="chaitanya"
print(s.split(s[4])) # Splits at index position 4 of the variable s.
print(s.split('t')) # Splits at the letter 't' of the variable s.
# .partition() #Prints the tuple, meaning first half, seperator, second half.
print(s.partition(s[4]))
print(s.partition('t')) | true |
fde8e0f55ea61fbb7fecd6c0cd4cc61e0e18ea84 | ggerod/Code | /PY/recurseexponent.py | 294 | 4.1875 | 4 | #!/usr/bin/python3
def exponent(num,expo):
if (expo==0):
return(1)
if (expo%2 == 0):
y=exponent(num,expo/2)
return(y*y)
else:
y=exponent(num,expo-1)
return(num * y)
NUM=12
EXPO=25
answer=exponent(NUM,EXPO)
print(NUM,"**",EXPO,"=",answer)
| false |
bcc7ae5bdfe6d3a4f2b0433ca78c7c931a629519 | Pigiel/udemy-python-for-algorithms-data-structures-and-interviews | /Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions/Sentence-Reversal.py | 1,431 | 4.21875 | 4 | #!/usr/bin/env python3
""" Solution """
def rev_word1(s):
return ' '.join(s.split()[::-1])
""" Practise """
def rev_word2(s):
return ' '.join(reversed(s.split()))
def rev_word3(s):
"""
Manually doing the splits on the spaces.
"""
words = []
length = len(s)
spaces = [' ']
# Index Tracker
i = 0
# While index is less than length of string
while i < length:
# If element isn't a space
if s[i] not in spaces:
# The word starts at this index
word_start = i
while i < length and s[i] not in spaces:
# Get index where the word ends
i += 1
# Append that word to the list
words.append(s[word_start:i])
i += 1
# Join the reversed words
return ' '.join(reversed(words))
""" SOLUTION TESTING """
import unittest
class ReversalTest(unittest.TestCase):
def test(self, sol):
self.assertEqual(sol(' space before'),'before space')
self.assertEqual(sol('space after '),'after space')
self.assertEqual(sol(' Hello John how are you '),'you are how John Hello')
self.assertEqual(sol('1'),'1')
print('ALL TEST CASES PASSED')
print("rev_word('Hi John, are you ready to go?')")
print(rev_word1('Hi John, are you ready to go?'))
print("rev_word(' space before')")
print(rev_word1(' space before'))
t = ReversalTest()
print('## Testing Solution 1')
t.test(rev_word1)
print('## Testing Solution 2')
t.test(rev_word2)
print('## Testing Solution 3')
t.test(rev_word3) | true |
19a3cc106f1dadaf621ef20dd79d62861ab01ac7 | Pigiel/udemy-python-for-algorithms-data-structures-and-interviews | /Sorting and Searching/01_Binary_Search.py | 754 | 4.25 | 4 | #!/usr/bin/env python3
def binary_search(arr, element):
# First & last index value
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2 # // required for Python3 to get the floor
# Match found
if arr[mid] == element:
found = True
# set new midpoints up or down depending on comparison
else:
# Set down
if element < arr[mid]:
last = mid - 1
# Set up
else:
first = mid + 1
return found
print('\n### Binary Search algorythm')
# NOTE: List must be already sorted!
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('List:\t' + str(arr))
print('binary_search(arr, 4): ' + str(binary_search(arr, 4)))
print('binary_search(arr, 2.2): ' + str(binary_search(arr, 2.2))) | true |
78993e5a2442e7947655a263788fbf83a9c50c0d | kartik-mewara/pyhton-programs | /Python/25_sets_methods.py | 672 | 4.4375 | 4 | s={1,2,3,4,5,6}
print(s)
print(type(s))
s1={}
print(type(s1)) #this will result in type of dict so for making empty set we follow given method
s1=set()
print(type(s1))
s1.add(10)
s1.add(20)
print(s1)
s1.add((1,2,3))
# s1.add([1,2,3]) this will throws an erros as we can only add types which are hashable of unmutable as list is unhashable
# s1.add({1:2}) same goes for dictionary
# set is datatype which is collection of unrepeated values
print(s1)
s1.add(20)
s1.add(20)
print(s1)
print(len(s1)) #gives tghe lenght of the set
s1.remove(10)
print(s1)
a=s1.pop() #it removes the random item and it return it
print(s1)
print(a)
s1.clear() # it clears the full set
print(s1) | true |
51fe08037ca0d96b83b0dadded63411c1791aecd | kartik-mewara/pyhton-programs | /Python/05_typecasting.py | 593 | 4.125 | 4 | # a="1234"
# a+=5
# print(a) this will not work as a is a string but we expect ans 1239so for that we will type cast a which is string into int
a="1234"
print(type(a))
a=int(a)
a+=5
print(type(a))
print(a)
# now it will work fine
# similerly we can type cast string to int to string int to float float to in etc
b=2.3
c="2.3"
d=345
b=str(b)
# c=int(c) #here we will get error becoz in string it is float and we are trying to make it int for that we need to make it first float then we will make it int
c=float(c)
print(type(c))
c=int(c)
print(type(c))
d=float(d)
print(b)
print(c)
print(d)
| true |
332bb7e70a8168e8194a995f6eca4b1983997400 | kartik-mewara/pyhton-programs | /Python/13_string_template.py | 255 | 4.34375 | 4 | letter='''Dear <|name|>
you are selected on the date
Date: <|date|> '''
name=input("Enter name of person\n")
date=input("Enter date of joining\n")
# print(letter)
letter=letter.replace("<|name|>",name)
letter=letter.replace("<|date|>",date)
print(letter) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.