blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1c0357c5d25156eb2b9024fa411639ad0ff2aec9 | Atrociou/Saved-Things | /todo.py | 619 | 4.1875 | 4 | print("Welcome to the To Do List")
todoList = ["Homework", "Read", "Practice" ]
while True:
print("Enter a to add an item")
print("Enter r to remove an item")
print("Enter p to print the list")
print("Enter q to quit")
choice = input("Make your choice: ")
if choice == "q":
exit()
break
elif choice == "a":
add = input("What would you like to add? ")
todoList.append("Run")
elif choice == "r":
# remove an item from the list
todoList.pop()
print("The item has been removed. ")
elif choice == "p":
print(todoList)
# print the list
else:
print("That is not a choice") | true |
7ca8bdfb4b5f89ec06fb494a75413184f153401d | NISHU-KUMARI809/python--codes | /abbreviation.py | 522 | 4.25 | 4 | # python program to print initials of a name
def name(s):
# split the string into a list
l = s.split()
new = ""
# traverse in the list
for i in range(len(l) - 1):
s = l[i]
# adds the capital first character
new += (s[0].upper() + '.')
# l[-1] gives last item of list l. We
# use title to print first character in
# capital.
new += l[-1].title()
return new
# Driver code
s = "Avul pakir Jainulabdeen Abdul Kalam"
print(name(s))
| true |
6c8e860f0ac34f6199c71ba0b528622dc980e61a | xdc7/pythonworkout | /chapter-03/01-extra-02-sum-plus-minus.py | 1,155 | 4.15625 | 4 | """
Write a function that takes a list or tuple of numbers. Return the result of alternately adding and subtracting numbers from each other. So calling the function as plus_minus([10, 20, 30, 40, 50, 60]) , you’ll get back the result of 10+20-30+40-50+60 , or 50 .
"""
import unittest
def plus_minus(sequence):
sumResult = 0
for i in range (0, len(sequence)):
if i % 2 == 0 and i != 0:
sumResult = sumResult - sequence[i]
else:
sumResult = sumResult + sequence[i]
return sumResult
print(plus_minus([10, 20, 30, 40, 50, 60]))
print(plus_minus([10, -20, 30, 40, -50, 60]))
print(plus_minus([-10, 20, 30, 40, 50, 60]))
print(plus_minus([10, 20, 30, 40, -50, 60]))
# class TeststringListTranspose(unittest.TestCase):
# def test_blank(self):
# self.assertEqual(even_odd_sums(''), [0,0])
# def test_valid01(self):
# self.assertEqual(even_odd_sums([10, 20, 30, 40, 50, 60]) , [90, 120])
# # def test_valid02(self):
# # self.assertEqual(even_odd_sums('Beckham Zidane Maldini Aguero Lampard'), 'Aguero,Beckham,Lampard,Maldini,Zidane')
# if __name__ == '__main__':
# unittest.main() | true |
182bc373458a808387825084a7927ff50288e270 | xdc7/pythonworkout | /chapter-02/05-stringsort.py | 984 | 4.25 | 4 | """
In this exercise, you’ll explore this idea by writing a function, strsort, that takes a single string as its input, and returns a string. The returned string should contain the same characters as the input, except that its characters should be sorted in order, from smallest Unicode value to highest Unicode value.
For example, the result of invoking strsort('cba') will be the string abc.
"""
import unittest
def strsort(inputString):
return ''.join(sorted(inputString))
class TeststringListTranspose(unittest.TestCase):
def test_blank(self):
self.assertEqual(strsort(''), '')
def test_valid01(self):
self.assertEqual(strsort('abc'), 'abc')
def test_valid02(self):
self.assertEqual(strsort('cba'), 'abc')
def test_valid03(self):
self.assertEqual(strsort('defjam'), 'adefjm')
def test_valid04(self):
self.assertEqual(strsort('bcfa'), 'abcf')
if __name__ == '__main__':
unittest.main()
| true |
92188bb3349159b96640692939e9b784426ee41d | xdc7/pythonworkout | /chapter-04/03-restaurant.py | 1,383 | 4.28125 | 4 | """
create a new dictionary, called menu, representing the possible
items you can order at a restaurant. The keys will be strings, and the values will be prices (i.e.,
integers). The program will then ask the user to enter an order:
If the user enters the name of a dish on the menu, then the program prints the price and
the running total. It then asks what else the user wants to order.
If the user enters the name of a dish not on the menu, then the program scolds the user
(mildly). It then asks what else the user wants to order.
If the user enters an empty string, then the program stops asking, and prints the total
amount.
For example, a session with the user might look like this:
Note that you can always check to see if a key is in a dict with the in operator. That returns True
Order: sandwich
sandwich costs 10, total is 10
Order: tea
tea costs 7, total is 17
Order: elephant
Sorry, we are fresh out of elephant today.
Order: <enter>
Your total is 17
"""
menu = {'sandwich' : 10, 'tea' : 7, 'soup' : 9, 'soda' : 4,}
totalBill = 0
while True:
print('Please enter an item to order and add it to your cart. Just hit enter when you are done ordering')
choice = input().strip()
if not choice:
break
if choice not in menu:
print(f'Sorry we are out of fresh {choice}')
continue
totalBill += menu.get(choice)
print(f'Your total bill is {totalBill}') | true |
a265236d9b35352de75c292cd30b2b66301aae55 | xdc7/pythonworkout | /chapter-02/01-pig-latin.py | 987 | 4.25 | 4 | """write a Python program that asks the user to enter an English word. Your program should then print the word, translated into Pig Latin. You may assume that the word contains no capital letters or punctuation.
# How to translate a word to pig latin:
* If the word begins with a vowel (a, e, i, o, or u), then add way to the end of the word. So air becomes airway and eat becomes eatway .
* If the word begins with any other letter, then we take the first letter, put it on the end of the word, and then add ay . Thus, python becomes ythonpay and computer becomes omputercay .
"""
def wordToPiglatin(word):
if len (word) < 1:
return None
word = word.lower()
result = ''
if word[0] in 'aeiou':
result = word + 'way'
else:
result = word[1:] + word[0] + 'ay'
return result
print (wordToPiglatin('air'))
print (wordToPiglatin('eat'))
print (wordToPiglatin('python'))
print (wordToPiglatin('computer'))
print (wordToPiglatin('a')) | true |
476c3f377be42a32630992fd0fbbc18bce1c9288 | xdc7/pythonworkout | /chapter-05/5.2.2-factors.py | 1,054 | 4.28125 | 4 | """
Ask the user to enter integers, separated by spaces. From this input, create a dictionary whose keys are the factors for each number, and the values are lists containing those of the users' integers that are multiples of those factors.
"""
def calculateFactors(num):
factors = []
for i in range (1, num + 1):
if num % i == 0:
factors.append(i)
return factors
uniqueFactors = []
result = {}
integerInput = input('Enter integers separated by spaces...\n')
integers = integerInput.split()
for integer in integers:
# print(f"{integer}")
integer = int(integer)
factors = calculateFactors(integer)
for factor in factors:
if factor not in uniqueFactors:
uniqueFactors.append(factor)
for integer in integers:
integer = int(integer)
for factor in uniqueFactors:
if factor % integer == 0:
if result.get(factor):
result[factor].append(integer)
else:
result[factor] = [integer]
print(result) | true |
bfdc1168bf7bbbf621d41de4efb479b1bf4a11fe | xdc7/pythonworkout | /chapter-01/05-extra-01-hex-to-dec.py | 1,737 | 4.25 | 4 | """
Write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen. Implement the above program such that it doesn’t use the int function at all, but rather uses the builtin ord and chr functions to identify the character. This implementation should be more robust, ignoring characters that aren’t legal for the entered number base.
"""
def hexToDec(userInput):
userInput = list(str(userInput))
userInput.reverse()
result = 0
for i, digit in enumerate(userInput):
temp = 0
if (ord(digit) >= 48 and ord(digit) <= 57) or (ord(digit) >= 65 and ord(digit) <= 70) or (ord(digit) >= 97 and ord(digit) <= 102):
if ord(digit) == 48:
temp = 0
elif ord(digit) == 49:
temp = 1
elif ord(digit) == 50:
temp = 2
elif ord(digit) == 51:
temp = 3
elif ord(digit) == 52:
temp = 4
elif ord(digit) == 53:
temp = 5
elif ord(digit) == 54:
temp = 6
elif ord(digit) == 55:
temp = 7
elif ord(digit) == 56:
temp = 8
elif ord(digit) == 57:
temp = 9
elif ord(digit) == 65 or ord(digit) == 97:
temp = 10
elif ord(digit) == 66 or ord(digit) == 98:
temp = 11
elif ord(digit) == 67 or ord(digit) == 99:
temp = 12
elif ord(digit) == 68 or ord(digit) == 100:
temp = 13
elif ord(digit) == 69 or ord(digit) == 101:
temp = 14
elif ord(digit) == 70 or ord(digit) == 102:
temp = 15
else:
return "Invalid hexadecimal number"
tempResult = temp * 16 ** i
result += tempResult
return result
print(hexToDec(50))
print(hexToDec('ABC'))
print(hexToDec(0))
print(hexToDec('FEDC134'))
| true |
38a591219f2e390385353788fa8c1eb969e4d253 | maurice-gallagher/exercises | /chapter-5/ex-5-6.py | 2,004 | 4.5 | 4 | # Programming Exercise 5-6
#
# Program to compute calories from fat and carbohydrate.
# This program accepts fat grams and carbohydrate grams consumed from a user,
# uses global constants to calculate the fat calories and carb calories,
# then passes them to a function for formatted display on the screen.
# Global constants for fat calories per gram and carb calories per gram
# define the main function
# Define local float variables for grams of fat, grams of carbs, calories from fat,
# and calories from carbs
# Get grams of fat from the user.
# Get grams of carbs from the user.
# Calculate calories from fat.
# Calculate calories from carbs.
# Call the display calorie detail function, passing grams of fat, grams of carbs,
# calories from fat and calories from carbs as arguments
# Define a function to display calorie detail.
# This function accepts grams of fat, grams of carbs, calories from fat,
# and calories from carbs as parameters,
# performs no calculations,
# but displays this information formatted for the user.
# print each piece of information with floats formatted to 2 decimal places.
# Call the main function to start the program
FAT_CAL_PER_GRAM = 9
CARB_CAL_PER_GRAM = 4
def main():
grams_fat = 0.0
grams_carbs = 0.0
cals_fat = 0.0
cals_carbs = 0.0
grams_fat = float(input('How many grams of fat: '))
grams_carbs = float(input('How many grams of carbs: '))
cals_fat = grams_fat * FAT_CAL_PER_GRAM
cals_carbs = grams_carbs * CARB_CAL_PER_GRAM
calorie_details(grams_carbs, grams_fat, cals_carbs, cals_fat)
def calorie_details(grams_carbs, grams_fat, cals_carbs, cals_fat):
print('Grams of fat:', format(grams_fat, ".2f"))
print('Grams of carbs', format(grams_carbs, ".2f"))
print('Calories from fat', format(cals_fat, ".2f"))
print('Calories from carbs', format(cals_carbs, ".2f"))
main()
| true |
667c668af92cafa7af07828df395d4d43b948b75 | nazariyv/leetcode | /solutions/medium/bitwise_and_of_numbers_range/main.py | 554 | 4.3125 | 4 | #!/usr/bin/env python
# Although there is a loop in the algorithm, the number of iterations is bounded by the number of bits that an integer has, which is fixed.
def bit_shift(m: int, n: int) -> int:
shifts = 0
while m != n:
m >>= 1
n >>= 1
shifts += 1
return 1 << shifts
# if n >= 2 * m:
# return 0
# else:
# r = m
# # time complexity is O(n - m)
# for i in range(m + 1, n + 1):
# r &= i
# return r
if __name__ == '__main__':
print(bit_shift(4, 6))
| true |
e305999659409116a695be650da868d41cad775c | sandeepbaldawa/Programming-Concepts-Python | /recursion/regex_matching_1.py | 1,453 | 4.28125 | 4 | '''
Implement a regular expression function isMatch that supports the '.' and '*' symbols.
The function receives two strings - text and pattern - and should return true if the text
matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.'
and '*' do not appear in the text string and are used as special symbols only in the pattern string.
Logic
=====
1. Pattern and Text match and reach end of size
2. Text reaches end of size but pattern does not
3. Pattern reaches end of size but text does not
4. Character match or "." followed by "*"
5. Pattern and Text match
'''
def match_regex(s, p):
T = [[False] * (len(p)+1) for _ in range(len(s)+1)]
T[0][0] = True
for i in xrange(1, len(T[0])):
if p[i-1] == "*":
T[0][i] = T[0][i-2]
for i in xrange(1, len(T)):
for j in xrange(1, len(T[0])):
if p[j-1] == "." or s[i-1] == p[j-1]:
T[i][j] = T[i-1][j-1]
elif p[j-1] == "*":
T[i][j] = T[i][j-2] # * consume zero characters
if s[i-1] == p[j-2] or p[j-2] == ".": # * consumes one or more
T[i][j] = T[i-1][j]
else:
T[i][j] = False
return T[len(s)][len(p)]
assert match_regex("aaa","aa") == False
assert match_regex("aaa","aaa") == True
assert match_regex("ab","a.") == True
assert match_regex("abbb","ab*") == True
assert match_regex("a","ab*") == True
assert match_regex("abbc","ab*") == False
| true |
96a0bc369ee2198c2bc03d5d555d6449a4339693 | sandeepbaldawa/Programming-Concepts-Python | /recursion/cryptarithm.py | 2,093 | 4.28125 | 4 | Cryptarithm Overview
The general idea of a cryptarithm is to assign integers to letters.
For example, SEND + MORE = MONEY is “9567 + 1085 = 10652”
Q. How to attack this problem?
-Need list of unique letters
-Try all possible assignments of single digits
-Different arrangement would produce a different answer
So, we want a permutation of the number of unique letters with unique numbers. First we need to get an expression…
def cryptarithm(expr):
We need to have a function that takes in a word and replaces the letters with digits, so it gives 3 5 6 4 instead of SEND. We can define this now inside cryptarithm and call it later.
def makeCryptValue(word, map):
# MakeCryptValue("SEND", {"S":5, "E":2, "N":1, "D":8 }) returns 5218
result = 0
for letter in word: #Walk through the result, get the digit and shift
result = 10*result + map[letter] #10*result is the shift, map[letter] is the digit value
return result
# 1) Make list of words, so word[0] + word[1] = word[2]. Assume that the expression is well-formed.
# Words = ["SEND", "MORE", "MONEY"]
words = expr.replace("+"," ").replace("="," ").split(" ") #use str.split()
# 2) Want a list of unique letters. Use sets for uniqueness
letters = sorted(set("".join(words))) #Returns unique letters
for digitAssignment in permutations(range(10), len(letters)): #Try every permutation of digits against letters
#If 4 letters, groups of 4. If more than 10 letters, change the base
map = dict(zip(letters, digitAssignment)) #Create tuples of letter/digit and put into a dictionary
values = [makeCryptValue(word, map) for word in words] #Now call the function that we created earlier
if (0 in [map[word[0]] for word in words]):
#The first number of any word cannot be a leading 0! We can create a map to check this
continue
if (values[0] + values[1] == values[2]): #We win!
return "%d+%d=%d" % (values[0], values[1], values[2])
return None
| true |
d39cf9c6a416f7678bf3b98e36ab52b6ac17997a | sandeepbaldawa/Programming-Concepts-Python | /recursion/crypto_game.py | 2,243 | 4.34375 | 4 | '''
Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None.
Where are we spending more time?
if we run CProfile on CProfile.run('test()')
we see maximum time is spent inside valid function,
so how do we optimize the same?
In valid function we use eval which repeated parses
all tokens, we might not have to do this always.
copiling this once is fine
>>> f = lambda Y, M, E, U, O:(1*U+10*O+100*Y) == (1*E+10*M)**2
>>> f(2,1,7,9,8)
True
>>> f(1,2,3,4,5)
False
Check faster version in cryptogame_faster.py
'''
from __future__ import division
import itertools, string, re, time
import cProfile
def solve(formula):
"""Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None."""
for f in fill_in(formula):
if valid(f):
return f
def fill_in(formula):
"Generate all possible fillings-in of letters in formula with digits."
letters = ''.join(set(re.findall('[A-Z]',formula))) #should be a string
for digits in itertools.permutations('1234567890', len(letters)):
table = string.maketrans(letters, ''.join(digits))
yield formula.translate(table)
def valid(f):
"""Formula f is valid if and only if it has no
numbers with leading zero, and evals true."""
try:
return not re.search(r'\b0[0-9]', f) and eval(f) is True
except ArithmeticError:
return False
tests = ("TWO + TWO == FOUR\n"
"X/X == X\n"
"A**N + B**N == C**N \n"
"GLITTERS is not GOLD\n"
"ONE < TWO and FOUR < FIVE\n"
"ONE < TWO < THREE\n"
"PLUTO not in set([PLANETS])\n"
"ODD + ODD == EVEN\n"
"sum(range(AA)) == BB\n"
"sum(range(POP)) == BOBO\n"
"RAMN == RA**3 + MN**3\n"
"ATOM**0.5 == A + TO + M \n").splitlines()
def test():
t0 = time.clock()
print tests
for each in tests:
t_each = time.clock()
print "Problem : %s Result: %s" % (each, solve(each)),
print " Time Taken : ", time.clock() - t_each
print "Total Time Taken : ", time.clock() - t0
print cProfile.run('test()')
| true |
16494f0438fe6af0cfc369187fa8c8708bda7925 | sandeepbaldawa/Programming-Concepts-Python | /lcode/amazon/medium_sort_chars_by_freq.py | 504 | 4.25 | 4 | '''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
'''
from collections import defaultdict
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
res = defaultdict(int)
for each in s:
res[each] += 1
res = sorted(res.items(), key = lambda i: i[1], reverse=True)
return "".join([key*val for key,val in res])
| true |
4fcf4d2382a0222c93bcd328383399ea292ea031 | isrishtisingh/python-codes | /URI-manipulation/uri_manipulation.py | 1,173 | 4.125 | 4 | # code using the uriModule
# the module contains 2 functions: uriManipulation & uriManipulation2
import uriModule
# choice variable is for choosing which function to use for manipulating the URL/URI
choice = -1
try:
choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/URL \n"))
except ValueError:
print("Invalid input\n")
exit()
if (choice == 1):
print(" \n Enter any of the following numbers to get parts of the URI/URL : ")
n = input(" 1 for scheme \n 2 for sub-domain \n 3 for domain \n 4 for directory/path \n 5 for sub-directory/query \n 6 for page/fragment\n\n ")
try:
if (type(n) != int):
uriModule.uriManipulation(n)
except TypeError:
print("Your input must be a number\n")
elif(choice == 2):
url = input("Enter a URL: ")
print(" \n Enter any of the following numbers to get parts of the URI/URL : ")
n = int(input(" 1 for scheme \n 2 for authority+domain \n 3 for directory/path \n 4 for sub-directory/query \n 5 page/fragment\n\n "))
print(uriModule.uriManipulation2(url, n))
else:
print("\nInvalid choice\n")
| true |
89ea463ab59b1aa03b14db54ec8d86a8a4168fcf | iriabc/python_exercises | /exercise3.py | 2,082 | 4.46875 | 4 | from collections import deque
def minimum_route_to_treasure(start, the_map):
"""
Calculates the minimum route to one of the treasures for a given map.
The route starts from one of the S points and can move one block up,
down, left or right at a time.
Parameters
----------
the_map: list of lists
Matrix containing the points of the map
e.g.
[
[‘S’, ‘O’, ‘O’, 'S', ‘S’],
[‘D’, ‘O’, ‘D’, ‘O’, ‘D’],
[‘O’, ‘O’, ‘O’, ‘O’, ‘X’],
[‘X’, ‘D’, ‘D’, ‘O’, ‘O’],
[‘X', ‘D’, ‘D’, ‘D’, ‘O’],
]
Map with different features:
- S is a point you can start from
- O is a point you can sail in
- D is a dangerous point you can't sail in
- X is the point with the treasure
"""
# Map dimensions
width = len(the_map)
height = len(the_map[0])
# Check that the map has some dimensions
if width == 0 or height == 0:
raise ValueError("Please provide a valid map")
# Define start point and features
treasure = "X"
danger = "D"
# Create a queue to store the track
queue = deque([[start]])
visited = [start]
# Find the path
while queue:
path = queue.popleft()
x, y = path[-1]
# Check if we have found the treasure
if the_map[x][y] == treasure:
return path
# Move using one of the possible movements
for x2, y2 in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if 0 <= x2 < width and 0 <= y2 < height and the_map[x2][y2] != danger \
and (x2, y2) not in visited:
queue.append(path + [(x2, y2)])
visited.append((x2, y2))
def min_route_to_many_treasures(the_map):
# Filter the starting points
starts = [(0, 0), (0, 3), (0, 4)]
paths = [minimum_route_to_treasure(start, the_map) for start in starts]
shortest_path = min(paths, key=len)
return shortest_path
| true |
19d10ffc36a71b8e662857b9f83cbdecdb47114e | TnCodemaniac/Pycharmed | /hjjj.py | 567 | 4.125 | 4 |
import turtle
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
s= int(num_str)
angle = 180 - 180*(10-2)/10
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color("red")
x += 5
y += 5
turtle.forward(x)
turtle.left(y)
for i in range(squares):
turtle.begin_fill()
turtle.down()
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
print (turtle.pos())
turtle.up()
turtle.end_fill()
| true |
2d5a337a4cef68a85705c164d5dcdfbd4edb5e17 | nembangallen/Python-Assignments | /Functions/qn10.py | 384 | 4.15625 | 4 | """
10. Write a Python program to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
"""
def get_even(my_list):
even_list = []
for item in my_list:
if (item % 2 == 0):
even_list.append(item)
else:
pass
return even_list
print(get_even([1, 2, 3, 4, 5, 6, 7, 8, 9]))
| true |
8a872760535ef1b17100bdd9faee4ff6609c1b8d | nembangallen/Python-Assignments | /Functions/qn13.py | 395 | 4.21875 | 4 | """
13. Write a Python program to sort a list of tuples using Lambda.
"""
def sort_tuple(total_student):
print('Original List of tuples: ')
print(total_student)
total_student.sort(key=lambda x: x[1])
print('\nSorted:')
print(total_student)
total_student = [('Class I', 60), ('Class II', 53),
('Class III', 70), ('Class V', 40)]
sort_tuple(total_student)
| true |
040902675356f5d842d290c5b0570546bc83c9cb | nembangallen/Python-Assignments | /Functions/qn8.py | 387 | 4.28125 | 4 | """
8. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
"""
def unique_list(my_list):
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
return unique_list
print(unique_list([1, 2, 3, 3, 3, 4, 5, 5]))
| true |
ecedcca7da6cd799acc1bce8c0e2b4361c9652a4 | BlaiseMarvin/pandas-forDataAnalysis | /sortingAndRanking.py | 1,820 | 4.34375 | 4 | #sorting and ranking
# to sort lexicographically, we use the sort_index method which returns a new object
import pandas as pd
import numpy as np
obj=pd.Series(range(4),index=['d','a','b','c'])
print(obj)
print("\n")
print(obj.sort_index()) #this sorts the indices
#with a dataframe, you can sort by index on either axis
frame=pd.DataFrame(np.arange(8).reshape((2,4)),index=['three','one'],columns=['d','a','b','c'])
print("\n")
print(frame)
print("\n")
print(frame.sort_index()) # it originally sorts the row index
#sorting the column index
print(frame.sort_index(axis=1))
#by default, the data is sorted in ascending order, we can change that though
print(frame.sort_index(axis=1,ascending=False))
#to sort a series by its values, you make use of the sort_values method
obj=pd.Series([4,7,-3,2])
print(obj)
print(obj.sort_values())
#Any missing values are always sorted to the end
#when sorting,you can sort by some data
frame= pd.DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]})
print(frame)
print(frame.sort_values(by='b'))
#to sort by multiple columns, we pass a list of names
print(frame.sort_values(by=['a','b']))
#Ranking
#ranking assigns ranks from one through the number of valid data points in an array
#The rank method for series and Dataframe are the place to look, ties are broken by assigning the mean rank
obj=pd.Series([7,-5,7,4,2,0,4])
print("\n")
print(obj)
print("\n")
print(obj.rank())
#Ranks can also be assigned acoording to the order in which they're observed in the data
print(obj.rank(method='first'))
#Ranks can also be assigned in descending order
print(obj.rank(ascending=False,method='max'))
#A dataframe can compute ranks over the columns and rows
frame=pd.DataFrame({'b':[4.3,7,-3,2],'a':[0,1,0,1],'c':[-2,5,8,-2.5]})
print(frame)
print("\n")
print(frame.rank(axis='columns')) | true |
7d44b3978280fed567e2422c24f0d2488c28d89d | vandent6/basic-stuff | /elem_search.py | 893 | 4.15625 | 4 |
def basic_binary_search(item, itemList):
"""
(str, sequence) -> (bool)
Uses binary search to split a list and find if the item is in the list.
Examples:
basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> True
basic_binary_search(99,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> False
"""
found = False
while found == False:
half = round(len(itemList)/2)
if not half % 2:
half -= 1
if len(itemList) == 1:
return itemList[0] == item
if itemList[half] == item:
found == True
if item >= itemList[half]:
itemList = itemList[half:]
elif item < itemList[half]:
itemList = itemList[:half]
return found
print(basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]))
| true |
2817f68fa0dc08ba61921f04a3c4ea5eccc31b38 | ltrii/Intro-Python-I | /src/cal.py | 1,702 | 4.6875 | 5 | # """
# The Python standard library's 'calendar' module allows you to
# render a calendar to your terminal.
# https://docs.python.org/3.6/library/calendar.html
# Write a program that accepts user input of the form
# `calendar.py month [year]`
# and does the following:
# - If the user doesn't specify any input, your program should
# print the calendar for the current month. The 'datetime'
# module may be helpful for this.
# - If the user specifies one argument, assume they passed in a
# month and render the calendar for that month of the current year.
# - If the user specifies two arguments, assume they passed in
# both the month and the year. Render the calendar for that
# month and year.
# - Otherwise, print a usage statement to the terminal indicating
# the format that your program expects arguments to be given.
# Then exit the program.
# """
import sys
import calendar
from datetime import datetime
dt = datetime.today()
if len(sys.argv) == 3:
month = str(sys.argv[1])
year = str(sys.argv[2])
elif len(sys.argv) == 2:
month = str(sys.argv[1])
year = dt.year
elif len(sys.argv) == 1:
month = dt.month
year = dt.year
month = int(month)
year = int(year)
if month & year == None:
print("Please provide at least one argument (month, year).")
if year == None:
year = datetime.date.today().strftime("%Y")
if month == None:
month = datetime.date.today().strftime("%B")
if month > 12:
print("Month provided is above range")
elif month < 1:
print("Month provided is below range")
else:
month = int(month)
year = int(year)
cal = calendar.TextCalendar(firstweekday=6)
curCal = "\n" + cal.formatmonth(year, month)
print(curCal)
| true |
4d726618926c5e8d18a6f6a1f6b69fe670c46ad5 | JayVer2/Python_intro_week2 | /7_dictionaries.py | 469 | 4.125 | 4 |
#Initialize the two dictionaries
meaningDictionary = {}
sizeDictionary = {}
meaningDictionary["orange"] = "A Fruit"
sizeDictionary["orange"] = 5
meaningDictionary["cabbage"] = "A vegetable"
sizeDictionary["cabbage"] = 10
meaningDictionary["tomato"] = "Widely contested"
sizeDictionary["tomato"] = 5
print("What definition do you seek?")
query = input()
print("The size of " + query + " is " +str(sizeDictionary[query]) + ", it means: " + meaningDictionary[query])
| true |
4207246674a228f5ab87bf29c41ef6677a1165fc | jaclynchorton/Python-MathReview | /Factorial-SqRt-GCD-DegreeAndRadians.py | 556 | 4.15625 | 4 | #------------------From Learning the Python 3 Standard Library------------------
#importing math functions
import math
#---------------------------Factorial and Square Root---------------------------
# Factorial of 3 = 3 * 2* 1
print(math.factorial(3))
# Squareroot of 64
print(math.sqrt(64))
# GCD-Greatest Common Denominator. Useful for reducing fractions
# 8/52 = 2/13
# GCD between 8 and 52 is 4, so we can divide the numerator and denominator by 4
# to get a reduced fraction
print(math.gcd(52, 8))
print(math.gcd(8, 52))
print(8/52)
print(2/13)
| true |
0eacae023b58e7727bcfcec37684d47ab49ddfbb | Jabed27/Data-Structure-Algorithms-in-Python | /Algorithm/Graph/BFS/bfs.py | 1,508 | 4.25 | 4 | # https://www.educative.io/edpresso/how-to-implement-a-breadth-first-search-in-python
from collections import defaultdict
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
#initializing a default dictionary with list
graph=defaultdict(list)
parent=[]
dist=[]
def init(n):
for i in range(n+1):
dist.append(-1)
for i in range(n+1):
parent.append(-1)
def shortestPath(i):
if(parent[i]==-1):
print(i,end=' ')
return
shortestPath(parent[i])
print(i,end=' ')
def ShortestDistance(source):
for i in range(1,len(visited)+2):
if(i != source):
if(dist[i]!=-1):
dist[i]*=6
print("\n"+str(i)+"->"+str(dist[i]),end='\n')
print("Shortest path: ")
shortestPath(i)
def bfs(visited, graph, source):
visited.append(source)
queue.append(source)
dist[source]=0
print("BFS traversals: ")
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
dist[neighbour]=dist[s]+1
parent[neighbour]=s
print("\n")
ShortestDistance(source)
# Driver Code
node,edge=input().split()
for i in range(int(edge)):
a,b= input().split()
graph[int(a)].append(int(b))
graph[int(b)].append(int(a))
starting_node=int(input())
init(int(node))
bfs(visited, graph, starting_node) | true |
a4a2e639b8c672ebfdb7f8b67f1f567c1ebc704e | Programmer7129/Python-Basics | /Functions.py | 444 | 4.25 | 4 | # For unknown arguments in a function
def myfunc(**name):
print(name["fname"]+" "+name["lname"])
myfunc(fname="Emily", lname="Scott")
def func(*kids):
print("His name is: "+ kids[1])
func("Mark", "Harvey", "Louis")
# Recursion
def recu(k):
if(k > 0):
result = k + recu(k-1)
print(result)
else:
result = 0
return result
print("The Recursion Example Results \n")
recu(3)
| true |
79072e55960b5de9f56486db34748bfaa55c08b9 | FayazGokhool/University-Projects | /Python Tests/General Programming 2.py | 2,320 | 4.125 | 4 | def simplify(list1, list2):
list1_counter,list2_counter = 0,0 #This represents the integer in each array that the loop below is currently on
list3 = [] #Initialise the list
list1_length, list2_length = len(list1), len(list2) #Gets the length of both lists and stores them as varibales so they don't have to be called again and again
both_lists_checked = False #Used for While Loop, False until all integers in both arrays checked
while both_lists_checked == False:
if list1_counter <= list1_length-1: #checks if counter still in range
list1_number = list1[list1_counter] #sets current integer in each array (so that it doesn't have to be called again and again)
if list2_counter <= list2_length-1:
list2_number = list2[list2_counter]
if list1_counter>=list1_length and list2_counter>=list2_length: #Checks both lists have been fully iterated through
both_lists_checked=True #Exits loop
elif list1_counter>=list1_length: # this and the next elif checks if either list has been fully chekced
for i in range(list2_counter,list2_length): #if yes, it adds all the remaining items in the other list to the final list (but not repeats)
if not list2[i] in list3:
list3.append(list2[i])
both_lists_checked = True;
elif list2_counter>=list2_length:
for i in range(list1_counter,list1_length):
if not list1[i] in list3:
list3.append(list1[i])
both_lists_checked = True;
if list1_number==list2_number and not (list1_number in list3): #Checks if two numbers are the same and not in final list
list3.append(list1[list1_counter]) #If yes, adds it to the final list and increments the counter for both
list1_counter+=1
list2_counter+=1
elif list1_number>list2_number and not (list2_number in list3): # The next two elifs Checks if number in one list is greater than the element being analysed in the next list
list3.append(list2[list2_counter]) #if yes, adds the lesser number to the final list and increments the list where the number was found's counter
list2_counter+=1
elif list2_number>list1_number and not (list1_number in list3):
list3.append(list1[list1_counter])
list1_counter+=1
return list3
list2 = [1,2,3]
list1 = [0,1,3,4] #Simple test case, returns correct answer
final_list = simplify(list1,list2)
print(final_list) | true |
39fdd0263563f932f80ce91303ba69e74bf67259 | leilii/com404 | /1-basics/3-decision/4-modul0-operator/bot.py | 214 | 4.375 | 4 | #Read whole number UserWarning.
#work out if the number is even.
print("Please enter a number.")
wholenumber=int(input())
if (wholenumber%2 == 0):
print("The number is even")
else:
print("The number is odd")
| true |
b7d81a61e20219298907d2217469d74539b10ac4 | fwparkercode/Programming2_SP2019 | /Notes/RecursionB.py | 806 | 4.375 | 4 | # Recursion - function calling itself
def f():
print("f")
g()
def g():
print("g")
# functions can call other functions
f()
def f():
print("f")
f()
g()
def g():
print("g")
# functions can also call themselves
#f() # this causes a recursion error
# Controlling recursion with depth
def controlled(depth, max_depth):
print("Recursion depth:", depth)
if depth < max_depth:
controlled(depth + 1, max_depth)
print("Recursion depth", depth, "has closed")
controlled(0, 10)
# Factorial
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
print(factorial(1000))
def recursive_factorial(n):
if n > 1:
return n * recursive_factorial(n - 1)
else:
return n
print(recursive_factorial(1000)) | true |
21f141bbd269f85b302c1950cc0f2c8705f97854 | tejasgondaliya5/advance-python-for-me | /class_variable.py | 615 | 4.125 | 4 | class Selfdetail:
fname = "tejas" # this is class variable
def __init__(self):
self.lname = "Gondaliya"
def printdetail(self):
print("name is :", obj.fname, self.lname) # access class variable without decorator
@classmethod # access class variable with decorator
def show(cls):
print(cls.fname)
obj = Selfdetail()
obj.printdetail()
Selfdetail.show() # access calss variable outside class with decorator
print(Selfdetail.fname) # Access class variable outside only class_name.variable_name | true |
298c5f852cc317067c7dfcceb529273bbc89ec66 | tejasgondaliya5/advance-python-for-me | /Method_Overloding.py | 682 | 4.25 | 4 | '''
- Method overloding concept is does not work in python.
- But Method ovrloding in diffrent types.
- EX:- koi ek method ma different different task perform thay tene method overloading kehvay 6.
'''
class Math:
# def Sum(self, a, b, c):
def Sum(self, a = None, b=None, c=None): # this one method but perform differnt task that reason this is method overloading
if a!=None and b!=None and c!=None:
s = a+b+c
elif a!=None and b!=None:
s = a=b
else:
s = "Provide minimum two argument"
return s
obj = Math()
print(obj.Sum(10, 20, 30))
print(obj.Sum(10, 20))
print(obj.Sum(10)) | true |
08421cdc822d1ee9fb6a906927bb4836f1bc691f | YuanchengWu/coding-practice | /problems/1.4.py | 605 | 4.1875 | 4 | # Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin drome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of letters.
# The palindrome does not need to be limited to just dictionary words.
def palindrome_permutation(s):
seen = set()
counter = 0
for c in s:
if c != ' ':
if c not in seen:
seen.add(c)
counter += 1
return counter % 2 == len(''.join(s.split())) % 2
s = input('Enter string: ')
print(palindrome_permutation(s)) | true |
767b3239ad235c29906cc7f903713ac0c67712c7 | laboyd001/python-crash-course-ch7 | /pizza_toppings.py | 476 | 4.34375 | 4 | #write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you'll add that to their pizza.
prompt = "\nPlease enter the name of a topping you'd like on your pizza:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
topping = input(prompt)
if topping == 'quit':
break
else:
print("I'll add " + topping + " to your pizza!") | true |
77a0cf7be579cd67bf2f9a449d8615c682924d6f | dipeshdc/PythonNotes | /loops/for.py | 782 | 4.125 | 4 | """
For Loop
"""
sentence = "the cat sat on the mat with"# the rat cat and rat were playing in the mat and the cat was happy with rat on the mat"
'''
print("Sentence is: ",sentence)
print("Length of sentence:", len(sentence))
print("Number of Occurrences of 'cat': ", sentence.count('t')) #3
'''
count=0
for char in sentence: #foreach char inside sentence:
count = count+1 #1 2 3 4 5.....20
print(count," > ",char)
#range(start, stop[, step])
print("\n Range range(startfrom,stopat,interval)")
for num in range(1,22,2):
print("Range : ",num)
'''
for i in range(10):
print("Range : ",i)
#xrange() used for very long ranges, Python 3 handles same with range()
for i in range(5000): #xrange(5000)
if(i%100==0):
print("xRange % 100 : ",i)
'''
| true |
014db87928669d171b65f3c43c09aca9345843bc | MrLVS/PyRep | /HW5.py | 621 | 4.15625 | 4 | print("Введите неотрицательные целые числа, через пробел: ")
answer = input("--> ")
def find_min_int_out_of_string(some_string):
""" A function to find the minimum number outside the list. """
int_list = list(map(int, some_string.split()))
for i in range(1, max(int_list)+1):
if i not in int_list:
print(i)
break
elif i not in int_list and i == 1:
print(max(int_list)+1)
break
elif i == max(int_list):
print(max(int_list)+1)
break
find_min_int_out_of_string(answer)
| true |
35d0fce23734caccf4dc22ddec7175a2230b3c5d | MrLVS/PyRep | /HW10.py | 496 | 4.21875 | 4 | # Solution of the Collatz Hypothesis
def сollatz(number):
""" A function that divides a number by two if the number is even,
divides by three if the number is not even, and starts a new loop.
Counts the number of cycles until the number is exactly 1. """
i = 0
while number > 1:
if number % 2 == 0:
number = number / 2
i += 1
elif number % 2 != 0:
number = number * 3 + 1
i += 1
print(i)
Collatz(12)
| true |
4dc8fcf6c516ca8bf19c652eef0ab235aa0dc1c4 | frederatic/Python-Practice-Projects | /palindrome.py | 509 | 4.3125 | 4 | # Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
def is_palindrome(s):
if s == "": # base case
return True
else:
if s[0] == s[-1]: # check if first and last letter match
return is_palindrome(s[1:-1]) # repeat using rest
else:
return False
print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True | true |
9185f60dee9625d663bcecea816da0255507f7a3 | ukrduino/PythonElementary | /Lesson02/Exercise2_1.py | 724 | 4.65625 | 5 | # Write a recursive function that computes factorial
# In mathematics, the factorial of a non-negative integer n, denoted by n!,
# is the product of all positive integers less than or equal to n. For example,
# 5! = 5 * 4 * 3 * 2 * 1 = 120.
def factorial_rec(n):
"""
Computing factorial using recursion
>>> print factorial_rec(10)
3628800
"""
if n < 2:
return 1
else:
return n * factorial_rec(n - 1)
def factorial_loop(n):
"""
Computing factorial using loop
>>> print factorial_loop(10)
3628800
"""
fact = 1
for i in range(2, n + 1):
fact *= i
return fact
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
ec90fa2fe745ef77be5573534260e1261f3a0d87 | Anku-0101/Python_Complete | /String/03_StringFunction.py | 329 | 4.15625 | 4 | story = "once upon a time there lived a guy named ABC he was very intelliget and motivated, he has plenty of things to do"
# String Function
print(len(story))
print(story.endswith("Notes"))
print(story.count("he"))
print(story.count('a'))
print(story.capitalize())
print(story.find("ABC"))
print(story.replace("ABC", "PQR"))
| true |
1d8479254cbe4a936f1b7c21715fc58638f61f84 | Anku-0101/Python_Complete | /DataTypes/02_Operators.py | 591 | 4.15625 | 4 | a = 3
b = 4
print("The value of a + b is", a + b)
print("The value of a*b is", a * b)
print("The value of a - b is", a - b)
print("The value of a / b is", a / b)
print("The value of a % b is", a % b)
print("The value of a > b is", a > b)
print("The value of a == b is", a == b)
print("The value of a != b is", a != b)
print("The value of a < b is", a < b)
flagA = True
flagB = False
print("The value of flagA and flagB is", flagA and flagB)
print("The value of flagA or flagB is", flagA or flagB)
print("The value of not flagB is", not flagB)
print("The value of not flagA is", not flagA) | true |
05f486e4dac5d903bd5ec01c15c0835caa59a8b2 | Weenz/software-QA-hw2 | /bmiCalc.py | 1,631 | 4.3125 | 4 | import math
#BMI Calculator function
def bmiCalc():
print ("")
print ("BMI Calculator")
print ("------------------")
#Loop to verify integer as input for feet
while True:
try:
feet = int(input("Enter your feet part of your height: "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
#Loop to verify integer as input for inches
while True:
try:
inches = int(input("Enter the inches part of your height: "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
#Loop to verify integer as input for weight
while True:
try:
weight = int(input("Enter your weight (in pounds): "))
except ValueError:
print("Incorrect value, must be a number.")
continue
else:
break
weight = weight * 0.45 #metric conversion
height = feet * 12 + inches #total height in inches
height = height * 0.025 #metric conversion
height = height * height #square height
bmi = weight / height #bmi calculation
bmi = math.ceil(bmi * 10) / 10 #keep one decimal place
if (bmi <= 18.5):
value = "Underweight"
elif ( (bmi > 18.5) and (bmi <= 24.9) ):
value = "Normal Weight"
elif( (bmi >= 25) and (bmi <= 29.9) ):
value = "Overweight"
else:
value = "Obese"
return (bmi, value) | true |
12491cc31c5021a38cb40799492171c2d5b6b978 | muneel/url_redirector | /redirector.py | 2,194 | 4.25 | 4 | """
URL Redirection
Summary:
Sends the HTTP header response based on the code received.
Converts the URL received into Location in the response.
Example:
$ curl -i http://127.0.0.1:5000/301/http://www.google.com
HTTP/1.0 301 Moved Permanently
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:11 GMT
Location: http://www.google.com
$ curl -i http://127.0.0.1:5000/302/http://www.google.com
HTTP/1.0 302 Found
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:17 GMT
Location: http://www.google.com
$ curl -i http://127.0.0.1:5000/303/http://www.google.com
HTTP/1.0 303 See Other
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:22 GMT
Location: http://www.google.com
"""
import BaseHTTPServer
import time
import sys
HOST_NAME = ''
PORT_NUMBER = 5000
class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
"""Sends only headers when HEAD is requested
Args:
None:
Returns:
None
"""
s.end_headers()
def do_GET(s):
"""GET request from getting URL Redirection with return status code
Args:
None
Returns:
None
"""
print s.path
try:
temp = str(s.path)
code = int(temp[1:4])
url = temp[5:]
if code in (301, 302, 303, 307):
s.__send_redirect(code, url)
else:
s.send_response(400)
s.end_headers()
except:
s.send_response(400)
s.end_headers()
def __send_redirect(s, code, url):
s.send_response(code)
s.send_header("Location", url)
s.end_headers()
if __name__ == '__main__':
if len(sys.argv) == 2:
PORT_NUMBER = int(sys.argv[1])
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), RedirectHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
| true |
94c39abb57532962ca90b9df933800cfa6d1b3b3 | AswinT22/Code | /Daily/Vowel Recognition.py | 522 | 4.1875 | 4 |
# https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
def count_vowel(string,):
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
count = 0
length=len(string)
for i in range(0, length):
if(string[i] in vowel):
number=(length-i)
count += (number+(number*(i)))
return count
for _ in range(int(input())):
string = input()
print(count_vowel(string))
| true |
d9816ac73df50f5676313824859a15b10485a7c4 | affreen/Python | /pyt-14.py | 511 | 4.28125 | 4 | """demo - script that converts a number into an alphabet and then
determines whether it is an uppercase or lowercase vowel or consonant"""
print("Enter a digit:")
var=input()
var=int(var)
new_var=chr(var)
#if(new_var>=97 and new_var<=122):
if (new_var in ['a','e','i','o','u']):
print("You have entered a lowercase vowel:", new_var)
elif(new_var in ['A','E','I','O','U']):
print("You have entered an uppercase vowel:", new_var)
else:
print("You have entered a consonant:", new_var)
| true |
f33786d90ed22092a69a7114e274fd8610c4d278 | admcghee23/RoboticsFall2019GSU | /multiCpuTest.py | 2,198 | 4.3125 | 4 | #!/usr/bin/env python
'''
multiCpuTest.py - Application to demonstrate the use of a processor's multiple CPUs.
This capability is very handy when a robot needs more processor power, and has processing elements
that can be cleaved off to another CPU, and work in parallel with the main application.
https://docs.python.org/2/library/multiprocessing.html describes the many ways the application parts
can communicate, beyond this simple example
Copyright (C) 2017 Rolly Noel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
from multiprocessing import cpu_count, Process, Value, Array
import time
secondCpuToRun = Value('i', False) #Shared memory designation for an integer
timeLastSaw = Value('d', 0.) #Shared memory designation for a decimal number
def watchTheTime(timeLastSaw): #THIS FUNCTION RUNS ON ITS OWN CPU
print()
while secondCpuToRun.value:
now = time
timeLastSaw.value = time.time() #
print('2nd CPU reporting the time: %d' % timeLastSaw.value)
time.sleep(5) #Sleep for 5 seconds
print('Second CPU task shutting down')
if __name__ == '__main__':
print("System has %d CPUs" % cpu_count())
secondCpuToRun.value = True
proc = Process(target=watchTheTime, args=(timeLastSaw,)) #Consume another cpu - TRAILING COMMA NEEDED
proc.daemon = True
proc.start()
x = raw_input("Hit Enter to shut 2nd CPU down") #This CPU is blocked till user hits Enter
secondCpuToRun.value = False #Tell second CPU process to shut down
time.sleep(1) #Give it a chance
print("Last time 2nd CPU captured was %d" % timeLastSaw.value) #Show work 2nd CPU did
| true |
7fb846cef384bf05421502c4602add3a30f2c889 | mahespunshi/Juniper-Fundamentals | /Comprehensions.py | 1,006 | 4.53125 | 5 | # List comprehension example below. notes [] parenthesis. Comprehensions can't be used for tuple.
x =[x for x in range(10)]
print(x)
# create comprehension and it can creates for us, but in dict we need to create it first and then modify it.
# so, we can't create auto-dict, we can just modify dict, unlike list.
# Dictionary comprehension is implement after list comprehension
# Keys should be unique in dict, guess keys are tuples ()
dict1 = {'a': 5, 'b': 10, 'c': 15}
triple = {k:v**3 for (k,v) in dict1.items()}
print(triple)
triple = {k:v**3 for (k,v) in {'a': 3, 'b': 6}.items()}
print(triple)
# in dict, keys should be any immutable type tuple,set, so number or letters both are fine.
# read cha 1,
# Use enumerate in list or string when you want to store index values instead of using while loop with i counter
city = 'Boston'
for index, char in enumerate(city):
print(index, char)
# or using while loop instead of enumerate
i = 0
while i < len(city):
print(i, city[i])
i = i + 1
| true |
19e0975c0f0f0df045b2c1a1e6ff13ad97a3aee6 | BaDMaN90/COM404 | /Assessment_1/Q7functions.py | 1,429 | 4.3125 | 4 | #file function have 4 functions that will do a cool print play
#this function will print piramids on the left of the face
def left(emoji):
print("/\/\/\\",emoji)
#this function will print piramids on the right of the face
def right(emoji):
print(emoji,"/\/\/\\")
#this function will print face between piramids
def both(emoji):
print("/\/\/\\",emoji,"/\/\/\\")
#this function will creat the grid of faces betweein piramids
#size of the grid will depend on the deifined size by the user
def grid(emoji,grid_size):
#2 loops will helo to create a nice grid
#first loop will define the height of the grid f.e. grid_size = 3 means that loop will creat 3 rows
#second loop will print the correct patternt in the raw
for x in range(grid_size):
for operator in range(-1,grid_size):
#operator range is from -1 to grid_size
#program will print piramids followed by face only on the first print. this will make sure that if grid size is 1 then the print still work.
#else the program will print 5 piramids followed by a face
if operator <= -1 or operator == grid_size-1:
print("/\/\/\\ ", end ="")
if operator != grid_size-1:
print(emoji,"", end='')
operator +=1
else:
print("/\/\/\/\/\\",emoji,"", end ="")
operator +=1
print("")
| true |
3f7d577aacbb73da5406b3676fb12d9947c98e51 | BaDMaN90/COM404 | /Basic/4-repetition/1-while-loop/2-count/bot.py | 684 | 4.125 | 4 | #-- importing the time will allow the time delay in the code
#-- progtram will print out the message and ask for input
#-- 2 variables are created to run in the while loop to count down the avoided live cables and count up how many have avoided
import time
print("Oh no, you are tangle up in these cables :(, how many live cables are you wrpped in?")
no_cables = int(input())
live_cable = 1
#-- while loop will run as long as no_cables are different then 0
while no_cables !=0:
print("Avoiding...")
no_cables = no_cables - 1
time.sleep(1)
print(str(live_cable) + " live cable avoided")
live_cable = live_cable + 1
time.sleep(1)
print("All live cable avoided") | true |
5996714a292cf5902cefb2830c497c7d81959b54 | RPadilla3/python-practice | /python-practice/py-practice/greeter.py | 407 | 4.1875 | 4 | prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\n Hello, " + name + "!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
| true |
5d10bf344a26b484e373e93cd734b9c405d3076c | rexrony/Python-Assignment | /Assignment 4.py | 2,548 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#Question 1
firstname = input("Your First Name Please ");
lastname = input("Your Last Name Please ");
age = int(input("Your Age Please "));
city = input("Your City Please ");
userdata = {
'first_name': firstname,
'last_name': lastname,
'age': age,
'city': city,
}
print("\n----------------\n")
print(userdata['first_name'])
print(userdata['last_name'])
print(userdata['age'])
print(userdata['city'])
# In[3]:
#Question 2
dubai = {
'country': 'UAE',
'population': '3.137 million',
'fact': 'The total population of Dubai is 3.1 million. Arabic is the official language. The currency is UAE dirham (AED).',
}
karachi = {
'country': 'PAKISTAN',
'population': '14.91 million',
'fact': 'In 1729, real settlements were founded, and it was named Kolachi after the name of an old woman, Mai Kolachi (Auntie Kolachi). She was the head of a village and was known for her fair decisions. However, there are many other tales about this city’s former name ‘Kolachi.’',
}
Mumbai = {
'country': 'INDIA',
'population': '13 million',
'fact': 'Every day in Mumbai, more than 200 trains make over 2,000 trips along 300 kilometres of track, carrying more passengers per kilometre than any railway on earth.',
}
#for key, value in Mumbai.items():
# print(key, "=", value)
print("DUBAI");
for key, value in dubai.items():
print(key, "=", value)
print("\n----------------\n")
print("PAKISTAN");
for key, value in karachi.items():
print(key, "=", value)
print("\n----------------\n")
print("Mumbai");
for key, value in Mumbai.items():
print(key, "=", value)
# In[1]:
#Question 3
ask_age = "How old are you?"
ask_age += "\nType 'end' when you are finished adding age. "
while True:
age = input(ask_age)
if age == 'end':
break
age = int(age)
if age < 18:
print(" You get in free!")
elif age <= 19:
print(" Your ticket is $10.")
else:
print(" Your ticket is $15.")
# In[2]:
#Question 4
def favorite_book(title):
print(title + " is one of my favorite books.");
fvrt_book = input("Enter your Favorite Book Name : ");
favorite_book(fvrt_book)
# In[2]:
#Question 5
import random
it=random.randint(1, 30)
def main():
x=int(input('Guess a number between 1 and 30 = '))
if x == it:
print("You got it!")
elif x > it:
print("too high")
main()
else:
print("too low")
main()
main()
# In[ ]:
# In[ ]:
| true |
8536c9d42de73a7e2b426c38df271740c51f79e2 | HarshHC/DataStructures | /Stack.py | 1,819 | 4.28125 | 4 | # Implementing stack using a linked list
# Node Class
class Node(object):
# Initialize node with value
def __init__(self, value):
self.value = value
self.next = None
# Stack Class
class Stack(object):
# Initializing stack with head value and setting default size to 1
def __init__(self, head=None):
self.head = head
if head:
self.size = 1
else:
self.size = 0
# Function to print the entire stack as string
def printStack(self):
current = self.head
while current:
print(str(current.value) + " -> ", end="")
current = current.next
print(str(current))
# Function to get current size of the stack
def getSize(self):
return self.size
# Function to check if the stack is empty
def isEmpty(self):
return self.size == 0
# Function to get the top item in the stack
def peek(self):
if self.isEmpty():
raise Exception("Peeking from an empty stack")
print(self.head.value)
# function to add an item to the top of the stack
def push(self, item):
item.next = self.head
self.head = item
self.size+=1
# function to remove an item from the top of the stack
def pop(self):
if self.isEmpty():
raise Exception("Popping from an empty stack")
self.head = self.head.next
self.size-=1
# Create a Stack
stack = Stack()
# Print current stack size
print(stack.getSize())
# Push Data to the top
stack.push(Node('head'))
stack.push(Node(1))
stack.push(Node(2))
stack.push(Node(3))
stack.push(Node(4))
stack.push(Node(5))
# Display the stack
stack.printStack()
# Pop Data from the top
stack.pop()
stack.printStack()
# Peek top item
stack.peek() | true |
dec63d4f99825d1934be4b81836d5a3728b8038e | DKanyana/Code-Practice | /ZerosAndOnes.py | 372 | 4.25 | 4 | """
Given an array of one's and zero's convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
"""
def binary_array_to_number(arr):
binNum = 0
for cnt,num in enumerate(arr):
binNum += num * (2 ** (len(arr)-1-cnt))
return binNum
print(binary_array_to_number([0,0,1,0]))
| true |
67588905fa64b3e7efa93541b569769688d1600f | krrish12/pythonCourse | /Day-4/DecisionMaking.py | 1,578 | 4.125 | 4 | var,var1 = 100,110
if ( var == 100 ) : print("Value of expression is 100 by Comparison operator")
#output: Value of expression is 100
if ( var == 10 ): print("Value of expression is 10 by Comparison operator")
elif(var1 == 50): print("Value of expression is 50 by Comparison operator")
else:print("Value of expression is 110 by Comparison operator")
#output: Value of expression is 100
if ( var or var1 ) : print("Result of expression is True by Logical operator")
#output: Result of expression is True by Logical operator
if ( var and var1 ) : print("Result of expression is False by Logical operator")
#output: Result of expression is False by Logical operator
if (not(var and var1)) : print("Result of expression is False by Logical operator")
else: print("Result of expression is True by Logical operator")
#output: Result of expression is True by Logical operator
if(var is 100): print("Value of expression is 100 by identity operator")
#output Value of expression is 100
if(var is not 100): print("Value of expression is 100 by identity operator")
else: print("Value of expression is 100 by identity operator by else ")
#output Value of expression is 100 by identity operator by else
obj,obj1 = 2,[1,2,10]
if(obj in obj1): print("Value of expression is 100 by membership operator")
#output Value of expression is 100 by membership operator
if(obj not in obj1): print("Value of expression is 100 by membership operator")
else :print("Value of expression is 100 by membership operator by else")
#output Value of expression is 100 by membership operator by else
| true |
56af4680b7f68a43096c0c8d8a9d81a318b3ceea | Tom0497/BCS_fuzzy | /src/FuzzyFact.py | 2,097 | 4.46875 | 4 | class FuzzyFact:
"""
A class to represent a fuzzy fact, i.e. a fact or statement with a value of certainty in the range [-1, 1],
where -1 means that the fact is a 100% not true, whereas a value of 1 means that the fact is a 100% true,
finally, a value of 0 means ignorance or lack of knowledge in terms of the fact or statement considered.
In specific, this application considers facts or statements about animals, therefore, the facts must match
one of these next formats:
* el animal tiene [attribute]
* el animal es [adjective]
Where both of these sentences are in spanish, and so must the objects created be.
"""
def __init__(self, obj: str, atr: str, val: str, cv: float = 0):
"""
Creates a new FuzzyFact object, from a fact or statement in the form of a three-part
sentence whose parts are:
* object
* attribute
* value
Also, a certainty value can be assigned to the object as specified before.
:param obj: the object of the sentence
:param atr: the attribute in the sentence
:param val: the value in the sentence
:param cv: the certainty value, a float in the range [-1, 1], default value is 0
"""
self.obj: str = obj
self.atr: str = atr
self.val: str = val
self.cv: float = 0.0
self.assign_cv(cv)
def assign_cv(self, cv: float):
"""
Assigns the certainty value to the FuzzyFact object. It makes sure the value is in the range [-1, 1]
"""
assert -1 <= cv <= 1, 'Certainty value is not in the range [-1, 1]'
self.cv: float = cv
def __repr__(self):
"""
Put the object together for printing.
Magic method for print(object) command.
"""
sentence = ' '.join([self.obj, self.atr, self.val])
sentence = f'(({sentence}) {self.cv})'
return sentence
if __name__ == "__main__":
fact1 = FuzzyFact('el animal', 'tiene', 'pelo')
fact1.assign_cv(0.9)
print(fact1)
| true |
6048b803d984e8837f31aaa7c31667e396f4b0b0 | yogesh1234567890/insight_python_assignment | /completed/Data3.py | 384 | 4.21875 | 4 | '''3. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t' '''
user=input("Enter a word: ")
def replace_fun(val):
char=val[0]
val=val.replace(char,'$')
val=char + val[1:]
return val
print(replace_fun(user)) | true |
12d6c22a4cdacef7609f965d1f682213f06d25d1 | yogesh1234567890/insight_python_assignment | /completed/Data22.py | 267 | 4.1875 | 4 | #22. Write a Python program to remove duplicates from a list.
mylist=[1,2,3,4,5,4,3,2]
mylist = list(dict.fromkeys(mylist))
print(mylist)
##here the list is converted into dictionaries by which all duplicates are removed and its well again converted back to list | true |
c0874441b6ae538e3be713d71015ec626f04272f | yogesh1234567890/insight_python_assignment | /functions/Func14.py | 498 | 4.4375 | 4 | #14. Write a Python program to sort a list of dictionaries using Lambda.
models = [{'name':'yogesh', 'age':19, 'sex':'male'},{'name':'Rahsit', 'age':70, 'sex':'male'}, {'name':'Kim', 'age':29, 'sex':'female'},]
print("Original list:")
print(models)
sorted_models = sorted(models, key = lambda x: x['name'])
print("\nSorting the List on name basis::")
print(sorted_models)
sorted_models = sorted(models, key = lambda x: x['age'])
print("\nSorting the List on age basis::")
print(sorted_models)
| true |
93705ba1b2d202737fa5f9f9852ed9814f768eb4 | yogesh1234567890/insight_python_assignment | /functions/Func5.py | 313 | 4.40625 | 4 | """ 5. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument. """
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n=int(input("Insert a number to calculate the factiorial : "))
print(fact(n)) | true |
7d701dbeb4a04cda556c0bc2da03de589a1d26e9 | yogesh1234567890/insight_python_assignment | /completed/Data39.py | 206 | 4.1875 | 4 | #39. Write a Python program to unpack a tuple in several variables.
a = ("hello", 5000, "insight")
#here unpacking is done
(greet, number, academy) = a
print(greet)
print(number)
print(academy)
| true |
93d2d0026b5d737c60049229091c9c01faedf0f0 | yogesh1234567890/insight_python_assignment | /functions/Func7.py | 666 | 4.25 | 4 | """ 7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12 """
string="The quick Brow Fox"
def check(string):
upper=0
lower=0
for i in range(len(string)):
if ord(string[i])>=97 and ord(string[i])<=122:
lower+=1
else:
if ord(string[i])==32:
continue
upper+=1
print("No. of Upper case characters: "+str(upper))
print("No. of Lower case characters: "+str(lower))
check(string) | true |
45c4e66f0dba9851ea5539d2c98e6076ed1ad8fd | sk-ip/coding_challenges | /December_2018/stopwatch.py | 734 | 4.125 | 4 | # program for stopwatch in python
from datetime import date, datetime
def stopwatch():
ch=0
while True:
print('stopwatch')
print('1. start')
print('2. stop')
print('3. show time')
print('4. exit')
ch=input('enter your choice:')
if ch=='1':
start=datetime.now()
print('time started at',start)
elif ch=='2':
stop=datetime.now()
print('time stopped at',stop)
elif ch=='3':
time_taken=start-stop
print('your timing is:',divmod(time_taken.days * 86400 + time_taken.seconds, 60))
else:
print('exiting')
exit()
if __name__=="__main__":
stopwatch()
| true |
9f34a088a4d0a61f2af65fa911222eb2d3372dd8 | mbramson/Euler | /python/problem016/problem016.py | 488 | 4.125 | 4 | # -*- coding: utf-8 -*-
## Power Sums
## 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
## What is the sum of the digits of the number 2**1000?
## This is actually a very simple problem in python, because Python automatically deals with large numbers.
## Returns the Power Sum of n. As in it sums the digits of 2^n
def PowerSum(n):
sumstring = str(2**n)
total = 0
for s in sumstring:
total += int(s)
return total
print(PowerSum(1000)) | true |
a4382447caa1d2c2e4bfd9ddedef88a7063bf943 | valerienierenberg/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,421 | 4.1875 | 4 | #!/usr/bin/python3
"""This module contains a function island_perimeter that returns
the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""island_perimeter function
Args:
grid ([list of a list of ints]):
0 represents a water zone
1 represents a land zone
One cell is a square w/ side length 1
Grid cells are connected horiz/vertically (not diagonally).
Grid is rectangular, width and height don’t exceed 100
The island is one contiguous land mass
"""
perim = 0
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1: # value is 1 at that cell
if row == 0 or grid[row - 1][col] == 0:
# outer rows always 0s, OR one cell above it is 0
perim += 1
if col == 0 or grid[row][col - 1] == 0:
# outer cols always 0s, OR one cell to the left is 0
perim += 1
if row == len(grid) - 1 or grid[row + 1][col] == 0:
# if row is one above bottom OR value below curr pos. is 0
perim += 1
if col == len(grid) - 1 or grid[row][col + 1] == 0:
# col is one to left of end OR value left of curr pos. is 0
perim += 1
return perim
| true |
74a62d228dbd2ce456d09211bea6f15d822ca3f7 | James-E-Sullivan/BU-MET-CS300 | /sullivan_james_lab3.py | 2,052 | 4.25 | 4 | # Eliza300
# Intent: A list of helpful actions that a troubled person could take. Build 1
possible_actions = ['taking up yoga.', 'sleeping eight hours a night.',
'relaxing.', 'not working on weekends.',
'spending two hours a day with friends.']
'''
Precondition: possible_actions is the list defined above
Postconditions:
1. (Welcome): A welcome message is on the console
2. (user_complaint): user_complaint is the user's response to a prompt for the
user's complaint
3. (how_long): how_long is the user's string response to "How many months have
you experience ...?" AND Eliza300 sympathized, mentioning duration
4. (Advice):
EITHER how_long < 3 AND "Please return in * months" is on the console where *
is 3-how_long
OR how_long >= 3 AND The phrases in possible_actions are on separate lines
on the console, each preceded by "Try ".
'''
# Welcome message from Eliza300 is printed on the console
print("Thank you for using Eliza300, a fun therapy program.")
# User prompted to input their emotional complaint
# User complaint stored as string in variable 'user_complaint'
print("Please describe your emotional complaint--in one punctuation-free line:")
user_complaint = input()
# User prompted to input number of months they have experienced their complaint
# User input stored as string in variable 'how_long'
print("How many months have you experienced '" + user_complaint + "'?")
how_long = input()
# Eliza300 sympathetic response, mentioning during, printed to console
print(how_long + " months is significant. Sorry to hear it.")
# Eliza advice, which is dependent on value of how_long, printed to console
# If how_long < 3, Eliza suggests user comes back when how_long is 3
# Otherwise, Eliza provides suggestions from list of possible_actions
if int(how_long) < 3:
print("Please return in " + str(3 - int(how_long)) + " months.")
else:
for possible_actions_index in range(5):
print("Try " + possible_actions[possible_actions_index])
| true |
91e5fa35bc4ea64c7cc65e096d10ed0d91d8d88b | bperard/PDX-Code-Guild | /python/lab04-grading.py | 320 | 4.125 | 4 | score = int(input('On a scale of 0-100, how well did you?'))
grade = ''
if score > 100:
grade = 'Overachiever'
elif score > 89:
grade = 'A'
elif score > 79:
grade = 'B'
elif score > 69:
grade = 'C'
elif score > 59:
grade = 'D'
elif score >= 0:
grade = 'F'
else:
grade = 'Leave'
print(grade)
| true |
21ab8c793589afe2c8f984db02ca2b5650be962b | bperard/PDX-Code-Guild | /python/lab08-roshambo.py | 1,309 | 4.25 | 4 | '''
Rock, paper, scissors against the computer
'''
import random
throws = ['rock', 'paper', 'scissors'] #comp choices
comp = random.choice(throws)
player = input('Think you can beat me in a game of Roshambo? I doubt it, but let\'s give it a shot.\n Choose your weapon: paper, rock, scissor.').lower() #player prompt
while player == comp: #check for tie, and replay
player = input('It\'s a tie, we can\'t end without a loser. Type "done," or throw again.').lower()
comp = random.choice(throws)
if player == 'done':
break
# rock outcome
if player == 'rock':
if comp == 'scissors':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# scissors outcome
elif player == 'scissors':
if comp == 'paper':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# paper outcome
elif player == 'paper':
if comp == 'rock':
print('You must be very proud of yourself, you win.')
else:
print('Computers are the future, this is just the beginning; you lose.')
# horrible person outcome
else:
print('There were three choices... how did you mess that up; you lose.')
| true |
75566c13a5e09874a1ea4ff64c7f198b7f4218fc | bperard/PDX-Code-Guild | /python/lab31-atm.py | 2,865 | 4.21875 | 4 | '''
lab 31 - automatic teller machine machine
'''
transactions = [] # list of deposit/withdraw transactions
class ATM: # atm class with rate and balance attribute defaults set
def __init__(self, balance = 0, rate = 0.1):
self.bal = balance
self.rat = rate
def __str__(self): # format when returned as a string
return 'BAL=' + str(self.bal) + '\nRAT=' + str(self.rat)
def check_balance(self): # return balance attribute
return self.bal
def deposit(self, amount): # add deposit parameter to ATM balance attribute, add transaction to list
self.bal += amount
transactions.append('User deposited $' + str(amount))
def check_withdrawal(self, amount): # return True if balance greater than amount parameter
return self.bal - amount >= 0
def withdraw(self, amount): # subtract parameter amount from balance attribute, add transaction, and return amount
self.bal -= amount
transactions.append('User withdrew $' + str(amount) + '\n')
return amount
def calc_interest(self): # return interest rate
return self.rat
def print_transactions(self): # print transaction history in separate lines
for lines in transactions:
print(lines)
print('Welcome, I am an ATM, feed me money!\n' # intro and user input stored in teller variable
'Just kidding, that was my humor function, hopefully I haven\'t offended you.\n'
'Now that you are done laughing, what would you like to do?\n'
'Enter "done" at any time to exit your account.')
teller = input('Choose "deposit", "withdraw", check "balance", and "history":')
account = ATM() # account variable initialized as ATM type
while teller != 'done': # while loop until teller == 'done'
if teller.lower() == 'deposit': # user input amount, call deposit function
amount = int(input('Enter how much you would like to deposit: $'))
account.deposit(amount)
elif teller.lower() == 'withdraw': # user input amount, call check_withdraw, call withdraw if True, notify user if False
amount = int(input('Enter how much you would like to withdraw: $'))
if account.check_withdrawal(amount):
account.withdraw(amount)
else:
print('Can\'t withdraw $' + str(amount) + ', balance is $' + str(account.bal) + '.')
elif teller.lower() == 'balance': # show user balance
print('Your balance is $' + str(account.bal) + '.')
elif teller.lower() == 'history': # call print_transactions
account.print_transactions()
if teller != 'done': # ask user for new mode
teller = input('Choose "deposit", "withdraw", check "balance", and "history":')
print('Work to live, don\'t live to work... okay, goodbye.') # pass knowledge and love to user | true |
e5a8eae58dc45a0259309b867eeac974b3dc7d62 | bperard/PDX-Code-Guild | /python/lab09-change.py | 838 | 4.25 | 4 | '''
Making change
'''
# declaring coin values
quarters = 25
dimes = 10
nickles = 5
pennies = 1
# user input, converted to float
change = float(input('Giving proper change is key to getting ahead in this crazy world.\n'
'How much money do you have? (for accurate results, use #.## format)'))
# convert float to int for math
change = int(change * 100)
# proper coinage math
#first line determins amount, second passes remaining change forward
quarters = int(change // quarters)
change -= quarters * 25
dimes = int(change // dimes)
change -= dimes * 10
nickles = int(change // nickles)
change -= nickles * 5
pennies = int(change // pennies)
# print proper coinage
print('Proper change is: ' + str(quarters) + ' quarters, ' + str(dimes) + ' dimes, ' + str(nickles) + ' nickles, and ' + str(pennies) + ' pennies.')
| true |
07de036683eeaf643caaa7e140c8959af82703e7 | RobertCochran/connect4 | /user_input.py | 1,148 | 4.25 | 4 | import random
def user_input():
""" This function allows the user to choose where their red piece goes. """
print "We're going to play Connect Four."
print " I'll be black and you'll be red. "
print "You go first and choose where you want to put your piece. There are seven columns in total."
valid_move = False
while not valid_move:
col = input(" Choose a column to put your piece in (1-7): ")
for row in range (6,0,-1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row-1][col-1] == "."):
board[row-1][col-1] = 'r'
valid_move = True
break
else:
print "Error, please restart game and try again."
def computer_choice():
""" this function has the computer randomly choose where it will set its
piece """
valid_move = False
while not valid_move:
row = random.randint(0,6)
col = random.randint(0,7)
for row in range (6,0,-1):
if board[row][col] == ".":
board[row][colum] == "b"
valid_move = True
break
| true |
eb7cb4ffdec2e4c5790db0c1d1b407ed5b8a2930 | galgodon/astr-119-hw-1 | /operators.py | 1,641 | 4.5 | 4 | #!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation (to the power of)
x = 9.191823 # Make x into a complicated float to show the effect of floor division
print(x//y) # Floor Division (divide but get rid of the decimal will ALWAYS round down)
# how many whole times does y go into x
# Assignment Operators
x = 9 # set x back to 9. Single equal ASSIGNS the value. Double equals is boolean
x += 3 # take the previous value of x and add 3. So x is now 12
print(x)
x = 9 # set x back to 9.
x -= 3 # take the previous value of x and subtract 3. So x is now 6
print(x)
x = 9 # set x back to 9
x *= 3 # take the previous value of x and multiply by 3. x = 27
print(x)
x = 9 # set x back to 9
x /= 3 # take the previous value of x and divide 3. x = 3
print(x)
x = 9 # set x back to 9
x **= 3 # take the previous value of x and put it to the power of 3. x = 9^3
print(x)
# Comparison Operators - Booleans
x = 9
y = 3
print(x==y) # is x the same as y? In this case False
print(x!=y) # is x different than y? In this case True
print(x>y) # is x greater than y? In this case True
print(x<y) # is x less than y? In this case False
print(x>=y) # is x greater than or equal to y? In this case True
print(x<=y) # is x less than or equal to y? In this case False | true |
9bdfa82561a8638beb7caa171e52f717cc3bb89e | galgodon/astr-119-hw-1 | /functions.py | 1,209 | 4.1875 | 4 | #!/usr/bin/env python3
import numpy as np # import numpy and sys
import sys
def expo(x): # define a function named expo that needs one input x
return np.exp(x) # the function will return e^x
def show_expo(n): # define a subroutine (does not return a value)
# n needs to be an integer
for i in range(n): # loop i values from 0 to n
print(expo(float(i))) # call the expo function. also convert i to a
# float to be safe
def main(): # define main function, no input needed
n = 10 # provide a default value for n
if (len(sys.argv)>1): # sys.argv is the command line arguements.
n = int(sys.argv[1]) # if a command line arguement is provided, use it for n
# in cmd: python3 functions.py [insert argv here]
show_expo(n) # call the show_expo subroutine with the input n
# if there are no command line arguements, n is the default 10
if __name__ == '__main__': # run the main() function
main() | true |
3ad1a7fcb0a7b6d2c7ba0e1f639d396c6adf6fe7 | Peter-Moldenhauer/Python-For-Fun | /If Statements/main.py | 502 | 4.3125 | 4 | # Name: Peter Moldenhauer
# Date: 1/12/17
# Description: This program demonstrates if statements in Python - if, elif, else
# Example 1:
age = 12
if age < 21:
print("Too young to buy beer!")
# Example 2:
name = "Rachel"
if name is "Peter": # you can use the keword is to compare strings (and also numbers), it means ==
print("Hello Peter!")
elif name is "Rachel":
print("Good afternoon Rachel")
elif name is "Bob":
print("Yo Bob what up!")
else:
print("Um I don't know your name!")
| true |
26cdf3876507195bf2db3deb50b2bee7eb316483 | JatinBumbra/neural-networks | /2_neuron_layer.py | 1,059 | 4.15625 | 4 | '''
SIMPLE NEURON LAYER:
This example is a demonstration of a single neuron layer composed of 3 neurons. Each neuron has it's own weights that it
assigns to its inputs, and the neuron itself has a bias. Based on these values, each neuron operates on the input vector
and produces the output.
The below program demonstrates the ouput of a layer.
NOTE: This example does not combine the result into a single value, like the final output layer which has one
output(in simplest case)
'''
inputs = [1, 2, 3, 2.5]
weights1 = [0.2, 0.8, -0.5, 1.0]
weights2 = [0.5, -0.91, 0.26, -0.5]
weights3 = [-0.26, -0.27, 0.17, 0.87]
bias1 = 2
bias2 = 3
bias3 = 0.5
output = [inputs[0]*weights1[0] + inputs[1] * weights1[1] + inputs[2]*weights1[2] + inputs[3]*weights1[3] + bias1,
inputs[0]*weights2[0] + inputs[1] * weights2[1] +
inputs[2]*weights2[2] + inputs[3]*weights2[3] + bias2,
inputs[0]*weights3[0] + inputs[1] * weights3[1] + inputs[2]*weights3[2] + inputs[3]*weights3[3] + bias3, ]
print(output) | true |
d8fb565e7a39ebb7a200514407b2ffb49e07b19d | adharmad/project-euler | /python/commonutils.py | 2,794 | 4.34375 | 4 | import functools
from math import sqrt
@functools.lru_cache(maxsize=128, typed=False)
def isPrime(n):
"""
Checks if the number is prime
"""
# Return false if numbers are less than 2
if n < 2:
return False
# 2 is smallest prime
if n == 2:
return True
# All even numbers are not prime
if not n & 1:
return False
# Now start at 3, go upto the square root of the number and check
# for divisibility. Do this in steps of two so that we consider
# only odd numbers
for i in range(3, int(n**0.5)+1, 2):
if n%i == 0:
return False
# number is prime
return True
def getPrimeFactors(n):
"""
Return a list having the prime factors of the number including the
number itself
"""
factors = []
for i in range(n+1):
if isPrime(i) and n%i == 0:
factors.append(i)
return factors
def getAllFactors(n):
"""
Return a list having all the factors of a number
"""
factors = []
for i in range(n+1):
if isPrime(i) and n%i == 0:
tmpnum = n
while tmpnum % i == 0:
factors.append(i)
tmpnum = tmpnum / i
return factors
def getAllFactorsWithCount(n):
"""
Return a map having the prime factors of the number and the number
of times the prime factor can divide the number
"""
allFactors = {}
factors = getPrimeFactors(n)
for f in factors:
tmpnum = n
count = 0
while tmpnum % f == 0:
tmpnum = tmpnum / f
count += 1
allFactors[f] = count
return allFactors
def isPalindrome(s):
"""
Checks if the given string is a palindrome and returns true
"""
i = 0
j = len(s) - 1
while i < j:
if s[i] == s[j]:
i += 1
j -= 1
continue
else:
return False
return True
def listToDictWithCount(lst):
"""
Convert a list of elements into a dictionary with the values
being the number of times the element occurs in the list.
For example,
[1, 2, 2, 3, 3, 3, 4, 4]
will return
{1:1, 2:2, 3:3, 4:2}
"""
retDict = {}
for elem in lst:
if elem in retDict.keys():
retDict[elem] = retDict[elem] +1
else:
retDict[elem] = 1
return retDict
def isPythagoreanTriplet(a, b, c):
x = [a, b, c]
x.sort()
if x[0]*x[0] + x[1]*x[1] == x[2]*x[2]:
return True
return False
def getAllDivisors(num):
"""
Returns a list having all the divisors of a number, including 1
"""
div = []
for i in range(1, int(num/2)):
if num % i == 0:
div.append(i)
return div
| true |
779d06833f0b30281c71242196a77f9ff08ce094 | abhay-rana/python-tutorials. | /DATA STRUCTURE AND ALGORITHMS/INSERRTION_ SORT.py | 397 | 4.15625 | 4 | #INSERTION SORT IS SIMILAR TO E WE PLAYING CARDS
# THE WAY WE SORT THE CARDS
def insertion_sort(arr):
for e in range(1,len(arr)):
temp=arr[e]
j=e-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j] # we are forwarding the elements
j=j-1
else:
arr[j+1]=temp
return arr
arr=[40,55,33,20,35,1,5]
print(insertion_sort(arr)) | true |
6cc03c6e49891cacfa4ff2824caf9718994e1811 | Avinint/Python_musicfiles | /timeitchallenge.py | 1,006 | 4.375 | 4 | # In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number of iterations to 1,000 or 10,000. The default
# of one million will take a long time to run.
import timeit
from statistics import mean, stdev
def fact(n):
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result
def factorial(n):
# n! can also be defined as n * (n-1)!
if n <= 1:
return 1
else:
return n * factorial(n-1)
res = timeit.repeat("fact(200)", setup="from __main__ import fact", number=1000, repeat=6)
res2 = timeit.repeat("factorial(200)", setup="from __main__ import factorial", number=1000, repeat=6)
print(f"Iterative: {mean(res)} {stdev(res)}")
print(f"Recursive: {mean(res2)} {stdev(res2)}")
| true |
f348334cc86f5d86e66be05fa2aaaab5da2460c6 | cyrus-raitava/SOFTENG_364 | /ASSIGNMENT_2/SOLUTIONS/checksum.py | 1,406 | 4.125 | 4 | # -*- coding: utf-8 -*-
def hextet_complement(num):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create bitmask to help calculate one's complement
mask = 0xffff
# Use the invert operator, alongside the bitmask, to calculate result
return (~num & mask)
def internet_checksum(data, total=0x0):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create temp array to hold/manipulate data from data input
temp = []
# If number of bytes is odd, append extra zero byte
# For every even-numbered element in the array, shift it to the right
# by 8 bits, to allow for the final summing
for x in range(0, len(data)):
if (x % 2 == 0):
temp.append(data[x] << 8)
else:
temp.append(data[x])
# Sum all of the elements in the now edited array
checksum = sum(temp)
# take only 16 bits out of the 32 bit sum and add up the carries
while (checksum >> 16) > 0:
checksum = (checksum & 0xffff) + (checksum >> 16)
# Return the hextet_complement of the sum of the checksum and total
return hextet_complement(checksum + total)
| true |
82b50126fd52145f1d863a61ca57c592bf13b297 | carlosflrslpfi/CS2-A | /class-08/scope.py | 1,521 | 4.21875 | 4 | # Global and local scope
# The place where the binding of a variable is valid.
# Global variable that can be seen and used everywhere in your program
# Local variable that is only seen/used locally.
# Local analogous to within a function.
# we define a global variable x
x = 5
def some_function():
x = 10 # local variable
# print('local x is {}'.format(x))
return x + 5
y = some_function() # Global variable y
# function call: some_function(), no input
# evaluate: x = 10, return x + 5, return 10 + 5
# output: 15
print('global x is {}'.format(x))
# 5, 10, or 15?
print(y)
def other_function():
a = "hello!"
print(a)
other_function()
# print(a)
outside_variable = 10
def another_function(x):
x = x + outside_variable # x = x + outside_variable
print(x)
return x + 1
x = 5
print(another_function(x))
# function call: another_function(x), x = 5
# evaluate: x = x + outside_variable, x = 5 + 10 = 15, print(x)
# output: x + 1, 15 + 1, 16
print(x)
def even_yet_another_function(word):
word = word + ' more letters'
return word
word = 'hello'
w = even_yet_another_function(word)
# function call: even_yet_another_function(word), word = 'hello'
# evaluate: word = 'hello' + ' more letters' -> word = 'hello more letters'
# return: 'hello more letters'
print(w)
print(word)
# strings are also immutable
# if the data type is an immutable type this works differently.
def make_first_one(lst):
lst[0] = 1
l = [0, 1]
make_first_one(l)
print(l)
# lists are mutable types
| true |
1f561cbd24991690d041d444eae5cc96a110e06d | bronyamcgrory1998/Variables | /Class Excercises 5.py | 724 | 4.21875 | 4 | #Bronya McGrory
#22/09/2014
#Both a fridge and a lift have heights, widths and depths. Work out how much space is left in the lift once the fridge
fridgeheight= int (input("fridge height"))
fridgewidth= int (input("fridge width"))
fridgedepth= int (input("fridge depth"))
volume_of_fridge_answer= fridgeheight * fridgewidth * fridgedepth
print (volume_of_fridge_answer)
liftheight= int (input("lift height"))
liftwidth= int (input("lift width"))
liftdepth= int (input("lift depth"))
volume_of_lift_answer= liftheight * liftwidth * liftdepth
print (volume_of_lift_answer)
space_left= volume_of_fridge_answer-volume_of_lift_answer
print("the amount of space left in the lift is".format(space_left))
| true |
2d8881cef624299204688eee1fbe091c8f32fab0 | mariia-iureva/code_in_place | /group_coding_sections/Section2/8ball.py | 991 | 4.375 | 4 | """
Simulates a magic eight ball.
Prompts the user to type a yes or no question and gives
a random answer from a set of prefabricated responses.
"""
import random
# make a bunch of random answers
ANSWER_1 = "Ask again later."
ANSWER_2 = "No way."
ANSWER_3 = "Without a doubt."
ANSWER_4 = "Yes."
ANSWER_5 = "Possibly."
def main():
# Fill this function out!
number = random.randint(1,5)
# ask the user
# name: question, type: string
question = input("Ask a yes or no question: ")
# is question (string) the same as 0 (number)
while question != "":
# pick a random answer and tell the user the answer
if number == 1:
print(ANSWER_1)
if number == 2:
print(ANSWER_2)
if number == 3:
print(ANSWER_3)
if number == 4:
print(ANSWER_4)
if number == 5:
print(ANSWER_5)
question = input("Ask a yes or no question: ")
if __name__ == "__main__":
main()
| true |
a57612a005864e361ebf18274fc62a76f97618d1 | duonglong/practice | /magicalRoom.py | 2,880 | 4.15625 | 4 | # --*-- coding: utf-8 --*--
"""
You're an adventurer, and today you're exploring a big castle.
When you came in, you found a note on the wall of the room.
The note said that the castle contains n rooms, all of which are magical.
The ith room contains exactly one door which leads to another room roomsi.
Because the rooms are magical, it is possible that roomsi = i.
The note indicated that to leave the castle, you need to visit all the rooms,
starting from the current one, and return to the start room without visiting any room twice (except start one).
The current room has the number 0. And to make things more interesting,
you have to change the exit of exactly one door, i.e. to change one value roomsi.
Now you need to figure out how to leave the castle.
You need to return an array of two numbers numbers result[0] and result[1],
where result[0] is the number of the room with the exit you're going to change
and result[1] is the new room number to which the door from result[0] leads.
The new exit shouldn't be equal to the old one,
and after this operation is done it should be possible to visit all the rooms,
starting from 0, without visiting any room twice, and return to room 0 afterall.
If there is no answer, return [-1, -1] (and you're stuck in the castle forever).
Example
For rooms = [0, 1, 2], the output should be
magicalRooms(rooms) = [-1, -1];
For rooms = [0, 2, 0], the output should be
magicalRooms(rooms) = [0, 1].
After changing the exit of room 0 to 1, we have the following scheme of exits:
Room 0 leads to room 1;
Room 1 leads to room 2;
Room 2 leads to room 0.
As we can see, path 0 -> 1 -> 2 is valid and visits all the rooms exactly once.
Input/Output
[execution time limit] 4 seconds (py)
[input] array.integer rooms
An array of integers, where roomsi represents the 0-based exit from the room number i.
Guaranteed constraints:
3 ≤ rooms.length ≤ 10^5,
0 ≤ rooms[i] < rooms.length.
[output] array.integer
An array containing exactly 2 numbers, result[0] and result[1],
where result[0] is the room with the exit that's changing and result[1] is the number of the new exit of this room. result[1] shouldn't be equal to the old exit, and it should be possible to visit all rooms starting from 0 without visiting any room twice, and return to room 0 afterall. If this is impossible, return [-1, -1]
"""
def magicalRooms(rooms):
n = len(rooms) - 1
x = n * (n + 1) / 2 - sum(rooms)
s = set(range(n + 1)) - set(rooms)
r = list(s)[0] - x
print r, list(s)[0]
if x == 0 or len(s) > 1:
return [-1, -1]
if rooms[0] == 0 and len(s):
return [-1, -1]
for i in rooms:
pass
# import random
# test = range(0, 100001)
# random.shuffle(test)
tests = [
[3, 0, 4, 6, 5, 2, 5], # [4, 1]
[0, 2, 0], # [0, 1]
[4, 5, 0, 1, 4, 2] # [4, 3]
]
for t in tests:
magicalRooms(t)
| true |
1cd204b6f3b4a171e9625b8d2a3db9c04e472b84 | duonglong/practice | /acode.py | 2,098 | 4.25 | 4 | """
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:
Alice: 'Let's just use a very simple code: We'll assign 'A' the code word 1, 'B' will be 2, and so on down to 'Z' being assigned 26.'
Bob: 'That's a stupid code, Alice. Suppose I send you the word 'BEAN' encoded as 25114. You could decode that in many different ways!'
Alice: 'Sure you could, but what words would you get? Other than 'BEAN', you'd get 'BEAAD', 'YAAD', 'YAN', 'YKD' and 'BEKD'. I think you would be able to figure out the correct decoding. And why would you send me the word 'BEAN' anyway?'
Bob: 'OK, maybe that's a bad example, but I bet you that if you got a string of length 5000 there would be tons of different decodings and with that many you would find at least two different ones that would make sense.'
Alice: 'How many different decodings?'
Bob: 'Jillions!'
For some reason, Alice is still unconvinced by Bob's argument, so she requires a program that will determine how many decodings there can be for a given string using her code.
Input
Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of '0' will terminate the input and should not be processed.
Output
For each input set, output the number of possible decodings for the input string. All answers will be within the range of a 64 bit signed integer.
Example
Input:
25114
1111111111
3333333333
0
Output:
6
89
1
"""
def solve(n, i):
if int(n) == 0:
return 0
if i == len(n) - 1:
return 1
if i == len(n) - 2:
if int(n[i:]) > 26 or int(n[i+1]) == 0:
return 1
else:
return 2
if int(n[i]+n[i+1]) > 26 or int(n[i]) == 0:
return solve(n, i + 1)
return solve(n, i + 1) + solve(n, i + 2)
print solve('0', 0)
print solve('10', 0)
print solve('101', 0)
print solve('25114', 0)
print solve('1111111111', 0)
print solve('3333333333', 0)
| true |
b3fbacf8e7c5a5fd61a833c04a2b4e87899dc127 | KRiteshchowdary/myfiles | /Calculator.py | 394 | 4.15625 | 4 | a = float(input('number 1 is '))
function = input('desired function is ')
b = float(input('number 2 is '))
if (function == '+'):
print(a + b)
elif (function == '-'):
print(a - b)
elif (function == '*'):
print(a*b)
elif (function == '/' and b != 0):
print(a/b)
elif (function == '/' and b==0):
print('b cannot be equal to zero')
else:
print('give proper functions')
| true |
0ee672d520f8a915f269215ac12d78738e46ed33 | bilun167/FunProjects | /CreditCardValidator/credit_card_validator.py | 1,036 | 4.1875 | 4 | """
This program uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm) and works with most credit card numbers.
1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit.
2. If the result is greater than 9 (e.g., 7 * 2 = 14), then sum the digits of it (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5).
This procedure can be alternatively described as: num - 9
3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid.
"""
if __name__ == '__main__':
number = raw_input('Enter the credit card number of check: ')\
.replace(' ', '')
digits = [int(ch) for ch in number]
digits = digits[::-1]
# double alternate digits (step 1)
double = [(digit * 2) if (i % 2) else digit \
for (i, digit) in enumerate(digits)]
# subtract 9 which >= 10 (step 2)
summ = [num if num < 10 else num - 9 \
for num in double]
# step 3
if sum(summ) % 10 == 0:
print 'The number is valid'
else:
print 'The number is invalid'
| true |
8153b4cfc2169b781bc16d1ad06e2ca4233b3ea9 | osagieomigie/foodWebs | /formatList.py | 1,572 | 4.21875 | 4 | ## Format a list of items so that they are comma separated and "and" appears
# before the last item.
# Parameters:
# data: the list of items to format
# Returns: A string containing the items from data with nice formatting
def formatList(data):
# Handle the case where the list is empty
if len(data) == 0:
return "(None)"
# Start with an empty string that we will add items to
retval = ""
# Handle all of the items except for the last two
for i in range(0, len(data) - 2):
retval = retval + str(data[i]) + ", "
# Handle the second last item
if len(data) >= 2:
retval += str(data[-2]) + " and "
# Handle the last item
retval += str(data[-1])
# Return the result
return retval
# Run some tests if the module has not been imported
if __name__ == "__main__":
# Test the empty list
values = []
print(values, "is formatted as", formatList(values))
# Test a list containing a single item
values = [1]
print(values, "is formatted as", formatList(values))
# Test a list containing two items
values = [3, 4]
print(values, "is formatted as", formatList(values))
# Test a list containing three items
values = [-1, -2, -3]
print(values, "is formatted as", formatList(values))
# Test a list containing four items
values = ["Alice", "Bob", "Chad", "Diane"]
print(values, "is formatted as", formatList(values))
# Test a list containing lots of items
values = [3, 1, 4, 1, 5, 9, 2, 6, 5, 9]
print(values, "is formatted as", formatList(values))
| true |
d87ae28da2b3a113e2891241fddd47595525417f | margueriteblair/Intro-To-Python | /more-loops.py | 1,001 | 4.125 | 4 | #counting in a loop,
zork = 0
print('Before', zork)
for thing in [9, 42,12, 3, 74, 15]:
zork = zork+1
print(zork, thing)
print('After', zork)
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 42,12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', sum, count, sum/count)
#we can also use Boolean values to search for things
found = False
print('Before', found)
for value in [9, 42,12, 3, 74, 15]:
if value == 3:
found = True
print(found, value)
print('After', found)
#none type has one marker None, it's a constant
# is is stronger than equal sign
smallest = None
print('Before')
for value in [9, 41, 12, 3, 74, 15]:
if smallest is None :
smallest = value
elif value < smallest:
smallest = value
print (smallest, value)
print('AFTER', smallest)
#python has an is operator that can be used in logical expressions
#is implies 'is the same as'
#is not is also a logical operator
| true |
c3bce9a9f83075deeb2e20c609676b26e669840e | murffious/pythonclass-cornell | /coursework/working-with-data-file/samples/unit4/convert.py | 956 | 4.15625 | 4 | """
Module showing the (primitive) way to convert types in a CSV files.
When reading a CSV file, all entries of the 2d list will be strings, even if you
originally entered them as numbers in Excel. That is because CSV files (unlike
JSON) do not contain type information.
Author: Walker M. White
Date: June 7, 2019
"""
def numify(table):
"""
Modifies table so that all non-header rows contains numbers, not strings.
The header row is assumed (as in all CSV files) to be names. It will not
be altered.
Parameter table: The table to convert
Precondition: table is a rectangular 2d list of strings. Every row after
the first contains strings that can all be converted to numbers.
"""
# Altering, so must loop over positions
for rpos in range(1,len(table)): # Ignore the header
# Loop over columns
for cpos in range(len(table[rpos])):
table[rpos][cpos] = float(table[rpos][cpos])
| true |
30be17d0390482768e1351980180136f55087a9e | murffious/pythonclass-cornell | /coursework/programming-with-objects/exercise2/funcs.py | 1,793 | 4.15625 | 4 | """
Module demonstrating how to write functions with objects.
This module contains two versions of the same function. One version returns a new
value, while other modifies one of the arguments to contain the new value.
Author: Paul Murff
Date: Feb 6 2020
"""
import clock
def add_time1(time1, time2):
"""
Returns the sum of time1 and time2 as a new Time object
DO NOT ALTER time1 or time2, even though they are mutable
Examples:
The sum of 12hr 13min and 13hr 12min is 25hr 25min
The sum of 1hr 59min and 3hr 2min is 4hr 1min
Parameter time1: the starting time
Precondition: time1 is a Time object
Parameter time2: the time to add
Precondition: time2 is a Time object
"""
sum_time_h = int(str(time1).split(':')[0]) + int(str(time2).split(':')[0])
sum_time_m = int(str(time1).split(':')[1]) + int(str(time2).split(':')[1])
if sum_time_m > 60:
sum_time_m -=60
sum_time_h += 1
return clock.Time(sum_time_h,sum_time_m)
def add_time2(time1, time2):
"""
Modifies time1 to be the sum of time1 and time2
DO NOT RETURN a new time object. Modify the object time1 instead.
Examples:
The sum of 12hr 13min and 13hr 12min is 25hr 25min
The sum of 1hr 59min and 3hr 2min is 5hr 1min
Parameter time1: the starting time
Precondition: time1 is a Time object
Parameter time2: the time to add
Precondition: time2 is a Time object
"""
sum_time_h = int(str(time1).split(':')[0]) + int(str(time2).split(':')[0])
sum_time_m = int(str(time1).split(':')[1]) + int(str(time2).split(':')[1])
if sum_time_m > 60:
sum_time_m -=60
sum_time_h += 1
time1.hours = sum_time_h
time1.minutes = sum_time_m
| true |
5aa45d78764eb9ca62abc1f4d6bfd82b7056d90d | ellafrimer/shecodes | /lists/helper.py | 549 | 4.46875 | 4 | print("Accessing just the elements")
for letter in ['a', 'b', 'c']:
print(letter)
print("Accessing the elements and their position in the collection")
for (index, letter) in enumerate(['a', 'b', 'c']):
print("[%d] %s" % (index, letter))
print("A string is also a collection...")
for (index, letter) in enumerate("banana"):
print("iteration no. %d" % (index+1))
print("[%d] %s" % (index, letter))
dict = {
'first_key': 'first value'
}
dict['hi'] = 'hello'
dict['anyword'] = 23
print(dict)
"""
ABCDEFG
CDEFGHI
BAD -> DCF
""" | true |
6276c03f5933147d623376818f96cfa35f07f8e8 | shahamran/intro2cs-2015 | /ex3/findLargest.py | 410 | 4.46875 | 4 | #a range for the loop
riders=range(int(input("Enter the number of riders:")))
high_hat=0
gandalf_pos=0
#This is the loop that goes through every hat size and
#checks which is the largest.
for rider in riders:
height=float(input("How tall is the hat?"))
if height>high_hat:
high_hat=height
gandalf_pos=rider+1
print("Gandalf's position is:",gandalf_pos)
| true |
8552969c9e3f4e2764951ac3914572d1b9744a36 | Lumexralph/python-algorithm-datastructures | /trees/binary_tree.py | 1,471 | 4.28125 | 4 | from tree import Tree
class BinaryTree(Tree):
"""Abstract base class representing a binary tree structure."""
# additional abstract methods
def left_child(self, p):
"""Return a Position representing p's left child.
Return None if p does not have a left child
"""
raise NotImplementedError('must be implemented by the subclass')
def right_child(self, p):
"""Return a Position representing p's right child.
Return None if p does not have a right child
"""
raise NotImplementedError('must be implemented by the subclass')
# concrete methods that got implemented in this class
def sibling(self, p):
"""Return a Position representing p's sibling or None if no sibling."""
parent = self.parent(p)
if parent is None: # p must be the root
return None # a root has no sibling
else:
if p == self.left_child(parent): # if it is the left child
return self.right_child(parent)
else:
return self.left_child(parent)
def children(self, p):
"""Generate an iteration of Positions representing p's children."""
if self.left_child(p) is not None:
yield self.left_child(p)
if self.right_child(p) is not None:
yield self.right_child(p)
| true |
bf12f927c2d684699f41b48c1191ea956205a41c | km-aero/eng-54-python-basics | /exercise_103.py | 433 | 4.3125 | 4 | # Define the following variables
# name, last_name, species, eye_color, hair_color
# name = 'Lana'
name = 'Kevin'
last_name = 'Monteiro'
species = 'Alien'
eye_colour = 'blue'
hair_colour = 'brown'
# Prompt user for input and Re-assign these
name = input('What new name would you like?')
# Print them back to the user as conversation
print(f'Hello {name}! Welcome, your eyes are {eye_colour} and your hair color is {hair_colour}.') | true |
1736fa54bb0aa30ff931ced7e8fc61c104a3aa5d | CheshireCat12/hackerrank | /eulerproject/problem006.py | 544 | 4.21875 | 4 | #!/bin/python3
def square_of_sum(n):
"""Compute the square of the sum of the n first natural numbers."""
return (n*(n+1)//2)**2
def sum_of_squares(n):
"""Compute the sum of squares of the n first natural numbers."""
return n*(n+1)*(2*n+1)//6
def absolute_diff(n):
"""
Compute the absolute difference between the square of sum
and the sum of squares.
"""
return square_of_sum(n) - sum_of_squares(n)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(absolute_diff(n))
| true |
99e02fa63b997cb3156d5427da3833584a99d3c3 | stogaja/python-by-mosh | /12logicalOperators.py | 534 | 4.15625 | 4 | # logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
criminal_record = False
if is_good_credit and not criminal_record:
print('Eligible for a loan.')
# AND both conditions must be true
# OR at least one condition is true
# NOT reverses any boolean value given
| true |
fa537f900f5a5f23c8573e1965895df2dd3b3706 | jhreinholdt/caesar-cipher | /ceasar_cipher.py | 1,693 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 15:33:33 2017
@author: jhreinholdt
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "monoalphabetic substitution cipher" provides almost no security,
because an attacker who has the encoded message can either use frequency analysis to guess the key,
or just try all 25 keys.
"""
from types import *
import string
def encode(key, plaintext):
assert type(key) is int, "key is not an integer: %r" % key
ciphertext = ''
for char in plaintext:
# print((ord(char)+key)-97)
cipherchr = chr((((ord(char) + key) - 97) % 26) + 97)
ciphertext += cipherchr
# print("Plaintext: ", char, " Ciphertext: ", cipherchr)
# print("Ciphertext: ", ciphertext)
return ciphertext
def decode(key, ciphertext):
assert type(key) is int, "key is not an integer: %r" % key
plaintext = ''
for char in ciphertext:
plainchr = chr((((ord(char) - key) - 97) % 26) + 97)
plaintext += plainchr
# print("Plaintext: ", plaintext)
return plaintext
def main():
ciphertext = encode(25, input("Enter plaintext: "))
print("Ciphertext: ", ciphertext)
for key in range(1,26):
plaintext = decode(key, ciphertext)
print("Decoded plaintext with key#", key, ":", plaintext)
if __name__ == '__main__':
main() | true |
58185c8ed1fbceae5dbb44fc547712f101f17e21 | Meenal-goel/assignment_7 | /fun.py | 2,238 | 4.28125 | 4 | #FUNCTIONS AND RECURSION IN PYTHON
#1.Create a function to calculate the area of a circle by taking radius from user.
rad = float(input("enter the radius:"))
def area_circle (r):
res = (3.14*pow(r,2))
print("the area of the circle is %0.2f"%(res) )
area_circle(rad)
print("\n")
#Write a function “perfect()” that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.
#[An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
#function to determine number is a perfect number
def perf_num (n):
sum = 0
for i in range (1,n):
rem = n % i
if( rem == 0 ):
sum = sum +i
if(sum == n):
print("%d"%(n))
else :
return()
print("in the given range i.e between 1 to 1000 are:")
#loop to make use of function perf_num in given range
for j in range(1,1000) :
perf_num(j)
print("\n")
#3.Print multiplication table of 12 using recursion
def multi_twelve( multiplicand, multiplier=1):
if(multiplier <= 10):
print(multiplicand ,"x", multiplier,"=", multiplicand * multiplier)
multi_twelve(multiplicand,multiplier+1)
else:
return()
m = int(input("enter the multiplicand:"))
print("the multiplication table of %d is:"%(m))
(multi_twelve(m))
print("\n")
#4. Write a function to calculate power of a number raised to other ( a^b ) using recursion.
a = int(input("enter a number:"))
b = int(input("enter the power:"))
def pwr ( num1 , num2):
if(num2 !=0):
return(num1*pow(num1,num2-1))
else :
return(1)
print("%d^%d is:"%(a,b))
print(pwr(a,b))
print("\n")
#5. Write a function to find factorial of a number but also store the factorials calculated in a dictionary
numx = int(input("enter a countof numbers:"))
f=0
def fact ( numbr ):
if (numbr == 0):
return(1)
else :
#print("the factorial of the number %d is "%(numbr))
y=((numbr*fact(numbr-1)))
return(y)
num = numx
factorial = fact(numx)
dict = {num:factorial}
print(dict)
| true |
833994a2e77655b22525d4cf4e8d3d3a6ab93cc4 | JustineRobert/TITech-Africa | /Program to Calculate the Average of Numbers in a Given List.py | 284 | 4.15625 | 4 | n = int(input("Enter the number of elements to be inserted: "))
a =[]
for i in range(0,n):
elem = int(input("Enter the element: "))
a.append(elem)
avg = sum(a)/n
print("The average of the elements in the list", round(avg, 2))
input("Press Enter to Exit!")
| true |
5f5106c85c99ffa303151c793d5d490844b92977 | rajatsachdeva/Python_Programming | /UpandRunningwithPython/Working with files/OS_path_utilities.py | 1,241 | 4.125 | 4 | #
# Python provides utilities to find if a path is file or directory
# whether a file exists or not
#
# Import OS module
import os
from os import path
from datetime import date, time , datetime
import time
def main():
# print the name of os
print "Os name is " + os.name
# Check for item existence and type
print "Item Exists: " + str(path.exists("textfile.txt"))
print "Item is a file: " + str(path.isfile("textfile.txt"))
print "Item is a directory: " + str(path.isdir("textfile.txt"))
# Work with file paths
print "Item's path: " + str(path.realpath("textfile.txt"))
print "Item's path and name: " + str(path.split(path.realpath("textfile.txt")))
# Get the modification time of the file
t = time.ctime(path.getmtime("textfile.txt"))
print "Modification time for 'textfile.txt' is : " + t
print datetime.fromtimestamp(path.getmtime("textfile.txt"))
# Calculate how long ago the file was modified
td = datetime.now() - datetime.fromtimestamp(path.getmtime("textfile.txt"))
print "It has been " + str(td) + " since the file was updated"
print "Or, " + str(td.total_seconds()) + " seconds"
if __name__ == "__main__":
main()
| true |
f848e3d507aaad9c30b0042a17542dc6225e5945 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/04 Syntax/object.py | 921 | 4.25 | 4 | #!/bin/python3
# python is fundamentally an object oriented language
# In python 3 everything is an object
# class is a blueprint of an object
# encapsulation of variables and methods
class Egg:
# define a constructor
# with special name __init__
# All methods within classes have first argument as self
# which is the reference to object itself
def __init__(self, kind = "fired"):
self.kind = kind
def whatKind(self):
return self.kind
def main():
print("Main starts")
# Creates an Object of Egg class and
# Constructor is called whenever an object is created
# Here kind will be initialized with default value as fried
fried = Egg()
print("fried egg has %s"%(fried.whatKind()))
# Create another object
scrambled = Egg("scrambled")
print("scrambled egg has %s"%(scrambled.whatKind()))
if __name__ == "__main__":
main() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.