blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
924c7314c0d9ff3222f31e5d6bda299168e17e14 | sockster/Beginner-Projects | /verify_age.py | 996 | 4.5625 | 5 | #Project: Verifying a User's Age
# Sometimes a site might not be appropriate for people of a certain age.
# For times like these, we'll need a program that verifies the user's age, to ensure that they can view the site.
#GOAL
# Create a program that makes sure that the user is of an age of your choice (18 being the default).
#SUB GOALS
# Have the user input their birthday, and use that to determine if they are old enough
# If the user is not of an appropriate age, suggest a different website/websites that would be appropriate for them
import datetime
now = datetime.datetime.now()
t_month = now.month
t_day = now.day
t_year = now.year
months_d = {
"jan":"1",
"feb":"2",
"mar":"3"
}
print "Today is %d" % t_month
def old_enough():
bdate = raw_input("In order to verify your age, please enter your birthdate (mm/dd/yyyy)")
if len(bdate) == 10:
print (int(now.year)) - (int(bdate[6:]))
else:
print "Please use the \"mm/dd/yyyy\" format"
old_enough()
old_enough()
| true |
5c970c6d66076e51287cb4d45e1e0f9467743646 | lakshyatyagi24/daily-coding-problems | /python/68.py | 2,520 | 4.375 | 4 | # ----------------------------
# Author: Tuan Nguyen
# Date: 20190720
#!solutions/68.py
# ----------------------------
"""
On our special chessboard, two bishops attack each other if they share the same diagonal.
This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces.
You are given N bishops, represented as (row, column) tuples on a M by M chessboard.
Write a function to count the number of pairs of bishops that attack each other.
The ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1).
For example, given M = 5 and the list of bishops:
(0, 0)
(1, 2)
(2, 2)
(4, 0)
The board would look like this:
[b 0 0 0 0]
[0 0 b 0 0]
[0 0 b 0 0]
[0 0 0 0 0]
[b 0 0 0 0]
You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.
"""
def printChessboard(M, bishops):
# input: int M as size of M*M chessboard & list 'bishops' as positions of bishops on chessboard
# output: print M*M chessboard with 'b' as bishop, '.' as non-bishop
chessboard = [['.' for i in range(M)] for j in range(M)] # init chessboard w/ all non-bishops
for bishop in bishops:
y, x = bishop[0], bishop[1] # get coordinates of bishop
chessboard[y][x] = 'b' # mark cell with bishop
# print chessboard
for row in chessboard:
for e in row:
print(e, end='\t')
print("\n")
def pairsBishopsAttack(M, bishops):
# input: int M as size of M*M chessboard & list 'bishops' as positions of bishops on chessboard
# output: no. pairs of bishops which can attack each other
noAttackingBishopPairs = 0 # init output=0
for i in range(len(bishops) - 1): # check every pair of bishops
y1, x1 = bishops[i][0], bishops[i][1] # get coordinates of 1st bishop
for j in range(i+1, len(bishops)):
y2, x2 = bishops[j][0], bishops[j][1] # get coordinates of 2nd bishop
if abs(x1 - x2) == abs(y1 - y2): # check if 2 bishops are on the same diagonal
noAttackingBishopPairs += 1 # then increase no. pairs by 1
return noAttackingBishopPairs
def pairsBishopsAttack_test(M, bishops):
printChessboard(M, bishops)
print('No. pairs of attacking bishops:', pairsBishopsAttack(M, bishops))
if __name__ == "__main__":
pairsBishopsAttack_test(M=5, bishops=[(0, 0), (1, 2), (2, 2), (4, 0)]) # return 2
pairsBishopsAttack_test(M=5, bishops=[(0, 4), (1, 2), (2, 2), (4, 0)]) # return 3, b/c bishops can attack through pieces | true |
1ecdfcd7b2c68acdb18c86209b7cbdc3943b4ed1 | lakshyatyagi24/daily-coding-problems | /python/101.py | 1,549 | 4.28125 | 4 | # -----------------------------
# Author: Tuan Nguyen
# Date created: 20190822
#!solutions/101.py
# -----------------------------
"""
Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
Input: 4
Output: 2 + 2 = 4
If there are more than one solution possible, return the lexicographically smaller solution.
If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d,
then [a, b] < [c, d] if a < c OR a==c AND b < d.
"""
import random
def isPrime(N):
# input: int N >=2
# output: True if N is prime, False if N is composite
# method: Fermat's primality test
# running time: O(n^3)
if N == 1:
return False
if (N == 2) or (N == 3):
return True
a = random.randint(2, N-1)
b = a**(N-1) % N
if b != 1:
return False
return True
def goldbachConjecture(n):
# input: int n >= 2
# output: list [a,b]; a & b prime s.t a+b=n
goldbachPair = [] # output declared
a = 2 # int a initialized
while a <= n/2: # loop until a = n/2
if not isPrime(a):
a += 1
continue
b = n - a
if not isPrime(b):
a += 1
continue
goldbachPair = [a, b] # both a & b are primes and a+b=n
break
return goldbachPair
def goldbachConjecture_test(n):
print(n, '~>', goldbachConjecture(n))
if __name__ == "__main__":
for i in range(4, 10):
goldbachConjecture_test(i) | true |
f202d59d0eac80c922fa1f9540f336b4bce234f6 | lakshyatyagi24/daily-coding-problems | /python/25.py | 2,292 | 4.3125 | 4 | # ----------------------------------
# Author: Tuan Nguyen
# Date: 20190607
#!solutions/25.py
# ----------------------------------
"""
Implement regular expression matching with the following special characters:
'.' (period) which matches any single character <br/>
'*' (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular expression
and returns whether or not the string matches the regular expression.
For example, given the regular expression "ra." and the string "ray",
your function should return true.
The same regular expression on the string "raymond" should return false.
Given the regular expression ".*at" and the string "chat",
your function should return true.
The same regular expression on the string "chats" should return false.
"""
def regexMatch(string, pattern):
# input: 2 strings string & pattern (pattern w/ rules of "." and "*")
# output: True/False if string matches w/ pattern
pivot = 0
for i in range(len(pattern)):
if (i == len(pattern) - 1) and (0 < pivot < len(string) - 1) and (pattern[i] != "*"): # end of pattern but string still has character(s) which is not "*"
return False
if pattern[i] == ".": # '.' matches any single character
pivot += 1
continue
if pattern[i] == "*": # '*' matches >=0 preceding elements
# skip pivot to the remained character index in pattern
# e.g pattern "ab*cd" -> after "*" in pattern, there remains 2 characters left -> pivot in string = -2
# no. characters left in pattern = len(pattern) - 1 - i
pivot = i + 1 - len(pattern)
continue
if (string[pivot] != pattern[i]): # normal case: not match a character
return False
else:
pivot += 1
continue
return True
def regexMatch_test(string, pattern):
print(string, pattern, regexMatch(string, pattern))
if __name__ == "__main__":
regexMatch_test(string="ray", pattern="ra.") # return True
regexMatch_test(string="raymond", pattern="ra.") # return False
regexMatch_test(string="chat", pattern=".*at") # return True
regexMatch_test(string="chats", pattern=".*at") # return False | true |
d508e46e468a81d3260935e9e24f74a578f9bdfa | lakshyatyagi24/daily-coding-problems | /python/315.py | 1,672 | 4.625 | 5 | # --------------------------
# Author: Tuan Nguyen
# Date created: 20200323
#!315.py
# --------------------------
"""
In linear algebra, a Toeplitz matrix is one in which the elements on any given diagonal from top left to bottom right are identical.
Here is an example:
1 2 3 4 8
5 1 2 3 4
4 5 1 2 3
7 4 5 1 2
Write a program to determine whether a given input is a Toeplitz matrix.
"""
def is_toeplitz_matrix(matrix):
""" return True if input matrix is a Toeplitz matrix """
if not matrix: # empty matrix
return False
n = len(matrix) # no. rows
m = len(matrix[0]) # no. columns
if n == 1 or m == 1: # trivial case: input is an vector
return True
# else:
for i in range(n-1): # all rows
for j in range(m-1): # all columns
if matrix[i][j] != matrix[i+1][j+1]: # next diagonal element is not same
return False
return True # reach this -> all elements in each diagonal are equal
def test1():
matrix = [
[1, 2, 3, 4, 8],
[5, 1, 2, 3, 4],
[4, 5, 1, 2, 3],
[7, 4, 5, 1, 2]
]
assert is_toeplitz_matrix(matrix) == True
def test2():
matrix = [
[1, 2, 3],
[5, 1, 2],
[4, 5, 10]
]
assert is_toeplitz_matrix(matrix) == False
def test3():
matrix = [[1, 2, 3]]
assert is_toeplitz_matrix(matrix) == True
def test4():
matrix = [
[1],
[5],
[4]
]
assert is_toeplitz_matrix(matrix) == True
def test5():
matrix = []
assert is_toeplitz_matrix(matrix) == False
if __name__ == "__main__":
test1()
test2()
test3()
test4()
test5() | true |
9ba30eab317315f41f45912caafd544e6dd7278d | lakshyatyagi24/daily-coding-problems | /python/339.py | 1,219 | 4.3125 | 4 | # ----------------------------
# Author: Tuan Nguyen
# Date created: 20200416
#!339.py
# ----------------------------
"""
Given an array of numbers and a number k,
determine if there are three entries in the array which add up to the specified number k.
For example, given [20, 303, 3, 4, 25] and k = 49, return true as 20 + 4 + 25 = 49.
"""
def is_summable_three(arr, k):
""" return True if any 3 elements in unsorted array sum to k; otherwise, return False """
n = len(arr)
arr_sorted = sorted(arr)
for i in range(n-2):
if is_summable_two_sorted(arr_sorted[i+1:], k - arr_sorted[i]):
return True
return False
def is_summable_two_sorted(arr, k):
""" return True if any 2 element in the sorted input array sum to k; otherwise, return False"""
n = len(arr)
l, r = 0, n-1
while l < r:
if arr[l] + arr[r] == k:
return True
elif arr[l] + arr[r] < k:
l += 1
else:
r -= 1
return False
# ----- test -----
def test1():
assert is_summable_three([20, 303, 3, 4, 25], 49) == True
def test2():
assert is_summable_three([20, 303, 3, 4, 25], 0) == False
if __name__ == "__main__":
test1()
test2() | false |
edbf9c397b53faafdc398cf89f7ea6a29e8fe76b | lakshyatyagi24/daily-coding-problems | /python/156.py | 1,704 | 4.375 | 4 | # --------------------------
# Author: Tuan Nguyen
# Date created: 20191017
#!156.py
# --------------------------
"""
Given a positive integer n, find the smallest number of squared integers which sum to n.
For example, given n = 13, return 2 since 13 = 32 + 22 = 9 + 4.
Given n = 27, return 3 since 27 = 32 + 32 + 32 = 9 + 9 + 9.
"""
def smallest_number_squared_integers(n):
""" return smallest number of squared integers which sum to n
* ensure to have result because having 1 as smallest unit & n is positive int """
squared_integer_list = [i**2 for i in range(n//2, 0, -1) if i**2 <= n] # list of squared integers up to n descendingly
m = len(squared_integer_list)
smallest = None # output smallest number initialized
for j in range(m): # each iteration drops a number in squared_integer_list
number = possible_smallest(n, squared_integer_list, j) # find the number of integers which sum to n
if (smallest is None) or (number < smallest): # update smallest number if possible
smallest = number
return smallest
def possible_smallest(n, lst, marker):
""" recursively find the number of integers from lst which sum to n """
if n == 0:
return 0
else:
q = n // lst[marker] # quotient: number of integers possible by this int
r = n % lst[marker] # remainder
return q + possible_smallest(r, lst, marker+1)
def smallestNumberSquaredIntegers_test(n, desiredVal):
assert smallest_number_squared_integers(n) == desiredVal
if __name__ == "__main__":
smallestNumberSquaredIntegers_test(n=13, desiredVal=2)
smallestNumberSquaredIntegers_test(n=27, desiredVal=3) | true |
cb4d20cc215c5f6eddebbffee37af68af0019725 | aylat/Payroll_Program | /Payroll_Program.py | 1,332 | 4.25 | 4 | # aylat
# This program will calculate and display different aspects of a user's payroll
# Define constants
OT_MULTIPLIER = 1.5
DEDUCTION_PERCENTAGE = 0.2
# Prompt user to input information
EmployeeName = input('Enter the employees full name: ')
RegHours = float(input('Enter the number of regular hours worked by the employee: '))
OvertimeHours = float(input('Enter the number of overtime hours worked by the employee: '))
PayRate = float(input('Enter the hourly pay for the the employee: '))
# Perform payroll calculations based on user input
RegPay = RegHours * PayRate
OvertimePay = OvertimeHours * PayRate * OT_MULTIPLIER
GrossPay = RegPay + OvertimePay
Deductions = GrossPay * DEDUCTION_PERCENTAGE
NetPay = GrossPay - Deductions
# Display and format the output to the user
print('\n')
print('Employee Name:\t\t', EmployeeName)
print('Regular Hours Worked:\t', format(RegHours, '.2f'))
print('Overtime Hours Worked:\t', format(OvertimeHours, '.2f'))
print('Hourly Pay Rate:\t$', format(PayRate, ',.2f'), sep='')
print('\n')
print('Regular Pay:\t\t$', format(RegPay, ',.2f'), sep='')
print('Overtime Pay:\t\t$', format(OvertimePay, ',.2f'), sep='')
print('Gross Pay:\t\t$', format(GrossPay, ',.2f'), sep='')
print('Deductions:\t\t$', format(Deductions, ',.2f'), sep='')
print('Net Pay:\t\t$', format(NetPay, ',.2f'), sep='') | true |
2a07cf2b3d6805e5a7beb589f1c026e0c416132b | soumasish/leetcodely | /python/next_permutation.py | 1,178 | 4.1875 | 4 | """Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return nums
l = len(nums)
i, j = l - 1, l - 1
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
while j > i and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = sorted(nums[i + 1:])
if __name__ == '__main__':
solution = Solution()
print(solution.nextPermutation([1, 2, 3]))
print(solution.nextPermutation([3, 2, 1]))
print(solution.nextPermutation([1, 1, 5]))
| true |
e039318552b51d17632e3b3e7d24013f0c453d86 | soumasish/leetcodely | /python/zig_zag_iterator.py | 951 | 4.28125 | 4 | """ Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1, 3, 2, 4, 5, 6]. """
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.queue = [item for item in (v1, v2) if item]
def next(self):
"""
:rtype: int
"""
v = self.queue.pop(0)
ans = v.pop(0)
if v:
self.queue.append(v)
return ans
def hasNext(self):
"""
:rtype: bool
"""
return len(self.queue) > 0
if __name__ == '__main__':
zigzag = ZigzagIterator([1, 2], [3, 4, 5, 6])
while zigzag.hasNext():
print(zigzag.next())
| true |
62c65736dd0c1d942d1404e20e1179b7d3067031 | soumasish/leetcodely | /python/enocde_and_decode_tiny_url.py | 1,322 | 4.25 | 4 | """TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode
algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be
decoded to the original URL."""
import random
import string
class Codec:
def __init__(self):
self.map = {}
self.host = 'https://tinyurl.com/'
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
code = self.id_generator(5)
self.map[self.host + code] = longUrl
return self.host + code
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.map[shortUrl]
def id_generator(self, size):
return ''.join([random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(size)])
# Your Codec object will be instantiated and called as such:
codec = Codec()
print(codec.decode(codec.encode('https://leetcode.com/problems/design-tinyurl')))
| true |
c8982c387b8281f12b3cf9fb42cfdacdab323236 | tommy115/begining-of-python | /chap06/training.py | 2,339 | 4.125 | 4 | print("###############6-1###############")
class Thing():
pass
example = Thing()
example2 = Thing
print(Thing)
print(example)
print(example2)
print("###############6-2###############")
class Thing2():
def __init__(self, name):
self.letters = name
class Thing3():
def set(self,name):
self.letters = name
exam = Thing2('abc')
print(exam.letters)
exam2 = Thing3()
exam2.set('hello')
print(exam2.letters)
print("###############6-4###############")
class Element():
def __init__(self, name, symbol, number):
self.__name = name
self.__symbol = symbol
self.__number = number
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def number(self):
return self.__number
def dump(self):
print(self.__name)
print(self.__symbol)
print(self.__number)
def __str__(self):
return self.__name + ' ' + self.__symbol + ' ' + str(self.__number)
e = Element('Hydrogen', 'H', 1)
print("###############6-5###############")
dict = {
'name' : 'Hydrogen',
'symbol' : 'H',
'number' : 1 }
hydrogen = Element(dict['name'],dict['symbol'],dict['number'])
print(hydrogen.name)
print("###############6-6###############")
hydrogen.dump()
print("###############6-7###############")
print(hydrogen)
print("###############6-8###############")
print(hydrogen.name)
print(hydrogen.symbol)
print(hydrogen.number)
print("###############6-9###############")
class Bear():
def eats(self):
return 'barries'
class Rabbit():
def eats(self):
return 'clover'
class Octothorpe():
def eats(self):
return 'campers'
b = Bear()
r = Rabbit()
o = Octothorpe()
print(b.eats())
print(r.eats())
print(o.eats())
print("###############6-10###############")
class Laser():
def does(self):
return 'disintegrate'
class Claw():
def does(self):
return 'crush'
class SmartPhone():
def does(self):
return 'ring'
class Robot():
def __init__(self):
self.laser = Laser()
self.claw = Claw()
self.smartPhone = SmartPhone()
def does(self):
return self.laser.does() + " " + self.claw.does() + " " + self.smartPhone.does()
r = Robot()
print(r.does())
| false |
8919e442ac64553119dafd0faad13be49acc4842 | mich-chen/add-to-zero-code-challenge | /addtozero.py | 1,154 | 4.28125 | 4 | """Given list of ints, return True if any two nums in list sum to 0.
>>> add_to_zero([])
False
>>> add_to_zero([1])
False
>>> add_to_zero([1, 2, 3])
False
>>> add_to_zero([1, 2, 3, -2])
True
Given the wording of our problem, a zero in the list will always
make this true, since "any two numbers" could include that same
zero for both numbers, and they sum to zero:
>>> add_to_zero([0, 1, 2])
True
"""
# maybe can use itertools.combinations_with_replacement(iterable, r)
# finding combinations with every possible permutation, including adding to itself
def add_to_zero(nums):
"""Given list of ints, return True if any two nums sum to 0."""
# set_nums = set(nums)
# if 0 in set_nums:
# return True
# do not need the above block of code because python considers -0 == 0)
set_nums = set(nums)
for num in set_nums:
if -num in set_nums:
return True
else:
return False
# for num in set_nums
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. NOTHING ESCAPES YOU!\n")
| true |
1ae250aa17872788950ddc6c8de235d6f5b2dacc | rp927/06-Intro-to-Algorithms | /Slingly_Linked_List_Practice/prepend.py | 807 | 4.21875 | 4 | class Node:
def __init__(self,data,next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
#Simple print statement
def print_list(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
#Simple prepend function
def prepend(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
if __name__ == "__main__":
#Initialize the linked list
llist = LinkedList()
#Create nodes
llist.head = Node(1)
second = Node(2)
third = Node(3)
#Establish links
llist.head.next = second
second.next = third
llist.prepend(0)
#print the list
llist.print_list() | true |
634ac22ccbb9b4275f70ec848a2bba406f18da29 | rp927/06-Intro-to-Algorithms | /Practice/binarySearchChallenge.py | 2,445 | 4.1875 | 4 | '''
2(challenge). The method that’s usually used to look up an entry in a phone book is not
exactly the same as a binary search because, when using a phone book, you don’t always go
to the midpoint of the sublist being searched. Instead, you estimate the position of the
target based on the alphabetical position of the first letter of the person’s last name.
For example, when you are looking up a number for “Smith,” you look toward the middle of
the second half of the phone book first, instead of in the middle of the entire book.
Suggest a modification of the binary search algorithm that emulates this strategy for a
list of names. Is its computational complexity any better than that of the standard
binary search?
'''
import string
def dict_generator():
alpha = {}
num = 0
for i in list(string.ascii_lowercase):
alpha[i] = num
num += 1
return alpha
def phone_book_lookup(dict,phone_book):
name = input("Enter the name of the user you would like to search: ")
first_letter = dict[name[0].lower()]
if first_letter < 9:
for key in phone_book.keys():
key_num = dict[key[0]]
if first_letter <= key_num:
for key in phone_book.keys():
if name.lower() == key.lower():
return f'{name}:{phone_book[key]}'
elif first_letter > 18 and first_letter < 26:
for key in list(reversed(phone_book.keys())):
key_num = dict[key[0]]
if first_letter <= key_num:
for key in phone_book.keys():
if name.lower() == key.lower():
return f'{name}:{phone_book[key]}'
else:
phone_keys = list(phone_book.keys())
print(phone_keys)
right = len(list(phone_keys))
left = 0
while left <= right:
midpoint = (left + right) // 2
if name == phone_keys[midpoint]:
return f'{name}:{phone_book[name.lower()]}'
elif first_letter < dict[phone_keys[midpoint][0]]:
right = midpoint - 1
else:
left = midpoint + 1
phone_book = {
'aaron':'555-0001',
'carson':'555-0002',
'frank':'555-0003',
'juliet':'555-0004',
'pratt':'555-0005',
'perry':'555-0010',
'reuben':'555-0006',
'tim':'555-0007',
'victor':'555-0008'
}
print(phone_book_lookup(dict_generator(),phone_book)) | true |
edffe9873e71511f1dd1d5c61913d8650d13dc1a | rp927/06-Intro-to-Algorithms | /Practice/count_2.py | 522 | 4.40625 | 4 | '''
2. Run the program you created in Exercise 1 using problem sizes of
1000, 2000, 4000, 10,000, and 100,000. As the problem size doubles
or increases by a factor of 10, what happens to the number of iterations?
'''
def main():
problemSize = [1000, 2000, 4000, 10000, 100000]
count_it(problemSize)
def count_it(problemSize):
for i in problemSize:
count = 0
print(f'{i}:')
while i > 0:
i = i // 2
count += 1
print(f'{count} iterations')
main() | true |
8e29314aaf56f3a1a25e48382da6122482ad8556 | rp927/06-Intro-to-Algorithms | /Recursion/Recursion_3.py | 962 | 4.46875 | 4 | '''
3. Recursive Lines
Write a recursive function that accepts an integer argument, n. The function should display
n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line
showing 2 asterisks, up to the nth line which shows n asterisks.
'''
'''Main function'''
def main():
num = input("Enter a number :")
num = num_validation(num)
asterick(num)
'''Where the magic happens'''
def asterick(num,ast=['*']):
if num == 0:
return num
else:
print(''.join(ast))
ast.append('*')
asterick(num-1,ast)
'''Simple input validati0n'''
def input_validation(num):
while str.isnumeric(num) == False:
num = input("INVALID INPUT! Enter a number: ")
return int(num)
def num_validation(num):
num = input_validation(num)
while num >= 996:
num = input("INVALID INPUT! Must be less than 996: ")
num = input_validation(num)
return num
main() | true |
3f3ae134036c0a5c281c038039bbcb10e4e51f1e | thakurmhn/Learn-python-scripting | /operators.py | 1,674 | 4.1875 | 4 | #!/usr/bin/env python3.7
'''
Arithematic Operators = input values and output will be values
Addition +
Subtraction -
Multiplication *
Division /
Modulo %
Floor Diviosn //
Exponential **
Assignment Operators = input values and output will be values
Comparison Operators = input values and output will be True or False
Identity Operators = input values and output will be True or False
Membership Operators = input values and output will be True or False
Logical Operators = input True or False output will be True or False
Bitwise Operator = Input values, perform operation on its binary and outputs values
'''
### Identity operation eg
## Identity operator compare type() of object whether its int, str, etc
## they are "is" and "is not"
'''
a=4
b=7
x="hi"
print(type(a) is type(b))
print(type(a) is type(x))
print(type(a) is not type(x))
'''
'''
## Membership operators
## "in" and "not in" operators
valid_java=['1.6','1.7','1.8','1.9']
inst_ver='1.5'
if inst_ver in valid_java:
print("host is deployed with valid java version")
else:
print("host is deployed with invalid java version")
'''
## Logical operators
## "and", "or", "not" operators
# and - if any one of the condition is false, result is false
# or - if any one of the condition is true, result is true
# not - inverse true to false, False to true
print(1<2 and 2<3 and 3<4)
print(1<2 and 2<3 and 4<3)
print(not 1<2)
print(not 4<3)
## Multiple and conditions
print(1<2 and 2<3 and 3<4 and 4<5 and 5<6)
## use all()
## all() == and operator
print(all([1<2,2<3,3<4,4<5,5<6]))
## Multiple 'or' conditions
## use any()
## any() == or
print(any([2<3,3<4,10<7]))
| true |
514d5f639b1ae0ecef28c8c42652c7a3aec4aa10 | thakurmhn/Learn-python-scripting | /regex_adv_pattern_rules.py | 2,222 | 4.25 | 4 | #!/usr/bin/env python3.7
'''
^ - start of string or start of line in case of multiple line string
'''
import re
text="it is python and it is easy to learn"
pat='^i[ts]'
print(re.findall(pat,text))
'''
$ - Matches end of the string
'''
text="it is python and it is easy to learn"
pat='learn$'
print(re.findall(pat,text))
'''
\b - matches empty string at the begining of the given string
'''
text="it is python andlearn it is learn easy to learn"
pat='\\blearn' # two \\ as \b is backslash charater and need to escape
# OR write 'r' - raw sting
pat=r'\blearn'
print(re.findall(pat,text)) # not matching first occurrence of learn as there is no space before it
text="it is python andlearn it isilearn easy to learn"
pat=r'\blearn\b' # matching only learn word
print(re.findall(pat,text))
'''
\B - Empty string NOT at begining or end of the string, inverse to \b
'''
text="it is python andlearnit is learn easy to learn"
pat=r'\Blearn\B' # finds 'learn' where no spaces at the start or at end of the word 'learn' i.e (andlearnit)
print(re.findall(pat,text))
'''
{} - {2}, - Exactly 2 times
{2,4} - matchs 2, 3 or 4 times
{2,} - 2 or more times
'''
text="pythonn aaaa "
pat=r'python{2}'
pat2=r'\ba{4}\b' # matches 'a' four times; \b is word boundry
text1="pythonn aaaa pythonnnn"
pat3=r'python{2,4}' # matches n' two, three or fourtimes
print(re.findall(pat,text))
print(re.findall(pat2,text))
print(re.findall(pat3,text1))
mytext="xaz xaaaaz sdfaaaaaaddda sdfdfaaaalll xaaazzz xaaaaaaaaz"
mypat=r'xa{2,}z'
print(re.findall(mypat,mytext))
'''
+ - matches character one or more times; same as {1,}
'''
mytext="xaz xaaaaz sdfaaaaaaddda sdfdfaaaalll xaaazzz xaaaaaaaaz"
mypat=r'xa+z'
print(re.findall(mypat,mytext))
'''
* - matches character 0 or more times
'''
mytxt="xaz xaaaaz xaaazzz xz xaaaaaaaaz"
mypat1=r'xa*z' # will match 'xz' also
print(re.findall(mypat1,mytxt))
'''
? - matches character having occurrence one or none times
'''
mytxt1="xaz xaaaaz xaaazzz xz xaaaaaaaaz"
mypat2=r'xa?z' # will match 'xaz' and xz
print(re.findall(mypat2,mytxt1))
'''
[] - [23] matches 2 or 3
'''
mytxt="I have python, python2 and python3"
mypat=r'\bpython[23]?\b'
print(re.findall(mypat,mytxt))
| true |
44886c78644f16cb807b9deffe1be14746d7dc5a | thakurmhn/Learn-python-scripting | /regex_basic_operations.py | 1,908 | 4.5 | 4 | #!/usr/bin/env python3.7
'''
#re Operations
re.search(pattern, text)
re.match(pattern, text)
re.finditer(pattern, text)
re.findall(pattern, text)
'''
import re
#print(re.findall('is','This is python and it is easy to learn'))
text='This is python and it is easy to learn'
my_pat='is'
print(re.findall(my_pat,text))
pat1='i[st]'
print(re.findall(pat1,text))
# Rules to create pattern
'''
a, x, 9 - Ordinary characters that match themselves
'''
text='x is greater than 9x'
#patt='a'
patt='x'
print(re.findall(patt,text))
'''
[abc] - match a or b or c
[a-z] - match all a to z characters
'''
text='a very big cat'
#patt='[abc]'
patt='[a-t]'
print(re.findall(patt,text))
'''
[a-zA-Z0-9] - Matches (a-z) or (A-Z) or (0-9)
'''
text="Learning Python3.7"
patt='[a-eL-Q2-7]'
print(re.findall(patt,text))
'''
\w Matches a-z, 0-9 and _
'''
#Match single character using \w
text="Learning @Python3.7 _ some __text-more text"
patt="\w"
print(re.findall(patt,text))
#Match two characters string using \w
patt1="\w\w"
print(re.findall(patt1,text))
#Match 3 character string using \w\w\w
patt2="\w\w\w"
print(re.findall(patt2,text))
'''
\W - Matches all characters which are not part of \w
'''
patt3="\W"
print(re.findall(patt3,text))
'''
\d
'''
text1="python2 and python3 and python37"
patt4="\d"
patt5="\w\w\w\d"
patt6="python\d\d"
print(re.findall(patt4,text1))
print(re.findall(patt5,text1))
print(re.findall(patt6,text1))
'''
. (dot) - Matches every single charater except newline \n
'''
text2="python2 and python3 and python3.7"
mypat="."
mypat1="..." # matches 3 characters in sequence
mypat2="\." # matches only dot
print(re.findall(mypat,text2))
print(re.findall(mypat1,text2))
print(re.findall(mypat2,text2))
## Extacting IP from string
iptext="extracting IP from this string 100.200.102.200 43434009992353"
ippat1="\d\d\d\.\d\d\d\.\d\d\d\.\d\d\d"
print(re.findall(ippat1,iptext))
| false |
c1fa41c9586672719dfad314ac2356ade6166679 | thakurmhn/Learn-python-scripting | /working_with_string.py | 1,001 | 4.125 | 4 | #!/usr/bin/env python3.7
'''
my_name=""
my_lastname=" "
print(f'{bool(my_name)}') ## bool of any empty variable is always False
print(f'{bool(my_lastname)}') ## bool of non empty variable is always True
'''
'''
# Access string based on Index values
fav_scripting="python scripting"
print(f"{fav_scripting[-1]}")
print(fav_scripting[0:5])
print(fav_scripting[-16:-6])
# Change or delete string
# You can not change/delete part of string but can replace entire string
fav_scripting="python"
print(fav_scripting)
del fav_scripting
print(fav_scripting)
'''
'''
# Find lenghth of string
fav_scripting="python scripting"
print(f"length of string is {len(fav_scripting)}")
#Concat
S1="python"
S2="Scripting"
print(S1+" "+S2+" "+"Tutorial")
print(f"{S1.lower()}")
print(f"{S2.upper()}")
'''
'''
# Print list of String Operations
S1="somestring"
print(dir(S1))
'''
S2="Mohan Thakur"
print(S2.swapcase())
S1="MOHAN THAKUR"
print(S1.title())
S3="PythoN ScriPTing tuTOrial"
print(S3.casefold())
| false |
21804fc05dbcb42afaa43a4beec5f7172e5b4638 | EmerTech20/Emerlanza | /Operadores relacionales.py | 965 | 4.21875 | 4 |
# Operadores de comparación como < _ > _ <= (menor o igual) >= (mayor o igual) == (igual) ¡= (diferente)
#son relacionales que sirven para establecer comparación entre diversos valores.
# Más información en =>>https://entrenamiento-python-basico.readthedocs.io/es/latest/leccion3/operadores_relacionales.html
saludo1 = "¡Hola!"
saludo2 = "¿Qué tal?"
print ( "\n", saludo1, "\n")
print(" ¿Cómo te llamas?")
nombre = input()
print( "\n", saludo2, nombre,"\n")
print("¿Cuantos años tienes?" )
edad = int(input())
print("\n")
if edad < 18:
print( "Estás en la tierna edad", nombre)
elif edad >= 18 and edad<=30:# and es un operador lógico que aqui establece una relación entre los valores
print("Eres una persona hecha y derecha", nombre)
if edad >= 45 and edad < 65:
print("Eres Senior, estás en los años de oro de la madurez", nombre)
else:
print("Estás en la flor dela juventud, tienes mucho por disfrutar", nombre)
| false |
bc65431d5da7979cb8386ff5d579458c33d68db7 | Kalliojumala/School-Work | /Week 8/Week8_hard/hard8.1.py | 1,308 | 4.125 | 4 | #poem scrambler, short words(<=3 letters) are lowercased and
#long words(>=7 letters) are uppercased
#print words in random order after recasing them
from random import shuffle
def word_scramble(poem):
#create 3 lists from user input
user_list = sorted(poem.split(' '), key= lambda x: len(x))
short_words = []
long_words = []
for word in user_list.copy():
#append short and long words to separate lists
if len(word) <= 3:
short_words.append(word.lower())
user_list.remove(word)
if len(word) >= 7:
long_words.append(word.upper())
user_list.remove(word)
#return the three lists combined
return [item for item in (user_list + short_words + long_words)]
while True:
#take user input
poem = input("Syötä vähintään viisi sanaa sisältävä runo tai sanonta:")
#check it is atleast 5 words long, re-ask input if its invalid
if len(poem.split(' ')) < 5:
print("\nSyötä vähintään viisi sanaa!\n")
continue
#apply the function on the input and shuffle the returned list
ready_list = word_scramble(poem)
shuffle(ready_list)
#print the list as a string and exit
print(" ".join(ready_list))
break
print("Kiitos ohjelman käytöstä!\n")
| true |
16310ed7453cca64889d34e1c105d71db74b0ad8 | snejDev/ElementaryCodes | /Python/Excepthin_handling/InvalidPasswordException.py | 743 | 4.25 | 4 | '''a = input("Enter a password: ").strip()
try:
assert len(a)>8,"InvalidPasswordException"
except AssertionError:
print("Create a password with minimum of 8 characters")
else:
print("Password: "+a)
'''
class InvalidePasswordException(Exception):
def __init__(self, msg):
self.msg = msg
def password(pwd):
if len(pwd) >= 8:
print("Strong password.")
else:
raise InvalidePasswordException("Password should be at least 8 character long.")
try:
print("Enter password of minimum length 8 characters.")
pwd1 = input("Enter password: ")
password(pwd1)
except InvalidePasswordException:
print("Password should be at least 8 character long.")
| true |
249b5b8fccb7d46038b555d0cbfbb0478474c9bf | MansiiMishra/Task-Reminder-Project | /Main.Py | 936 | 4.21875 | 4 | import time
text = str(input("What's the task that i need to remind you about?\n"))
local_time = float(input("In how many minutes should i remind you about the task?\n")) * 60
time.sleep(local_time)
print("Yooo, this is your reminder to:",text)
print("For more options press the mentioned keys")
option = int(input(print("Enter 1 to Complete task \n Enter 2 to Snooze the task \n Enter 3 to insert new task\n")))
if option == 1:
print("Task Marked as complete")
elif option == 2:
new_time = float(input("For how many minutes would you like to snooze the task?\n"))*60
time.sleep(new_time)
print("Yooo, this is your reminder to:",text)
elif option == 3:
text = str(input("What's the task that i need to remind you about?"))
local_time = float(input("In how many minutes should i remind you about the task?")) * 60
time.sleep(local_time)
print("Yooo, this is your reminder to:",text)
| true |
001b883bb823fe6926a1ae3f086fa8ea16146dee | rounakskm/Machine-Learning | /2.Regression/Section 4 - Simple Linear Regression/Simple_linear_regression_self.py | 1,610 | 4.28125 | 4 | #Simple linear regression
#Importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#Splitting the dataset into train and test
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state = 0)
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""
#Fitting the regression to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)
#Predicting the test set results
y_pred = regressor.predict(X_test)
#Vizualizing the training results
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue') # y-cordinate is the predictions made on the training data
plt.title('Salary Vs Experience (Training Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() #Plots the graph
#Vizualizing the test results
plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color='blue') # this is the model line which was trained using training data
plt.title('Salary Vs Experience (Test Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() #Plots the graph
| true |
9073fd4861e291d24742d6c7615f4e108bd56dc8 | JamesK1ng/JamesK1ng.github.io | /CS Assignments/Assignment24.py | 263 | 4.21875 | 4 | #Assignment24
usernouns = (input("Enter nouns:"))
words = usernouns.split(" ")
wordnum = words.count("z ")
plurals = usernouns.count("s ")
frac = wordnum / plurals
print("Number of Words: ", wordnum)
print("Fraction of your list that is plural is: " , frac)
| true |
cc75b6b38d9365106e730469b9b6ec8814445013 | 790212828/Homework | /Cat.py | 919 | 4.15625 | 4 | """
比如创建一个类(Animal)【动物类】,类里有属性(名称,颜色,年龄,性别),类方法(会叫,会跑)
创建子类【猫】,继承【动物类】,
重写父类的__init__方法,继承父类的属性,
添加一个新的属性,毛发 = 短毛,
添加一个新的方法, 会捉老鼠,
重写父类的【会叫】的方法,改成【喵喵叫】
"""
from lagou.python1.test14.homework.Animal import Animal
class Cat(Animal):
def __init__(self):
super().__init__()
self.name="Cat"
self.hair="短毛"
def catch_mouse(self):
print(f"{self.name} 会捉老鼠")
def will_call(self,action):
print(f"动物:{self.name} 会{action}")
if __name__ == '__main__':
animal=Animal()
animal.will_call()
animal.will_run()
cat=Cat()
cat.will_call("喵喵叫")
cat.will_run()
cat.catch_mouse()
| false |
4d5515ddab16e6c87100ee57693f9d5a9823ba0e | nbuonin/project_euler | /pe_004.py | 1,413 | 4.125 | 4 | """
Project Euler Problem #4
Find the largest pallindrome of two three digit numbers
"""
def p_tester(n):
"""tests if passed value is a pallindrome"""
test_str = list(str(n))
test_str_rev = list(test_str)
test_str_rev.reverse()
return test_str == test_str_rev
class ProductKeeper:
"""An object test and track the largest pallindrome"""
def __init__(self):
self.greatest_pallindrome = 0
self.prod_a = 0
self.prod_b = 0
def check(self, p, q):
prod = p * q
if p_tester(prod) and prod > self.greatest_pallindrome:
self.greatest_pallindrome = prod
self.prod_a = p
self.prod_b = q
def get_gp(self):
return (self.greatest_pallindrome,
self.prod_a,
self.prod_b)
def greatest_pallindrome(n, m):
"""
Check all distinct pairs of integers within a range
for the largest product which is also a pallindrome.
returns a tuple of the form: (product, factor, factor)
"""
if m < n:
raise ValueError
pk = ProductKeeper()
# these nested loops compare distinct pairs of products
for i in range(n + 1, m + 1):
for j in range(n, i):
pk.check(i, j)
return pk.get_gp()
if __name__ == "__main__":
print("The largest pallindrome: %d, its factors are: %d, %d"
% greatest_pallindrome(100, 999))
| true |
61c0a0a2dc9eaf8b10fe00de641c1a0b6f8650ee | matthewgiem/Socratica.py | /Python/if_then_2.py | 259 | 4.40625 | 4 | # Prompth user to enter a number / test if even or odd
input = input("Please enter an integer: ")
# should add an exception to catch type error
number = int(input)
if number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
| true |
868c57b87bdbc0772a5ae9ae648a19d9e7a58f63 | lucascbarbosa/Calculadora-AerospaceUFRJ | /calculadora.py | 2,993 | 4.15625 | 4 | class Calculator(object): #Class calculator
def __init__(self): #Stores all attributes of class
pass
def add(self,a,b):
#method sum
# Receives:
# (a:int, b:int)
# Returns:
# a+b:int
return a+b
def sub(self,a,b):
# Method add
# Receives:
# (a:int, b:int)
# Returns:
# a-b:int
return a-b
def mult(self,a,b):
# Method sub
# Receives:
# (a:int, b:int)
# Returns:
# a-b:int
return a*b
def div(self,a,b):
# Method sub
# Receives:
# (a:int, b:int)
# Returns:
# a-b:int
return a/b
def mod(self,a,b):
# Method mod
# Receives:
# (a:int, b:int)
# Returns:
# The remainder of the division from a/b
a = int(a)
b = int(b)
return a%b
def power(self,a,b):
# Method power
# Receives:
# (a:int, b:int)
# Returns:
# a**b:int
return a**b
def root(self,a,b):
# Method power
# Receives:
# (a:int, b:int)
# Returns:
# the bth root of a: float
return a**(1/b)
def fib(self,x):
# Method fib
# Receives:
# x: int
# Returns
# the x-th fibonacci number
if x == 0 or x == 1:
return 1
else:
return self.fib(x-1)+self.fib(x-2)
if __name__ == "__main__":
calc = Calculator()
print("Welcome to the Awesome Calculator! Here are the instructions:\nType [number1] [operator] [number2 (if not needed type -)]\n The lists of operators are:\n+: sum\n-: subtraction\n*: multiplication\n/:division\n%: remainder\n^:potentiation\n~: radication.\n!: the [number1]-th fibonacci number\n")
will = True # Boolean variable to determine if the user wishes to continue using calculator
while will:
a,op,b = input("Please insert desired operation: ").split()
a = int(a) #the numbers must be int
try: #If [number2] is not null
b = int(b)
if op == "+":
answer = calc.add(a,b)
if op == "-":
answer = calc.sub(a,b)
if op == "*":
answer = calc.mult(a,b)
if op == "/":
answer = calc.div(a,b)
if op == "%":
answer = calc.mod(a,b)
if op == "^":
answer = calc.power(a,b)
if op == "~":
answer = calc.root(a,b)
print(f'The answer of {a} {op} {b} is {answer}')
except:
if op == "!":
answer = calc.fib(a-1)
print(f"The {a}-th fibonacci number is {answer}")
cont = input('Wish to continue (s/n)? ').lower()
if cont == "n":
will = False | true |
0a2057ee558fb43c7b3370c6a2ba25f4e5df3090 | Guykor/Intro-to-ML | /ex2/test_lab.py | 2,871 | 4.125 | 4 | import numpy as np
import pandas as pd
from pandas import DataFrame
from plotnine import *
def add_noise(data, mu, sigma):
"""
:param data: numpy array to add gaussian noise to
:param mu: The expectation of the gaussian noise
:param sigma: The standard deviation of the gaussian noise
:return: np array of data with noise
"""
return data + np.random.normal(loc=mu, scale=sigma)
def fit_model(x, y):
"""
:param x: numpy array of dataset samples
:param y: numpy array of response vector
:return: A fitted Linear Regression model using sklearn
"""
model = linear_model.LinearRegression()
model.fit(x, y_noisy)
return model
def create_df(x, y, mu, sigma):
"""
Return a DataFrame with the following columns (exact order and names): x, y, y_noisy, y_hat, r_squared, sigma
1) y_noisy - should be the y values after noise was added
2) y_hat - the model's prediction ofr the y values for the given x values.
3) r_squared - the goodness of fit measurement of the fitted model
4) sigma - the sigma value the values of this DataFrame were created with
Hint: On what y values should the model be trained? (In the real world do we ever observe y itself?)
:param x: The explanatory variable
:param y: The response variable
:param mu: The expectation of the gaussian noise to add
:param sigma: The standard deviation of the gaussian noise to add
:return: The created DataFrame
"""
x = x.reshape(-1, 1)
y_noisy = add_noise(y, mu, sigma)
model = fit_model(x, y_noisy)
y_hat = model.predict(x)
return pd.DataFrame({'x': x, 'y': y, 'y_noisy': y_noisy, 'y_hat': y_hat,
'r_sqared': model.score(x, y_hat), 'sigma': sigma})
def plot_lm_fitting_for_different_noises(x, y, mu, sigmas):
""""
:param x: The explanatory variable
:param y: The response variable
:param mu: The expectation of the gaussian noise to add
:param sigmas: A list of standard deviation noises to apply to response data
:return: A ggplot with the following:
1) In black the original x-y points
2) In red the x-y_noisy points (shape is `*`)
3) In blue the x-y_hat points (shape is `x`)
4) A dashed line for the x-y_hat - see geom_line (and linetype='dashed')
5) Text showing the r_squared
6) One plot for each value of sigma
Hint 1: `geom_text` also receices an `aes(...)` argument.
Hint 2: Recall `facet_wrap` from previous lab
"""
return pd.concat([create_df(x, y, mu, sigma) for sigma in sigmas], axis=0)
def main():
x = np.linspace(-2, 100, 20)
y = 2*x + 1
# df = create_df(x, y, 1, 100)
plot_lm_fitting_for_different_noises(x, y, 10, np.arange(1, 27, 5))
| true |
d4471b09355ec762b32c4c0a200035417563b9c1 | Eslee30/SimpleProjects | /Hangman/hangman.py | 1,553 | 4.21875 | 4 | import random
# opens and reads word options from .txt file
open_words_list = open("hangmanwords.txt", "r")
read_words_list = open_words_list.readlines()
# prints greeting and asks for user's name
print("Welcome to Hangman!\n")
name = input("What is your name? ")
def yes():
# chooses a word randomly from .txt file and deletes newline
chosen_word = random.choice(read_words_list).replace('\n', '')
chosen_word_list = [char for char in chosen_word]
print("\nOkay, let's start!\n")
print(len(chosen_word)* "_")
letters = []
tries = 15
while tries > 0:
print("\n\nYou have " + str(tries) + " tries left.")
tries -= 1
letter = input("Guess a letter (in lowercase)! ")
if letter not in chosen_word:
print("Wrong!")
letters.append(letter)
for char in chosen_word:
if char in letters:
print(char, end = "")
else:
print("_", end = "")
if all(elem in letters for elem in chosen_word_list) == True:
print("\n\nYou won!")
break
if all(elem in letters for elem in chosen_word_list) == False:
print("\n\nYou lost! The answer is " + chosen_word + ".")
# runs the whole game
while True:
play = input("\nHi, " + name + ", do you want to play Hangman (Y/N)? ")
if play == "Y":
yes()
elif play == "N":
print("\nToo bad.. See you next time. Bye!")
break
else:
print("\nSorry, I don't understand. Please try again.")
| true |
19fd473fe5ff45baa055065f81f226ef7cfd1da7 | bdabre/Debogitpy | /factorial.py | 484 | 4.25 | 4 | n=int(input("Enter n :"))
s=0
f=1
for i in range(1,n+1):
f=f*i
for j in range (i, i+1):
s=s+f
print("sum=",s)
# write a function fact() which returns factorial of a given number.
# use this function to calculate the sum of series
# 1!+2!+3!+...upto n terms
def fact():
s = 0
f = 1
for i in range(1, n + 1):
f = f * i
for j in range(i, i + 1):
s = s + f
return s
n = int(input("Enter a number :"))
s = fact()
print(s)
| true |
a59761bea30bb66f9c6b9a11b6d9bd2906c81bd3 | caodongxue/python_all-caodongxue | /day-10/obj/obj.py | 856 | 4.125 | 4 | '''
类:class
'''
'''
# 模板的编写
class car:
num = 0
color = ""
brand = ""
def run(self):
print("在大马路上跑来跑去!溜了溜了!!!!")
# 造车
c = car() # 车造完了
# 给车加各种属性
c.num = 4
c.color = "宝色蓝"
c.brand = "BMW"
# 让车跑起来
c.run() # 跑起来
print("我的车有",c.num,"个轮胎,车身是",c.color,"颜色,总之我的车是",c.brand,"牌子的车!")
'''
class ren:
skin_color = ""
head = 0
hair = ""
arm = 0
leg = 0
def eat(self):
print("饿了吃火锅!!!")
c=ren()
c.head = 1
c.hair = "黑色"
c.skin_color = "黄皮肤"
c.arm = 2
c.leg = 2
print("人类有",c.head,"个脑袋,",c.arm,"个胳膊,",c.leg,"条腿",c.hair,"的头发",c.skin_color)
c.eat() | false |
17b5904b2ac431b9bb9ec03bc23b8f10da853eee | PhilomenaGMIT/Script-prog | /Labs/Topic03-variables/lab03.06-randomfruit.py | 269 | 4.15625 | 4 | #Program to print out a random fruit
import random
Fruitlist = ['Apple','Orange','Pear','Melon','Lemon','Pineapple','Banana']
listlength = len(Fruitlist)
randomindex = random.randint(0,listlength-1)
print("Here is a random fruit: {}".format(Fruitlist[randomindex])) | true |
6ecc0bfeda3c09a4e92ce7f40c01327a13630c03 | jklhj222/bin | /template/argument.py | 419 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 1 15:24:44 2018 @author: jklhj
"""
import argparse
parser = argparse.ArgumentParser()
#parser.parse_args()
#parser.add_argument("echo", help="echo the string you use here")
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
#print(args.echo)
print(args.square**2) | true |
68f4615e5964e8271c335c498c8c5e363accba39 | solito83/aprendendo-programar-em-python | /d-manipulando strings/string frases.py | 607 | 4.40625 | 4 | strs = 'Aula 9 manipulação de string'
print ('{}'.format(strs))
#Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), strip(), junção com join().
frase = ('Aprendendo programar em python')
print (len(frase))
print (frase[:30])
print (frase[::15])
print (frase.count('n'))
print ('programar' in frase)
#print (frase.replace ('em', 'com'))
frase = frase.replace ('em', 'com')
print (frase)
print (frase.split())
| false |
21cd14f27109033198ba587dd5237a792290e180 | rileyL6122428/data-science-from-scratch-notes | /03-exercises/list-comprehensions.py | 621 | 4.125 | 4 | # Basic List comprehensions
even_numbers = [ num * 2 for num in range(6) ]
print('event_numbers = %s' % even_numbers)
squares = [ num ** 2 for num in range(6) ]
print('squares = %s' % squares)
# Basic Dict Comprehensions
even_number_mapping = { num : num * 2 for num in range(6) }
print('even_number_mapping = %s' % even_number_mapping)
square_mapping = { root : root ** 2 for root in range(6) }
print('square mapping = %s' % square_mapping)
# multiple loop comprehensions
some_coords = [
(x, y)
for x in range(2)
for y in range(2) # x is accessible in this loop
]
print('some_coords = %s' % some_coords) | false |
5ca409eb221f97ea60a6b646ffe5af00cf1a757a | qinyanjuidavid/Python-Basics | /PythonLists.py | 1,934 | 4.15625 | 4 | list1=['physics','Chemistry',1997,2000]
print(list1)
print(type(list1))
print(list1[0])
list2=[1,2,3,4,5,6,7,8,9]
print(list2)
print(list2[1:5])
print(list2[-1])
#Updating Lists
myList=["physics","Chemistry",1997,2000]
print(myList)
myList[3]="biology"
print(myList)
myList.append("Mathematics")
print(myList)
lis=[1,2,3,4,5]
print(lis)
del lis
try:
print(lis)
except:
print("List not available")
myList.remove(1997)
print(myList)
myList.append("Programming")
print(myList)
myList.pop(-1)
print(myList)
#Basic List Operation
newList=["c++","Java","Python"]
print(newList)
print(len(newList))
print(newList[0])
print(newList[:-1])
print(newList[1:])
#built in List method
#len() Checks the length of the function
list1=["Physics","Chemistry","Biology"]
print(list1)
print(len(list1))
newList=list(range(10))
print(newList)
print(len(newList))
myList=[1,22,56,32,78,56]
print(max(myList))
print(min(myList))
atuple=(123,"C++","Java","Python")
print(type(atuple))
aList=list(atuple)
print(aList)
print(type(aList))
#In built List methods
#Append() This method adds an object into an existing list
list1=["C++","Python","Java"]
print(list1)
list1.append("C#")
print(list1)
#count()
aList=[123,"xyz","zara","abc",123]
print(aList.count(123))
#extends()
#It appends a list on another list
myList=["Physics","Mathematics","Chemistry"]
print(myList)
newList=list(range(10))
print(newList)
newList=[1,2,3,4,5,6]
myList.extend(newList)
print(myList)
#index()
myList=["Python","C#","Java","C++"]
print(myList)
myList.insert(2,"Cobol")
print(myList)
newSub=["Mathematics","Biology","Chemistry","Physics","English"]
print(newSub)
newSub.pop(-1)
print(newSub)
newSub.append("Kiswahili")
print(newSub)
newSub.remove("Kiswahili")
print(newSub)
#Reverse
newSub.reverse()
print(newSub)
myList=["C++","Java","Python","Cobol"]
print(myList)
myList.sort()
print(myList)
myList.sort(reverse=True)
print(myList)
| true |
f4bdea1ef5112c274307c5f6f43a7e049d4566d3 | qinyanjuidavid/Python-Basics | /PythonTuples.py | 715 | 4.4375 | 4 | #Tuples are immutable
tup1=("Physics","chemistry",1997,2000)
print(tup1)
print(type(tup1))
tup1=(25,)
print(type(tup1))
tup2=("Physics","Chemistry","Mathematics",1997,2000)
print(tup2[0])
print(tup2[-1])
print(tup2[1:5])
#Updating Tuples
tup1=("Java","C++","Python","C#")
tup2=tuple(range(5))
tup3=tup1+tup2#Tuples Support Concatination
print(tup3)
#Deleting Tuples
#Del is used to delete the entire tuple
tup1=tuple(range(10))
del tup1
try:
print(tup1)
except:
print("The tuple was Deleted")
#Basic Tuple Operations
tup1=tuple(range(10))
tup2=tuple(range(5))
tup3=tup1+tup2
print(len(tup1))
print(tup3)
print(tup3.count(1))
print(tup3.index(7))
print(max(tup3))
print(min(tup3))
| false |
ad9c3c944a0523f1d10895dcbcbbfd42331a9d57 | jcgv2002/TCPC | /my scripts/3. milestone_1/app.py | 1,493 | 4.25 | 4 | MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# - adding movies
def add_movies():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
# - listing movies
def list_movies():
for movie in movies:
print_movies(movie)
# - printing movies
def print_movies(movie):
print(f"Title: {movie['title']}")
print(f"Director: {movie['director']}")
print(f"Release year: {movie['year']}")
# - finding movies
def find_movies():
user_title = input("Enter the movie title: ")
for movie in movies:
title = movie['title']
if title == user_title:
print(f"You are lucky!. {user_title} is available")
print_movies(movie)
break
else:
print(f"Sorry!, {user_title} is not available yet")
user_options ={
'a': add_movies,
'l': list_movies,
'f': find_movies
}
# - user menu
def user_menu():
selection = input(MENU_PROMPT)
while selection != 'q':
if selection in user_options:
user_options[selection]()
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
# Remember to run the user menu function at the end!
user_menu() | true |
ed2817c24e575f593721f2a1d516fd25e21110d8 | GabriOliv/python-general-scripts-exercises | /ex_03.py | 1,653 | 4.4375 | 4 | #!/usr/bin/env python3.8
# 03
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list that are less than 5.
# Extras:
# Instead of printing the elements one by one,
# make a new list that has all the elements less than 5
# from this list in it and print out this new list.
# Write this in one line of Python.
# Ask the user for a number and return a list that contains
# only elements from the original list
# a that are smaller than that number given by the user.
#List
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print("\nOriginal List:\n\t", a)
#List Size
list_size = len(a)
print("\nList of Less Than 5:")
#List Output
for i in range(list_size):
#Less than 5
if a[i] < 5:
#Print Same Line
print("\t [", a[i], "] ", end="")
#2 New Lines
print()
print("\nNew List:")
#Create New Empty List
b = []
#New List
for i in range(list_size):
#Less than 5
if a[i] < 5:
b.append(a[i])
print("\t", b, "\n\n")
#Input
#Try Exception
while True:
#Input
try:
barrier = int(input("Enter a Number: "))
assert barrier >= 0
#Error
except ValueError:
print("\n[!] Sorry, Only Non-Negative Numbers.")
#No Error
except AssertionError:
print("\n[!] Sorry, Only Non-Negative Numbers.")
else:
break
#Create New Empty List
b = []
#New List
c = []
for i in range(list_size):
#Less than 5
if a[i] < barrier:
c.append(a[i])
#\b (Backspace)
print("\nList of Less Than", barrier,"\b: ")
print("\t", c, "\n\n")
| true |
04ec3ba0b0e5c2a2dc1a03beb50e8538233fa97b | njpayne/pythagoras | /Archive/Body_Mass_Index.py | 522 | 4.40625 | 4 | # Write a program that calculates and displays a person's body mass index (BMI)
# A person's BMI is calculed with the following formula
# BMI = weight x 703 / height^2
w = float(input("Please enter your current weight (in pounds): "))
h = float(input("Please enter your current height (in inches): "))
def bmi(w, h):
body = w * (703 / (h ** 2)) # Calculate the users BMI
print("")
print("Based on our calculation, your current BMI is: ",
format(body, '.2f'))
bmi(w, h) # Call the function to initiate the program
| true |
c302972777b60dca376f5868681ad70d3827265f | njpayne/pythagoras | /Archive/cellphone.py | 2,516 | 4.40625 | 4 | # Create a class that represents cellphone data. Then, add a manufacturer, model, and retail price to the class
class CellPhone: # Create the cell phone class
"""docstring for CellPhone""" # This is the cell phone class that will be the framework for the individual objects
def __init__(self, manufac, model, retailprice): # The init class is automatically executed every time the
self.__manufac = manufac # Accept the initial argument for the manufacturing data
self.__model = model # Accept the initial argument for the model data
self.__retailprice = retailprice # Accept the initial argument for the price data
# Remember that __price enables us to hide the attribute (make it private)
# Need first to create separate methods for each of the object parameters
# The methods below accept arguments for each of the parameters
def set_manufact(self, manufac): # Accept the argument for the manufacturer
self.__manufac = manufac # This is a mutator method
def set_model(self, model): # Accept the argument for the model
self.__model = model # This is a mutator method
def set_retailprice(self, retailprice): # Accept the argument for the price
self.__retailprice = retailprice # This is a mutator method
# The following methods operate when the user asks for value of the object to be return
def get_manufac(self): # This is an accessor method
return self.__manufac
def get_model(self): # This is an accessor method
return self.__model
def get_retailprice(self): # This is an accessor method
return self.__retailprice
def main(): # Create a basic function to test the cellphone class
# Let us get all the phone data
man = input("Please input the name of the manufacturer for this cellphone: ")
model = input("Please input the name of the model for this cellphone: ")
price = float(input("Please input the price of this cellphone: "))
# Create an instance of the CellPhone class
phone = CellPhone(man, model, price) # This class is created using the three inputs which are passed to the new object
# Display the data that was entered
print("The manufacturer of your phone is:", phone.get_manufac()) # Note that phone is the object and get_manufac() is the method
print("The model of your phone is:", phone.get_model()) # Note that phone is the object and get_model() is the method acting on it
print("The price of your phone is:", phone.get_retailprice()) # Note that phone is the object and get_model() is the method acting on it
main() # Call the main function
| true |
ba93eb8f750af4a30f561f50b15de2e701efba66 | njpayne/pythagoras | /Archive/petclass_test.py | 1,511 | 4.375 | 4 | # Create a set of commands to test out the Pet Class
import petclass # Import the file titled petclass which holds the Pet class
def main(): # Create the main function
pet_list = [] # Create an empty list which will be full of pet objects
print("Welcome to the pet management system!")
print("The system below helps you manage your current pet inventory!")
print("Please note that each pet has a name, animal type, and age that you can give it!")
option = input("Would you like to add an animal to the pet management system? (y or n) ")
counter = 1
while option.lower() == 'y':
print("Please enter the information for pet", counter)
name = input("Please enter the name of your current pet! ")
animaltype = input("Please enter the type of animal! ")
age = int(input("Please enter the age of this animal (as an integer): "))
pet_object = petclass.Pet(name, animaltype, age) # Create a new pet object
pet_list.append(pet_object) # Append the pet list with the newly created pet object
option = input("Would you like to add another animal to the pet management system? (y or n) ")
counter += 1
print("")
print("") # Thank you for using the pet information system
print("You entered the following pets inside the system.")
counter = 1
for x in pet_list: # For each of the objects in the pet list
print("Pet Number:", counter)
print("Name:", x.get_name())
print("Animal Type:", x.get_animaltype())
print("Age:", x.get_age())
counter += 1
main() # Call the main function
| true |
1332be845cf9c9a1896fff8ad9818c87f06959be | njpayne/pythagoras | /Archive/Coin_Flip.py | 2,519 | 4.6875 | 5 | # Program demonstrating object oriented programming in Python through the coin flip
import random # Import the random module
# Create a coin class. This class is code that specifies the data attributes and methods for a particular object
# Note that the __init__ method initializes the sideup data attribute
class Coin: # Create the coin class. This is the cookie cutter that the objects will be built on
"""docstring for Coin"""
def __init__(self):
#self.sideup = 'Heads' # This statement assigns heads to the side-up data attribute belonging to the object that was just created
self.__sideup = 'Heads' # Note that this approach allows me to hide the attribute; Thus, outside code cannot access it
# Note that __init__ creates the first method. This method is automatically executed and is usually the first method inside a class definition
# when an instance of the class is created in memory (hence its name as an initializer method)
# Note also that the self parameter is required in every method of a class. You don't have to name it self. That said,
# the naming of this parameter is strongly recommended in order to make sure that this conforms with standard practice
def toss(self): # Create a toss method that generates a random number in the range of 0 through 1
if random.randint(0,1) == 0:
self.__sideup = 'Heads' # If the random number generated is a 0, then return heads
else:
self.__sideup = 'Tails' # Otherwise, return tails if the number is 1
def get_sideup(self): # This method returns the value of the self parameter
return self.__sideup # This parameter can be used in the main program
def main(): # Create the main function
my_Coin = Coin() # Create a new object from the Coin class above
tails = 0 # Create a counter to keep track of the number of tails
heads = 0 # Create a counter to keep track of the number of heads
times = int(input("How many times would you like to toss the coin? "))
print("Below is your list of results from the coin flip:")
for x in range(0,times):
my_Coin.toss() # Toss the coin to generate the heads or tails call
print(my_Coin.get_sideup()) # This can be optional
if my_Coin.get_sideup() == 'Heads': # If the coin flip results in a head, then add 1 to the head counter
heads += 1 # Add 1 to the head counter
else:
tails += 1 # Otherwise, add 1 to the tail counter
print("After running your program, your coin flipped a total of", heads, "heads and ", tails, "tails!")
main() # Call the main function
| true |
235a45db2750a0cad2efb3d79e9b5931373ca5b8 | njpayne/pythagoras | /Archive/User_Controlled_Square_Calculator.py | 806 | 4.28125 | 4 | # Write a program that allows the user to control the range of the values over which the
# loop runs (to calculate their squares).
print("This program displays a list of numbers, their squares, and the cumulative sum!")
min = int(input("Please enter the value that you would your range to start with: "))
max = int(input("Please enter the value that you would your range to start with: "))
def squares(min, max):
total = 0 # This is the initial value for the cumulative total
print("Num\tSquare\tCumSum") # Print the table headers
print("------------------------") # Print a line below the table header
for x in range(min, max+1):
square = x ** 2 # Calculate the square of the function
total = total + square
print(x, "\t", square, "\t", total)
squares(min, max) # Call the squares function
| true |
94ac66ccd0a0ca167050164d4b30e5515b3cc675 | njpayne/pythagoras | /Archive/contact_test.py | 712 | 4.15625 | 4 | import contact
def main(): # Create a basic function to test the cellphone class
# Let us get all the phone data
a = input("Please input the name of your contact: ")
b = input("Please input the phone number of your contact: ")
c = input("Please input the e-mail of your contact: ")
# Create an instance of the CellPhone class
address = contact.Contact(a, b, c) # This class is created using the three inputs which are passed to the new object
# Display the data that was entered
print("The name of your contact is:", address.get_name())
print("The phone number of your contact is:", address.get_phone())
print("The email of your contact is:", address.get_email())
main() # Call the main function | true |
10d13fc2d365ac5ed02d93ce14ed5f4cd3d3a08d | njpayne/pythagoras | /Archive/pickle_cellphone.py | 1,217 | 4.40625 | 4 | # The pickle module provides functions for serializing objects
# Serializing an object means converting it into a stream of bytes that can be saved to a file for later retrieval
# The pickle modules dump function serializes an object and writes it to a file
# The load function retrieves an object from a file and deserializes it (unpickles it)
import pickle
import cellphone
FILENAME = 'cellphones.dat' # This is the constant representing the file name
def main(): # Create the main function
again = 'y' # Initialize a variable to control the loop
output_file = open(FILENAME, 'wb') # Write back to the file that is open & which was created above
while again.lower() == 'y': # While the again = 'y'
man = input("Please enter the manufacturer: ")
mod = input("Please enter the model: ")
retail = float(input("Please enter the retail price: "))
phone = cellphone.CellPhone(man, mod, retail) # Create the cell phone object
pickle.dump(phone, output_file) # Pickle the object and send it to the output_file
again = input("Would you like to enter more phone data? (y/n): ")
output_file.close() # Close the file in question
print("The data was written to", FILENAME)
main() # Call the main function | true |
e0368f2d99b45e7207b467d72c92c4a587bc4d66 | njpayne/pythagoras | /Archive/Sum_of_Digits_In_A_String.py | 961 | 4.1875 | 4 | # Write a program that asks the user to enter a series of single-digit numbers with nothing separating them
# The program should display the sum of all the single-digit numbers in the string.
# For example, is the user enters 2154, the method should return 12, which is the sum of 2, 1, 5, 4
def sum(): # Define the sum function
container = [] # The list used to hold the numbers
number = input("Please enter a string of numbers that contains spaces: ") # Get the number from the user
for x in number: # Loop through all the characters in the number entry
container.append(int(x)) # int(x) converts a string value to an integer (if possible)
total = 0 # Set the total equal to zero
for b in range(0,len(container)):
total += container[b] # Loop through the entries in the container to generate a total
print("You entered the string: ", number)
print("The sum of all the numbers in your string is", total, "!")
sum() # Call the first function | true |
07aef9e567d9f75e61c70c1454794b5cc5bf74eb | Dhanush-web-source/my-cap-pro | /LIST and DICT functions.py | 2,017 | 4.28125 | 4 | #program to print the list functions in python
mylst=["A.R.rahman","uvanshankarraja","Anirudh"]
print(mylst)
#append function
mylst.append("harrisjayaraj")
print(mylst)
#clear
mylst.clear()
print(mylst)
#copy
mylst=["A.R.rahman","uvanshankarraja","Anirudh"]
myst=mylst.copy()
print(myst)
#count
print(mylst.count(0))
#length
print(len(mylst))
#index
print(mylst[-1])
print(mylst[0:])
#insert
mylst.insert(2,"santhosh")
print(mylst)
#pop
mylst.pop(2)
print(mylst)
#remove
mylst.remove("Anirudh")
print(mylst)
#reverse
mylst.reverse()
print(mylst)
#sort
nums=[20,4,32,1,16]
nums.sort()
print(nums)
#list will allow the duplicates
nums.append(20)
print(nums)
#allows different data types and for loop
mums=[96,99,6.2,"theend"]
for i in mums:
print(i)
#extend
mylst.extend(nums)
print(mylst)
#while loop
i=0
while i<len(mums):
print(mums[i])
i=i+1
#list comprehension
[print(x) for x in mums]
mems=["choclates","candies","lollies"]
germs=[]
for i in mems:
if "c" in i:
germs.append(i)
print(germs)
num1=[v for v in range(10)]
print(num1)
num1=[y for y in range(20) if y<15]
print(num1)
#sort in descending
germs.sort(reverse=True)
print(germs)
#JOIN THE TWO LISTS
m1=[1,2,3,4,5]
m2=[6,7,8,9,10]
m=m1+m2
print(m)
print("--------------------------------------------dictionary starts--------------------------------------------")
my_dict={"red":"colour","mango":"fruit","potato":"vegetable"}
print(my_dict)
print(my_dict["red"])
print(len(my_dict))
print(type("color"))
x=my_dict["potato"]
print(x)
print(my_dict.get("red"))
print(my_dict.keys())
my_dict["potato"]="snacks"
print(my_dict)
z=my_dict.values()
print(z)
for i in my_dict:
print(i)
print(my_dict.values())
n=my_dict.items()
print(n)
my_dict.update({"fruit":"jack"})
print(my_dict)
my_dict.pop("fruit")
print(my_dict)
ndict=my_dict.copy()
print(ndict)
#fromkeys
e={"k1","k2","k3","k4"}
f=0
thisdict = dict.fromkeys(e,f)
print(thisdict) | false |
0e60de3f8c9c945567c29a3dc47738d865a3307f | thri3243/cu_coding | /python_tutorials/ex05.py | 836 | 4.125 | 4 | my_name = 'Thomas W. Riley'
my_age = 23
my_height = 72 #inches
my_weight = 215 #pounds
weight_kg = my_weight * 0.454
height_cm = my_height * 2.54
my_eyes = 'Green'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {my_name}")
print(f"He's {my_height} inches tall or {height_cm} centimeters tall")
print(f"He's {my_weight} pounds heavy, which is {weight_kg} kilograms.")
print("Actually that's somewhat heavy.")
print(f"His teeth are usually {my_teeth} depending on the coffee")
print(f"He's got {my_eyes} eyes and {my_hair} hair")
#this line is trick, try to get it exavtly right
total = my_age + my_height + my_weight
total_met = my_age + weight_kg + height_cm
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}")
print(f"If I add {my_age}, {height_cm}, and {weight_kg} I get approximately {round(total_met)}")
| true |
497e7ce14ca60259cbdbddd2b751528764e0c1dd | thri3243/cu_coding | /python_tutorials/ex16_1.py | 849 | 4.15625 | 4 | from sys import argv
#declared user inputs
script, filename = argv
#first printed statement with a prompt
print(f"We're going to erase {filename}.")
print("If tou don't want that, hit CTRL-C (^C)")
print("If you do want that, hit RETURN.")
#line for input is labelled with ?
input('?')
#opens the file input by user
print("Opening the file...")
target = open(filename, 'w')
#truncates the open file
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
#declares three variables to be overwritten in the new file
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to a file.")
target.write(line1"\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()
| true |
3fa88525c38de879bd04520771503d7210c249fc | yaoxingqi/Algorithms-Learning-Python | /binary-search/binary-search-3.py | 1,106 | 4.15625 | 4 | # 查找第一个大于等于给定值的元素
def binary_search_3(nums, target):
size = len(nums)
l = 0
# 注意,r 向右边加了 1 位,因为 target 可能比 nums[-1] 还要大
r = size
while l < r:
mid = l + ((r - l) >> 1)
# 1,3,3,3,3,4,5
if nums[mid] >= target:
r = mid
else:
assert nums[mid] < target
# mid 有可能是最优解
l = mid + 1
# 特判
# if l == size - 1 and nums[-1] < target:
# return size
return l
def binary_search_3_1(nums, target):
size = len(nums)
l = 0
r = size - 1
while l < r:
mid = l + ((r - l) >> 1)
# 1,3,3,3,3,4,5
if nums[mid] >= target:
r = mid
else:
assert nums[mid] < target
# mid 有可能是最优解
l = mid + 1
# 特判
if l == size - 1 and nums[-1] < target:
return size
return l
if __name__ == '__main__':
nums = [1, 3, 3, 3, 3, 4, 5]
target = 3
result = binary_search_3_1(nums, target)
print(result)
| false |
e70e96f0db6aeb898bda38841e9897e1df0e8013 | jeehfreitas/Python | /comando input.py | 395 | 4.25 | 4 | # -*- coding: utf-8 -*-
# Input
numero = input("Digite um número: ")
print("O número digitado é: ")
print(numero)
nome = input("Digite seu nome: ")
print("Bem vindo " + nome)
# Recebendo textos
meu_texto = input("Digite um texto: ")
# Recebendo números
numero_inteiro = int(input("Digite um numero inteiro: "))
numero_decimal = float(input("Digite um numero decimal: "))
| false |
058661af4941bcf9f112f0fd08505171f756241b | ritulsingh/Python | /Life, the Universe, and Everything.py | 454 | 4.1875 | 4 | # Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
# Example
# Input:
# 1
# 2
# 88
# 42
# 99
# Output:
# 1
# 2
# 88
while(True):
n = int(input())
if (n == 42):
break
print(n) | true |
8a8cd52f154afd0e28f1703c5161641bfdf6c577 | Sekina-Muntaz/PythonBasics | /operatorsConditionalStatementsExercise.py | 1,555 | 4.34375 | 4 | #GRADING SYSTEM APPLICATION.
maths=int(input("Enter marks for maths: "))
english=int(input("Enter marks for english: "))
science=int(input("Enter marks for science: "))
kiswahili=int(input("Enter marks for kiswahili: "))
sst=int(input("Enter marks for sst: "))
print(type(sst))
# Finding total marks
totalMarks=(maths+english+kiswahili+science+sst)
print("Your total marks is: ",totalMarks)
# Finding average marks
averageMarks=(totalMarks/5)
print("Your average is: ",averageMarks)
# USING AVERAGE SCORE, GRADE THE STUDENT USING THE FOLLOWING GRADING SYSTEM
if averageMarks>=80 and averageMarks<=100:
print("Your Grade is",": A")
elif averageMarks>=75 and averageMarks<=79:
print("Your grade is ","B")
elif averageMarks >= 70 and averageMarks <= 74:
print("Your grade is", ": B+")
elif averageMarks >= 65 and averageMarks <= 69:
print("Your grade is", ": B")
elif averageMarks >=60 and averageMarks <= 64:
print("Your grade is", ": B-")
elif averageMarks >= 55 and averageMarks <= 59:
print("Your grade is", ": C+")
elif averageMarks >=50 and averageMarks<=54:
print("Your grade is",": C")
elif averageMarks>=45 and averageMarks<=49:
print("Your grade is",": C-")
elif averageMarks>=40 and averageMarks<=44:
print("Your grade is",": D+")
elif averageMarks>=35 and averageMarks<=39:
print("Your grade is",": D")
elif averageMarks>=30 and averageMarks<=34:
print("Your grade is",": D-")
elif averageMarks>=0 and averageMarks<=29:
print("Your grade is",": E")
else:
print("Check your marks again")
| true |
53f8ad5b1544dd845ee7946c501ee0fd4bf8074d | EricAragorn/crypto-predict | /crawler/util.py | 817 | 4.46875 | 4 | def list_to_string(s):
"""Convert a list to a string delimited by ","
Args:
s: the set to convert
Returns:
A formatted string
format:
FST,SND,TRD,...
"""
param_string = ''
count = 0
for p in s:
if count != 0:
param_string += ","
param_string += p
count += 1
return param_string
def string_to_double(s):
"""Convert all string elements in a list to double
Args:
s: the set to convert
Returns:
A list with all eligible string elements converted to double
"""
new_list = []
for p in s:
v = p
if type(p) is str:
try:
v = float(p)
except ValueError:
None
new_list.append(v)
return new_list
| true |
e95dbbe14b52fc8472a9c13c119bef943c8c9ee1 | xingcoAi/Elementary-machine-learning | /task_37.py | 1,553 | 4.53125 | 5 | """
什么是异常?
运行时代码抛出的错误
BaseException是所有异常的基类
异常的处理方式:
try:
代码块
except 异常名字:
代码块:你要如何去处理这个异常
else:
代码块
"""
try:
file = open("aaa", "r")
except FileNotFoundError as e:
print("发生异常")#只针对FileNotFoundError的异常
print(e)
else:
print("没有发生异常")
#异常的分级
try:
file = open("aaa", "r")
except FileNotFoundError as e:
print("发生异常")#只针对FileNotFoundError的异常
print(e)
except ReferenceError as e:
print("异常2")
except Exception:#权限大的异常放在后面
print("发生异常了")
else:
print("没有发生异常")
"""
异常的处理原则:
能处理的异常才捕获,不能处理的异常直接抛出
"""
try:
file = open("aaa", "r")
except FileNotFoundError as e:
print("发生异常")#只针对FileNotFoundError的异常
print(e)
except ReferenceError as e:
print("异常2")
except Exception:#权限大的异常放在后面
print("发生异常了")
else:
print("没有发生异常")
finally:
print("不管有没有捕获异常,这个无论如何都会被执行")
#手动抛出异常
# raise Exception("手动抛出一个异常")
try:
raise Exception("手动抛出一个异常")
except:
print("捕获一个异常")
#自定义异常
class MyDefineError(BaseException):
pass
try:
raise MyDefineError("抛出一个自定义异常")
except MyDefineError as e:
print(e) | false |
94be9a36a292b6612f70ecc05eac61a532f31bdd | xingcoAi/Elementary-machine-learning | /task_28.py | 915 | 4.125 | 4 | """
多态:一类事物有多种形态
多态性
"""
#都继承了Animal类,但run有不同形式
class Animal:
def run(self):
raise AttributeError("子类必须实现这个方法")
class Person(Animal):
def run(self):
print("person run")
class Pig(Animal):
def run(self):
print("pig run")
class Dog(Animal):
def run(self):
print("dog run")
# person = Person()
# person.run()
# pig = Pig()
# pig.run()
# dog = Dog()
# dog.run()
#多态性:
def func(obj):
obj.run()
person = Person()
func(person)
pig = Pig()
func(pig)
class Computer:
def usb_insert(self):
pass
def usb_run(sub_computer):
sub_computer.usb_insert()
class Mouse(Computer):
def usb_insert(self):
print("插入鼠标")
class keyboard(Computer):
def usb_insert(self):
print("键盘插入")
m = Mouse()
usb_run(m)
k = keyboard()
usb_run(k)
| false |
68b2fa04d7ff0333739442a88109f01b894855be | MrVJPman/UofTCoding | /CSC148/exam prep/priorityqueue.py | 2,343 | 4.1875 | 4 | class EmptyQueueError(Exception):
pass
class LinkedListNode(object):
def __init__(self, data, priority, next=None):
"""(LinkedListNode, object, float, LinkedListNode) -> NoneType"""
self.data = data
self.priority = priority
self.next = next
class PriorityQueue(object):
"""A basic priority queue class"""
# Implemented with a linked list
def __init__(self):
self._head = None
def enqueue(self, elt, priority):
"""(Queue, object, float) -> NoneType
Add the element to queue
"""
new_node = LinkedListNode(elt, priority)
if self.is_empty() or self._head.priority > priority:
# Add the new node to the beginnning of the linked list
new_node.next = self._head
self._head = new_node
else:
# Add the new node to the appropriate point in the list
# to preserve sorted order
prev = None
node = self._head
while node is not None:
if node.priority > priority:
break
prev = node
node = node.next
# At this point, prev will point to the node before where we
# want to insert new_node.
# node might be None though, if we have to add to the end.
new_node.next = prev.next
prev.next = new_node
def dequeue(self):
"""Queue -> object
Remove and return the element with the lowest priority in the queue
If multiple elements have the same priority, return the one that was
added first to the queue.
"""
if self.is_empty():
raise EmptyQueueError()
data = self._head.data
self._head = self._head.next
return data
def is_empty(self):
"""Queue -> bool
Return whether or not the queue is empty
"""
return self._head is None
if __name__ == "__main__":
q = PriorityQueue()
assert q.is_empty()
values = [(1, "a"), (0, "b"), (5, "c"), (3, "d")]
for priority, data in values:
assert q.enqueue(data, priority) is None
assert not q.is_empty()
for priority, data in sorted(values):
assert q.dequeue() == data
assert q.is_empty()
| true |
18361d73833297812061a1e255608b02ca7d193e | Bartholomeow/PythonCode | /seventh_practice/src/inputoutput/__init__.py | 795 | 4.25 | 4 | def write_to_file(data, filename, mode):
"""
Write data to file
Keyword arguments:
data - data to be written
filename - path to the file where you want to save the result
mode - mode of file (t for text or b for binary)
"""
try:
f = open(filename, "w" + mode)
except Exception as exc:
print(exc)
f.write(data)
f.close()
def read_from_file(filename, mode):
"""
Read binary data from file
Keyword arguments:
filename - path to the file where you want to save the result
mode - mode of file (t for text or b for binary)
Returns:
data - data from file
"""
try:
f = open(filename, "r" + mode)
except Exception as exc:
print(exc)
data = f.read()
f.close()
return data
| true |
2b235a288b3c5fde792b52fda7f0a777c2f85c84 | bug5654/PythonRefresh | /list.py | 897 | 4.3125 | 4 | listsample = [1,5,2,'a','a','q', False]
print("starting: " + str(listsample) )
listsample.append(True)
print("append: " + str(listsample) )
listsample.count('a')
print("count: " + str(listsample) )
listsample.index('q')
print("index q: " + str(listsample) )
listsample.insert(2,'x')
print("inserted x: " + str(listsample) )
listsample.pop()
print("after a pop: " + str(listsample) )
listsample.remove('x')
print("x removed: " + str(listsample) )
listsample.reverse()
print("after a reverse: " + str(listsample) )
comprable = [2,5,16,2,4]
print("numerical list: " + str(comprable) )
comprable.sort()
print("after sorting: " + str(comprable) )
print("and readout element by element: ")
for a in comprable:
print(a)
mytuple = (2,3)
print("tuple: " + str(mytuple)) #same as lists, but const list`
print("as a list: " + str(list(mytuple)))
print("listsample as a tuple: " + str(tuple(listsample))) | false |
24f8877c51e4541d49b600b2e0776f713e584303 | Vince-geek/Python | /00-Formation/Mooc/Semaine_1/4-Notebooks/fibonacci.py | 764 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def fibonacci(n):
"retourne le nombre de fibonacci pour l'entier n"
# pour les petites valeurs de n il n'y a rien a calculer
if n <= 1:
return 1
# sinon on initialise f1 pour n-1 et f2 pour n-2
f2, f1 = 1, 1
# et on itère n-1 fois pour additionner
for i in range(2, n + 1):
f2, f1 = f1, f1 + f2
# print(i, f2, f1)
# le résultat est dans f1
return f1
# à nouveau : ceci n'est pas conçu pour être exécuté dans le notebook !
parser = ArgumentParser()
parser.add_argument(dest="entier", type=int,
help="entier d'entrée")
input_args = parser.parse_args()
entier = input_args.entier
print(f"fibonacci({entier}) = {fibonacci(entier)}") | false |
947a3b5f2c6ab4bb0a94182b191a9d5abda80646 | BXGrzesiek/HardCoder | /pythonBasics/module1/theTasks/task1_4.py | 906 | 4.21875 | 4 | #Write a program that calculates a rectangular trapezoid field with bases 4 and 9 and arms 12 and 13.
print("Calculation The rectangular trapezoidal area.")
A=4
B=9
C=12
D=13
print("Given dimensions of the figure: "
+ "\nbase A: " + str(A)
+ "\nbase B: " + str(B)
+ "\narm1: \t" + str(C)
+ "\narm2: \t" + str(D)
+ "\nheight could be C or D. We have to check that.")
print("For rectangular trapeze, we know that the height will be the shortest arm. "
+ "\nThe IF conditional statement selects the appropriate value: ")
if C>D:
H=D
print("\nThe height is equal with D: " + str(D))
elif C==D:
H=C=D
print("\nBoth arms are the same?! How is that possible? Wrong data??")
else:
H=C
print("\nThe height is qual with C: " + str(C))
result=((A+B)*H)/2
print("\nThe area of the rectangular trapezoid is: ", end="")
print(int(result))
print("Figure circumference: ", end="")
print(A+B+C+D)
| true |
ca0dee17fee2664e9783040ee32eb03ef7954510 | BXGrzesiek/HardCoder | /pythonBasics/Exam/exam1.py | 2,217 | 4.21875 | 4 | from math import pi
# -----------FUNCTIONS-------------- #
def circle(r):
if r <= 0:
return "Invalid Data\nDataValidationFailed - radius must be positive!\n\n"
result = pi * pow(r, 2)
return result
def triangle(a, h):
if a <= 0 or h <= 0:
return "Invalid Data\nDataValidationFailed - length must be positive!\n\n"
result = 0.5 * a * h
return result
def rectangle(a, b=1):
if a <= 0 or b <= 0:
return "Invalid Data\nDataValidationFailed - length must be positive!\n\n"
result = a * b
if b == 1 or b == a:
choice = figures[3]
print(str(choice))
return result
def calculator(choice):
if choice == 1:
r = int(input('Provide r: '))
print('Area of figure type: \t' + figures[choice-1]
+ '\nwith the given values is: \t{:.2f}'.format(circle(r)))
elif choice == 2:
a = int(input('Provide a: '))
h = int(input('Provide h: '))
print('Area of figre type: \t' + figures[choice-1]
+ '\nwith the given values is: \t{:.2f}'.format(triangle(a, h)))
elif choice == 3:
a = int(input('Provide a: '))
b = int(input('Provide b: '))
if a == b:
print('Area of figre type: \t' + figures[choice]
+ '\nwith the given values is: \t{:.2f}'.format(rectangle(a, b)))
else:
print('Area of figre type: \t' + figures[choice-1]
+ '\nwith the given values is: \t{:.2f}'.format(rectangle(a, b)))
else:
print('We are here \t--> nowhere ;) \n\t\t--> try again')
# -----------VARIABLES-------------- #
figures = ['circle', 'triangle', 'rectangle', 'square']
repeat = 'y'
# -----------BODY------------------- #
while repeat == 'y' or repeat == 'Y':
try:
print('CALCULATOR v1.0.2\n\n\tOption list: ')
for figure in figures[:3]:
print('\t' + str(figures.index(figure)+1) + ': ' + figure)
choice = int(input('Provide figure name [1|2|3]: '))
calculator(int(choice))
repeat = input('You want to try again? [Y/n]')
except ValueError:
print('Value Error! \tPlease provide correct data!')
repeat = input('You want to try again? [Y/n]') | true |
b9d8fdcc64060290e7e36d2a5b72907eaff0e1f5 | lwinthida/python-exercises | /ex30.py | 438 | 4.25 | 4 | people=30
cars=40
buses=15
if cars>people:
print "We should take the cars."
elif cars<people:
print "We shouldn't take the cars."
else:
print "We can't decide."
if buses>cars:
print "That's too many buses."
elif buses<cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people>buses:
print "Alright,let's just take the buses."
else:
print "Fine,let's stay home then."
| true |
9e3ac50953198f56100f4076bedcda53894486d9 | Parz3val83/CSC-111 | /quizes/quiz_1.py | 257 | 4.21875 | 4 | a = int(input("Enter an integer: "))
b = int(input("Enter a second integer: "))
c = int(input("Enter a third integer: "))
d = int(input("Enter your final integer: "))
numerator = (a * d) + (b * c)
denominator = b * d
print(numerator / denominator) | false |
3541edf3d0894953bf501284b8e5ca05e080d0fe | AdamK42/cse163-project | /data_cleaning.py | 1,149 | 4.25 | 4 | # Name: Adam Klingler and Kayla Perez
# Description: Helper functions for cleaning the data for the main dataframe.
def get_school_names(df, prefix_len, suffix_len):
"""
Takes a school data DataFrame, prefix length, and suffix length.
Returns a list of the schools in the DataFrame.
"""
col_names = list(df.columns)
schools = list()
for name in col_names[1:]:
words = name.split()
school_list = words[prefix_len:len(words) - suffix_len]
school = " ".join(school_list)
schools.append(school)
return schools
def get_school_data(df, school_names, stat_name):
"""
Takes the raw DataFrame, the list of school names, and the name of the
statistic. Returns a list of dictionaries with keys "School", "Year", and
the given statistic name.
"""
all_data = list()
for i in range(len(df)):
year = df.loc[i, "Time"]
for j in range(len(school_names)):
row = dict()
row["Year"] = year
row["School"] = school_names[j]
row[stat_name] = df.loc[i, df.columns[j + 1]]
all_data.append(row)
return all_data
| true |
cabf4dd399160c64b8e1d1beaa9833c72bc5a13c | pombredanne/reversing-quicktest | /wordcounter.py | 1,680 | 4.21875 | 4 | '''
1. Write a script that takes a file containing a number of words (one per line) and sorts them
by the number of times they occur in the file (descending order), but exclude words that only
occur once. Ignore the case of the words and filter out any punctuation characters. The output
should contain lines each with word and the number of times it occurs in the input separated
by space.
Example input:
microsoft
apple
microsoft.
Apple
security
microsoft
internet
Example output:
microsoft 3
apple 2 '''
import argparse
import re
from collections import Counter
def transform(word):
#[^\w] matches all non word characters
return (re.sub(r'[^\w]','',word)).lower()#case is ignored
def read(file):
words = Counter()
with open(file) as f:
for word in f:
words[transform(word)] += 1;
filtered = [w for w in words.items() if w[1] > 1]
filtered.sort(key=lambda k: k[1], reverse=True)
return filtered
def log(words, outfile):
if (outfile):
with open(outfile, 'w') as f:
f.writelines("{0} {1}\n".format(w[0], w[1]) for w in words)
print("Output writtent to {0}".format(outfile))
else:
for w in words:
print("{0} {1}".format(w[0], w[1]))
def main(file, out):
words = read(file)
log(words, out)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='File containing the words.',
required=True)
parser.add_argument('-o', '--out', help='File to write result into. \
If not specified, console will be used.', required=False)
args = parser.parse_args()
main(args.source, args.out)
| true |
2156fc0d16e6439d339ea70226c8e08d70b7b22c | RuntimeX/Sandbox | /tryexTest.py | 332 | 4.15625 | 4 | while True:
try:
n = input("\nPls enter an integer.\n> ")
n = int(n)
break
except ValueError:
print("\nWTF? That is NOT an integer.\nTry again, Dipshit.")
print('Well, %i is an integer. Good job. You may live the rest of the day without\nworrying about be raping your butt.' % n)
| true |
a71d3abcce26f7a3de01b958150ae4c32f320c02 | jj1here/ATBS-Regex-Files | /search.py | 894 | 4.15625 | 4 | #!python3
#takes an input and searches the .txt files in the current directory for the word
import re, os
from pathlib import Path
# word to search for
find = input("What word would you like to find?\n")
# gets current directory
p = Path.cwd()
# for regex express
searchFor = re.compile(rf"{find}")
# collects the files with the word
found = []
# loops through the files
for file in p.glob('*.txt'):
openFile = open(file,'r') #opens the file
readFile = openFile.read() #reads the file
mo = searchFor.search(readFile) #searchs the file for the word
if mo != None : #if one instance found the file is added to found
found.append(os.path.basename(file))
final = " ".join(found) #seprates the files by a space
if len(found) > 0: #if a file was found
print(f"{find} was found in {final}")
else: #if a file was not found
print(f"Sorry I couldn't find {find}")
| true |
c9611c5024b6b291702bfa986a857e6a8984118a | p3ll1n0r3/palindrome | /palindrome.py | 1,670 | 4.375 | 4 | #!/usr/bin/env python
# palindrome.py - takes any number serie : start_num and end_number and with a maximum of iterations
# for every number, add itself and it's reverse until it reach a palindrome.
# it runs until the max_iter value has been reached.
# some numbers does not become palindrome : example number 196
import sys
def addreverse(a):
return a + int(str(a)[::-1])
def donumber(a,max_iter):
iter = 0
nums = []
nums.append(str(a) + ' : ')
while (str(a) != str(a)[::-1]) and (iter < max_iter):
a = addreverse(a)
nums.append(str(a) + ' ')
iter += 1
if iter == max_iter:
nums.append(' : Reached max iterations')
else:
nums.append(' : ' + str(iter))
return nums, iter
# Main starts here
num_iters = []
if __name__ == "__main__":
if len(sys.argv) != 4:
print('Start with 3 argumanets : start_number stop_number max_iteration')
print('Example: ./palindrome.py 100 196 10000')
print('')
exit(0)
else:
start_num = int(sys.argv[1])
end_num = int(sys.argv[2]) + 1
max_iter = int(sys.argv[3])
# for each number , run the adding until it is a palindrome or max_iter has been reached
# print the number and the resulting numbers, with the number of iterations needed
for num in range(start_num,end_num):
result, iters = donumber(num, max_iter)
# print(''.join(donumber(num, max_iter)))
print(''.join(result))
num_iters.append([num,iters])
# print a summary of each number in the serie, with number of iterations
for num_iter in num_iters:
print(num_iter)
| true |
dde09f0da6499952d3c0e5d69969088414d95260 | vcomer/class-work | /5-2.py | 357 | 4.15625 | 4 | largest = None
smallest = None
while True :
sval = input('Enter a number: ')
if sval == 'done' : break
try:
fval = float(sval)
except:
print('Invalid input')
continue
if smallest is None or fval < smallest:
smallest = fval
if largest is None or fval > largest:
largest = fval
print ("Maximum is", largest)
print ("Minimum is", smallest)
| true |
97cc6351b1da4f731763180843af3c35ae9a29b3 | AdiGarmendia/dictionaries | /dictionaryOfWords.py | 1,036 | 4.6875 | 5 | """
Create a dictionary with key value pairs to
represent words (key) and its definition (value)
"""
word_definitions = dict()
"""
Add several more words and their definitions
Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python"
"""
word_definitions["whaaaaaaatttttttt"] = "My reaction when reading about slice not needing slice"
word_definitions["quuuuuueeeeeeeeee"] = "My reaction when getting an explanation of slice"
word_definitions["Black Box"] = "where .slice() should be"
"""
Use square bracket lookup to get the definition of two
words and output them to the console with `print()`
"""
print(word_definitions["whaaaaaaatttttttt"])
print(word_definitions["quuuuuueeeeeeeeee"])
"""
Loop over the dictionary to get the following output:
The definition of [WORD] is [DEFINITION]
The definition of [WORD] is [DEFINITION]
The definition of [WORD] is [DEFINITION]
"""
for (word, definition) in word_definitions.items():
print(f"The definition of {word} is {definition}")
| true |
d2a5208ed4547a1fb2817e6ea463ab261c40e389 | FabioLGVieira/estudos | /Python/exercicios.py | 1,293 | 4.125 | 4 | from math import sqrt
""" ex1 """
idade = int(input("Digite sua idade: "))
if idade >= 18:
print("voce eh maior de 18.")
else:
print("voce nao eh maior de 18.")
""" ex2 """
nota1 = int(input("digite sua primeira nota: "))
nota2 = int(input("digite sua segunda nota: "))
media = (nota1 + nota2)/2
if media >= 6:
print("Voce foi Aprovado")
else:
print("Voce foi Reprovado")
""" ex3 """
print("y = x² - 1x + 6")
a = 1
b = -5
c = 6
delta = (b**2) - 4*a*c
print("Delta: " + str(delta))
if delta > 0:
rDelta = sqrt(delta)
raiz1 = (-b + rDelta)/2*a
raiz2 = (-b - rDelta)/2*a
print("raiz1: " + str(raiz1) + ", raiz2: " + str(raiz2))
elif delta == 0:
raiz = -b/2*a
print("raiz: " + str(raiz))
else:
print("Nao tem raiz real")
""" ex4 """
lista = [ 15,2,10,7 ]
for x in range(len(lista)):
menor = 0
maior = 0
for i in range(len(lista)):
if lista[x] < lista[i]:
menor = lista[x]
maior = lista[i]
lista[i] = menor
lista[x] = maior
print(lista)
""" ex5 """
num1 = int(input("digite um numero: "))
num2 = int(input("digite outro numero: "))
sinal = input("digite o sinal + - / *: ")
if sinal == "+":
result = num1 + num2
elif sinal == "-":
result = num1 - num2
elif sinal == "*":
result = num1 * num2
elif sinal == "/":
result = num1 / num2
print(result) | false |
3dfc407cfbddc06e5b014e427b044313cf0fb612 | valeriekamen/python | /reverse_list.py | 1,254 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_item(self, item):
new_node = Node(item)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert_item_at_start(self, item):
new_node = Node(item)
new_node.next = self.head
self.head = new_node
def printLL(self):
current = self.head
print('head', self.head.value)
while(current):
print(current.value)
current = current.next
def reverse_list(input_list):
reversed_list = LinkedList()
current = input_list.head
while current:
reversed_list.insert_item_at_start(current.value)
if not current.next:
break
current = current.next
return reversed_list
my_list = LinkedList()
my_list.insert_item(3)
my_list.insert_item(4)
my_list.insert_item(5)
print('original list')
my_list.printLL()
print('reversing')
reversed_list = reverse_list(my_list)
reversed_list.printLL() | true |
fef8d76486c4306959f965114f36db9e093565c3 | meenalgupta2306/30-Days-Of-Code-HackerRank | /Day9- Recursion 3.py | 926 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 19 15:22:44 2021
@author: Meenal
"""
#Recursive Method for Calculating Factorial
# factorial(n)= 1 n<=1
#= n* factorial(n-1) otherwise
#Function Description
#Complete the factorial function in the editor below. Be sure to use recursion.
#factorial has the following paramter:
#int n: an integer
#Returns
#int: the factorial of n
#Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of .
#Input Format
#A single integer, n (the argument to pass to factorial).
#Constraints
#2<=n<=12
#Your submission must contain a recursive function named factorial.
def factorial(n):
if(n<=1):
return 1
else:
return (n* factorial(n-1))
# Write your code here
n = int(input().strip())
print(factorial(n))
| true |
7b5042d6734934e0ef32803b047b751a2bcd84ae | PdxCodeGuild/20170626-FullStack | /lab11-distance_v2.py | 1,804 | 4.53125 | 5 |
# lab 11 v2: convert the given distance and units to the target units
# we have four types of units: meters (m), miles (mi), feet (ft), and kilometers (km)
# we could handle each case individually
# e.g. if from_units == 'm' and to_units == 'miles'
# instead, we'll just convert to meters, then convert to the target units
# 1) get the distance from the user
# 2) convert that distance to a float
# 3) get the units for that distance from the user
# 4) get the units that the user wants to convert to
# 4) convert the distance to meters
# 5) convert the distance from meters to the target
# meters = 1609.34*miles
# meters = 0.3048*feet
# meters = 1000*km
# convert the given distance from the given units to meters
def to_meters(distance, units):
if units == 'm': # meters
return distance
elif units == 'mi': # miles
return distance * 1609.34
elif units == 'ft': # feet
return distance * 0.3048
elif units == 'km': # kilometers
return distance * 1000
# convert the given distance (in meters) to the target units
def from_meters(distance, units):
if units == 'm': # meters
return distance
elif units == 'mi': # miles
return distance / 1609.34
elif units == 'ft': # feet
return distance / 0.3048
elif units == 'km': # kilometers
return distance / 1000
print('Welcome to the Distance Converter 5001™')
distance_in = float(input('what is the distance? '))
units_in = input('what are the units you\'re converting from? ')
units_out = input('what are the units you\'re converting to? ')
distance_in_m = to_meters(distance_in, units_in)
distance_out = from_meters(distance_in_m, units_out)
output = str(distance_in) + ' ' + units_in + ' is '
output += str(distance_out) + ' ' + units_out
print(output)
| true |
8c0c24baecaf3e9ab064e5f46967b2a0e120304d | PdxCodeGuild/20170626-FullStack | /lab04-rock_paper_scissors.py | 1,584 | 4.53125 | 5 |
# lab 4: play rock-paper-scissors with the computer
# 1) we get the user's choice
# 2) we check to make sure that what the user entered was among the valid possibilities
# 3) the computer randomly picks rock, paper, or scissors
# 4) depending on the choices, the program declares a winner or a tie
# below are the various combinations:
# rock - rock
# rock - scissors
# rock - paper
# scissors - rock
# scissors - scissors
# scissors - paper
# paper - rock
# paper - scissors
# paper - paper
import random
rps = ['rock', 'paper', 'scissors']
user_choice = input('which do you choose: rock, paper, or scissors? ')
print('user chooses: '+user_choice)
if user_choice in rps:
random_index = random.randint(0, 2) #get a random index: 0, 1, or 2
comp_choice = rps[random_index] #get a random choice of 'rock', 'paper' or 'scissors
print('computer chooses: '+comp_choice)
if user_choice == comp_choice: #we can eliminate 3 possibilities with one if
print('tie!')
elif user_choice == 'rock' and comp_choice == 'scissors':
print('user wins!')
elif user_choice == 'rock' and comp_choice == 'paper':
print('computer wins!')
elif user_choice == 'scissors' and comp_choice == 'rock':
print('computer wins!')
elif user_choice == 'scissors' and comp_choice == 'paper':
print('user wins!')
elif user_choice == 'paper' and comp_choice == 'rock':
print('user wins!')
elif user_choice == 'paper' and comp_choice == 'scissors':
print('computer wins!')
else:
print('you entered an invalid string')
| true |
0307e812829206dc9baabc9a2cd61951f5d1b1f4 | PdxCodeGuild/20170626-FullStack | /lab05-guess_number.py | 1,144 | 4.53125 | 5 |
# lab 5: the computer randomly picks a value, the user has to guess
# v1: the user is told they're incorrect, and given another chance to guess
# v2: the user is told whether the target is higher or lower than the guess
# v3: the user is told whether their latest guess is closer or further from the target than their last guess
import random
def abs_distance(a, b):
return abs(a-b)
target = random.randint(1, 10) #pick a random number: 1,2,3...10
last_guess = -1
while True:
guess = int(input('guess a number: '))
if guess == target:
print('correct!')
break
#else:
# print('incorrect!')
#v2
#if target > guess:
# print('higher!')
#else:
# print('lower!')
#v3
if last_guess != -1:
d_last_guess = abs_distance(last_guess, target)
d_guess = abs_distance(guess, target)
if d_guess < d_last_guess:
print('closer!')
elif d_guess > d_last_guess:
print('further!')
else:
print('you\'re the same distance away')
last_guess = guess #set the value up for the next iteration
| true |
eafce4ffafc01615b3e8b24600ccf18200dd94b6 | sairamprogramming/python_book1 | /chapter3/programming_exercises/exercise9.py | 778 | 4.25 | 4 | # Roulette Wheel Color
# Getting the pocket number from the user.
number = int(input("Enter the roulette number (1 to 36 inclusive): "))
# Finding the color of the pocket from the input number.
if number == 0:
print('pocket is green.')
elif number <= 10:
if number % 2 == 0:
print('pocket is black.')
else:
print('pocket is red.')
elif number <= 18:
if number % 2 == 0:
print('pocket is red.')
else:
print("pocket is black.")
elif number <= 28:
if number % 2 == 0:
print('pocket is black.')
else:
print('pocket is red.')
elif number <= 36:
if number % 2 == 0:
print('pocket is red.')
else:
print('pocket is black.')
else:
print('You have entered a invalid pocket number.') | true |
b4854e421c2849c0e0ae6e76c9420c5d19635123 | sairamprogramming/python_book1 | /chapter8/programming_exercises/exercise7.py | 1,162 | 4.34375 | 4 | # Character Analysis.
# This program reads a file and prints:
# Number of uppercase letters in the file.
# Number of lowercase letters in the file.
# Number of digits in the file.
# Number of whitespace characters in the file.
def main():
# Open the file in read mode.
infile = open('text.txt', 'r')
file_content = infile.read()
# Closing the file.
infile.close()
# Initazling variables.
uppercase_number = 0
lowercase_number = 0
digit_number = 0
whitespace_number = 0
# Finding the total of all the required variables respectively.
for character in file_content:
if character.isupper():
uppercase_number += 1
elif character.islower():
lowercase_number += 1
elif character.isdigit():
digit_number += 1
elif character.isspace():
whitespace_number += 1
# Display the output.
print("Total uppercase characters:", uppercase_number)
print("Total lowercase characters:", lowercase_number)
print("Total digits:", digit_number)
print("Total whitespace:", whitespace_number)
# Call the main function.
main() | true |
a336f126963769c36991ef3c0aeb376e4f2279a8 | sairamprogramming/python_book1 | /chapter4/programming_exercises/exercise12.py | 620 | 4.40625 | 4 | # Calculating the factorial of a number.
# Getting number to find the factorial for from the user.
number = int(input('Enter the number to calculate the factorial(non-negative number): '))
# Input Validation. (Number cannot be negative)
while number < 0:
print('Invalid Number, Enter a positive integer.')
number = int(input('Enter the number to calculate the factorial(non-negative number): '))
# Initaling the factorial variable, multiplicative accumulator
factorial = 1
# Finding the factorial.
for i in range(1, number + 1):
factorial *= i
# Display the output.
print("The factorial is", factorial)
| true |
b81c9216aab19d7d03f2ec8d5c717f0d8a3f405f | sairamprogramming/python_book1 | /chapter6/programming_exercises/exercise8.py | 596 | 4.28125 | 4 | # Word List File Reader.
def main():
infile = open('word_list.txt', 'r')
word_count = 0
longest_word = ''
total_characters = 0
for word in infile:
word = word.rstrip('\n')
word_count += 1
if len(word) > len(longest_word):
longest_word = word
total_characters += len(word)
infile.close()
average_length_words = total_characters / word_count
print("Number of words is file:", word_count)
print("Longest word:", longest_word)
print('Average word length:', format(average_length_words, '.2f'))
main() | true |
07280edd256adea838e7d9089a53049a4bd92472 | sairamprogramming/python_book1 | /chapter6/programming_exercises/write_numbers.py | 504 | 4.125 | 4 | # Program to create and write numbers 1 to 100 to numbers.txt file.
# Not part of any exercise just to create a file for testing all the exercise programs.
def main():
# Opening the file in write mode
outfile = open('numbers.txt', 'w')
# Writing numbers 1 to 100 to the file.
for number in range(1, 100 + 1):
outfile.write(str(number) + '\n')
# Closing the file.
outfile.close()
print('Written numbers to numbers.txt file.')
# Calling the main function.
main() | true |
ad8d5eda17b3c8191b1d4d9cfa0ee997e093e906 | sairamprogramming/python_book1 | /chapter12/programming_exercises/exercise6.py | 725 | 4.34375 | 4 | # Design a function that accepts a string as an argument. Assume that the string will contain
# a single word. The function should use recursion to determine whether the word is a palin-
# drome (a word that reads the same backwards as forward).
# Hint: Use string slicing to refer to and compare the characters on either end of the string.
# The main function.
def main():
s1 = input('Enter string: ')
s2 = input('Enter string: ')
print(is_palindrome(s1,s2))
# The recursive function.
def is_palindrome(s1, s2):
if not s1 and not s2:
return True
elif s1[-1] != s2[0]:
return False
else:
return is_palindrome(s1[:-1],s2[1:])
# Calling the main function.
main() | true |
08a6f10270b239417911a3218dba438d62a5e9c7 | sairamprogramming/python_book1 | /chapter4/algorithm_workbench/exercise9.py | 315 | 4.25 | 4 | # Input Validation
number = int(input("Enter a number between 1 and 100 (inclusive): "))
while number < 1 or number > 100:
print("ERROR! you have entered a number outside the valid range.")
number = int(input("Enter a number between 1 and 100 (inclusive): "))
print("Number you have entered is", number)
| true |
d09eb15f8c202fa02364407f205db727cc13058c | sairamprogramming/python_book1 | /chapter8/programming_exercises/exercise2.py | 277 | 4.375 | 4 | # Program to sum digits of a number for a number string.
def main():
numbers = input("Enter number: ")
total = 0
try:
for digit in numbers:
total += int(digit)
print(total)
except:
print('Invalid Inputs.')
main() | true |
5ad86a29ecba3b1e4bf0c238f23f69e591d230df | sairamprogramming/python_book1 | /chapter4/programming_exercises/exercise6.py | 420 | 4.28125 | 4 | # Miles to Kilmeters Table
# Miles to Kilometer converter constant
MILE_TO_KILOMETER_CONVERTER = 1.60934
# Heading of the table.
print("Miles\t\tKilometers")
print("-----\t\t----------")
# Loop to get the miles input required
for miles in range(10,81,10):
# CAlculating kilometers
kilometers = miles * MILE_TO_KILOMETER_CONVERTER
# Displaying the output.
print(miles, '\t\t', format(kilometers, '.2f')) | false |
f40be7b080f42de590ba76a1a1989e945ce1aa23 | sairamprogramming/python_book1 | /chapter8/programming_exercises/exercise9.py | 1,133 | 4.25 | 4 | # Vowels and Consonants.
# This tuple holds list of vowel characters in the alphabets.
VOWELS = ('a','e','i','o','u')
# This function takes a string input and returns the number of
# vowels in the string.
def total_vowels(string):
number_vowels = 0
for character in string:
if character.lower() in VOWELS:
number_vowels += 1
return number_vowels
# This function takes a string and returns the number of
# consonants in the string.
def total_consonants(string):
number_consonants = 0
for character in string:
# First condition is required, since consonants are only alphabets.
if character.isalpha() and (character.lower() not in VOWELS):
number_consonants += 1
return number_consonants
def main():
# Get string input from the user.
string_input = input("Enter a string: ")
# Display the total number of vowels and consonants in the input string.
print("Total vowels in the string is", total_vowels(string_input))
print("Total consonants in the string is", total_consonants(string_input))
# Call the main function.
main() | true |
119ee56c772944894c04f8b67fcd565071308531 | sairamprogramming/python_book1 | /chapter2/examples/string_input.py | 282 | 4.375 | 4 | # This program demonstrates the input() funtion in python.
# Get the user's first name.
first_name = input('Enter your first name: ')
# Get the user's last name.
last_name = input('Enter your last name: ')
# Printing a greeting to the user.
print('Hello', first_name, last_name)
| true |
62a572f8c75c90167d10ca2c47eb0c76a74f2942 | sairamprogramming/python_book1 | /chapter5/programming_exercises/exercise16.py | 699 | 4.1875 | 4 | # Odd/Even Counter.
import random
# Defining the main function.
def main():
# Initalizing the counter variables for even and odd integers.
count_even = 0
count_odd = 0
# Counting all the even and odd numbers from a sequence of random integers.
for i in range(100):
number = random.randint(1,1000)
if is_even(number):
count_even += 1
else:
count_odd += 1
# Display the output.
print("Total even numbers:", count_even)
print("Total odd numbers:", count_odd)
# Function returns True is number is even, else returns False
def is_even(number):
return number % 2
# Calling the main function.
main()
| true |
3a12abf67de6a3664ea33cbd7963eb752bc2ad32 | FJRH03/PythonCourse | /Essentials/Lists.py | 442 | 4.40625 | 4 | #We gonna work with List
#NOTE: When you use list you only can store values of the same type
friends = ["Kevin", "Karen", "Jim"]
friends[1] = "Martha" #update value from list
print(friends)
countries = ["Mexico","Argentina","Brazil","Chile","Peru", "Colombia"]
print(countries[1]) #access to specific value through index
print(countries[1:]) #from the index 1 to the last value
print(countries[1:3]) #from the index 1 and the third value
| false |
c4e9ef6279fd0f6ac221c3f15b5c007e3dc25ae2 | kickscar/deep-learning-practices | /01.python-basics/04/04.object_copy.py | 712 | 4.1875 | 4 | import copy
# 렌퍼런스 복사
a = 1
b = a
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = x
print(x)
print(y)
print(x is y)
# swallow copy(얕은 복사)
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.copy(x)
print(x)
print(y)
print(x is y)
print(x[0] is y[0])
# deep copy(깊은 복사)
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.deepcopy(x)
print(x)
print(y)
print(x is y)
print(x[0] is y[0])
# 깊은 복사가 복합객체만을 생성하기 때문에
# 복합 객체가 한개만 있는 경우,
# 얕은 객체와 깊은 복사는 차이가 없다.
a = ["hello", "world"]
b = copy.copy(a)
print(a is b)
print(a[0] is b[0])
c = copy.deepcopy(a)
print(a is c)
print(a[0] is c[0])
| false |
326dc136884a16eda0e276be6e6e8fb68df6d94a | aksonal/Python | /Task3.py | 819 | 4.21875 | 4 | #Task 3
#list manupulation
#Create a list of even and odd numbers.Identify even , odd numbers from the
#list and print them in separate list.Then put these two lists into dictionary
#program
List = [2,4,6,7,3,1]
#Empty lists
EvenList=[]
OddList=[]
total_1=0
total_2=0
# Iterate over the list
for value in range(0,len(List)):
if (List[value] %2 ==0):
EvenList.append(List[value])
else:
OddList.append(List[value])
print('Even numbers List is: ',EvenList)
print('Odd Numbers List is: ',OddList)
#Add all elements of each list
for value in range(0,len(EvenList)):
total_1 = total_1 + EvenList[value]
for value in range(0,len(OddList)):
total_2 = total_2 + OddList[value]
#dictionary
dict = {"Even Summation": total_1,"Odd Summation": total_2}
print(dict)
| true |
6713d787db3d39b9b51fa2d75300520981eb2048 | etcadinfinitum/zalgo-cli | /zalgo.py | 2,541 | 4.125 | 4 | #Author: Nicholas J D Dean
#Date created: 2017-12-02
import random
#take the given string and add <addsPerChar> unicode
#combining characters after each character.
def zalgo(string, addsPerChar):
result = ''
for char in string:
#add the additions to the character
for i in range(0, addsPerChar):
randBytes = random.randint(0x300, 0x36f).to_bytes(2, 'big')
char += randBytes.decode('utf-16be')
#add the character and its additions
#to the final result
result += char
return result
#keep asking for input with <inputString> until a valid int is given
def intInput(inputString):
result = -1
valid = False
while not valid:
try:
result = int(input(inputString)) #throws ValueError
#wont run if exception is thrown
valid = True
except ValueError as e:
print('Invalid input.')
return result
#accept only a valid integer character or 0, which
#is used to identify there being no limit.
def charLimitInput(minLimit):
charLimit = 0
valid = False
#receive a valid char input
while not valid:
charLimit = intInput('Character limit [0 for no limit, min ' +
str(minLimit) + ']: ')
#valid if 0 or >= minimum
if (charLimit == 0) or (charLimit >= minLimit):
valid = True
if not valid:
print('Invalid character limit.')
return charLimit
def run():
string = input('Initial string: ')
#the user can't select a limit less than twice
#the size of the string. This is to ensure that
#each character has at least one addition.
charLimit = charLimitInput(len(string) * 2)
addsPerChar = 0
#ask for the adds per char. else if they chose a limit
#then use the maximum possible per char without going
#over the limit
if charLimit == 0:
addsPerChar = intInput('Number of additions per char: ')
else:
addsPerChar = (charLimit - len(string)) // len(string)
amountWanted = intInput('Amount to generate: ')
#run the function the requested number of times
#and format the output
for i in range(0, amountWanted):
print(zalgo(string, addsPerChar), end='')
#TODO: Change number of columns based on string size
#print in 3 tabbed columns
if ((i+1) % 4 == 0):
print()
else:
print('\t', end='')
print()
if __name__ == "__main__":
run()
| true |
53a4b0f939cb4a87d07b0915ff7104ec857aa82f | Edvoy/PythonWorkout | /3. Lists and tuples/exercice11.py | 892 | 4.25 | 4 | '''
Let’s assume you have phone book data in a list of dicts, as follows:
PEOPLE = [{'first':'Reuven', 'last':'Lerner', 'email':'reuven@lerner.co.il'}, {'first':'Donald', 'last':'Trump'], 'email':'president@whitehouse.gov'}, {'first':'Vladimir', 'last':'Putin', 'email':'president@kremvax.ru'}]
Write a function, alphabetize_names, that assumes the existence of a PEOPLE constant defined as shown in the code. The function should return the list of dicts, but sorted by last name and then by first name.
'''
import operator
PEOPLE = [{'first': 'Reuven', 'last': 'Lerner',
'email': 'reuven@lerner.co.il'},
{'first': 'Donald', 'last': 'Trump',
'email': 'president@whitehouse.gov'},
{'first': 'Vladimir', 'last': 'Putin',
'email': 'president@kremvax.ru'}
]
def alphabetize_names(list_of_dicts):
return sorted(list_of_dicts,
key=operator.itemgetter('last', 'first'))
print(alphabetize_names(PEOPLE)) | true |
dd0cac64ef0b5de91ac06b0274128a0f209f6b9a | Edvoy/PythonWorkout | /2. Strings/exercice6.py | 764 | 4.125 | 4 | '''
Write a function called pl_sentence that takes a string containing several words, separated by spaces.
(To make things easier, we won’t actually ask for a real sentence.
More specifically, there will be no capital letters or punctuation.)
So, if someone were to call pl_sentence('this is a test translation') the output would be histay isway away estay ranslationtay
Print the output on a single line, rather than with each word on a separate line.
'''
def pig_latin(word):
if word[0] in 'aeiou':
return f'{word}way'
return f'{word[1:]}{word[0]}ay'
print(pig_latin('python'))
def pl_sentence(en_sentence):
pig_translation = ''
for word in en_sentence.split(' '):
pig_translation += pig_latin(word) + " "
print(pig_translation) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.