blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
aa7556b840c4efa4983cd344c69008a0f342f528 | shvnks/comp354_calculator | /src/functionsExponentOldAndrei.py | 2,603 | 4.21875 | 4 | # make your functions here
def exponent_function(constant, base, power):
total = base
if power % 1 == 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
counter = power - 1
while counter > 0:
total *= base
counter -= 1
return constant * total
else:
power *= -1
counter = power - 1
while counter > 0:
total *= base
counter -= 1
total = 1 / total
return constant * total
elif power % 1 != 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
sqrt = base ** power
return constant * sqrt
else:
power *= -1
sqrt = 1 / (base ** power)
return constant * sqrt
# print("\nPOSITIVE WHOLE NUMBERS")
# print("2^0= " + str(exponent_function(1, 2, 0)))
# print("2^1= " + str(exponent_function(1, 2, 1)))
# print("2^2= " + str(exponent_function(1, 2, 2)))
# print("2^3= " + str(exponent_function(1, 2, 3)))
# print("1^4= " + str(exponent_function(1, 1, 4)))
#
# print("\nNEGATIVE WHOLE NUMBERS")
# print("2^-0= " + str(exponent_function(1, 2, -0)))
# print("2^-1= " + str(exponent_function(1, 2, -1)))
# print("2^-2= " + str(exponent_function(1, 2, -2)))
# print("2^-3= " + str(exponent_function(1, 2, -3)))
# print("1^-4= " + str(exponent_function(1, 1, -4)))
#
# print("\nPOSITIVE FLOAT NUMBERS")
# print("2^0.0= " + str(exponent_function(1, 2, 0.0)))
# print("2^0.5= " + str(exponent_function(1, 2, 0.5)))
# print("2^1.5= " + str(exponent_function(1, 2, 1.5)))
# print("2^2.5= " + str(exponent_function(1, 2, 2.5)))
# print("2^3.5= " + str(exponent_function(1, 2, 3.5)))
# print("1^4.5= " + str(exponent_function(1, 1, 4.5)))
# print("4^1.5= " + str(exponent_function(1, 4, 1.5)))
# print("8^0.3= " + str(exponent_function(1, 8, 0.3)))
# print("2^arcos(0.98)= " + str(exponent_function(1, 2, math.acos(0.98))))
# print("2^log2(10)= " + str(exponent_function(1, 2, math.log(10, 2))))
# print("\nNEGATIVE FLOAT NUMBERS")
# print("2^-0.0= " + str(exponent_function(1, 2, -0.0)))
# print("2^-0.5= " + str(exponent_function(1, 4, -0.5)))
# print("2^-1.5= " + str(exponent_function(1, 2, -1.5)))
# print("2^-2.5= " + str(exponent_function(1, 2, -2.5)))
# print("2^-3.5= " + str(exponent_function(1, 2, -3.5)))
# print("1^-4.5= " + str(exponent_function(1, 1, -4.5)))
# print("4^-1.5= " + str(exponent_function(1, 4, -1.5)))
# print("8^-0.3= " + str(exponent_function(1, 8, -0.3)))
| true |
8face047d25661db2f4a5ed4faccf7036977c899 | y0m0/MIT.6.00.1x | /Lecture5/L5_P8_isIn.py | 854 | 4.28125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case: If aStr is empty, we did not find the char.
if aStr == '':
return False
# Base case: if aStr is of length 1, just see if the chars are equal
if len(aStr) == 1:
return char == aStr
middle = aStr[len(aStr)/2]
if char == middle:
return True
# Recursive case: If the test character is bigger than the middle
# character, recursively search on the first half of aStr
if char > middle:
return isIn(char,aStr[len(aStr)/2:])
# Otherwise the test character is smaller than the middle
# character, recursively search on the first half of aStr
else:
return isIn(char,aStr[:len(aStr)/2])
| true |
4a442570e403106067cd7df096500e2d34099819 | ge01/StartingOutWithPython | /Chapter_02/program_0212.py | 236 | 4.1875 | 4 | # Get the user's first name.
first_name = raw_input('Enter your first name: ')
# Get the user's last name.
last_name = raw_input('Enter your last name: ')
# Print a greeting to the user.
print('Hello ' + first_name + " " + last_name)
| true |
d38fbf3290696cc8ca9ae950fd4fe81c0253bbfd | jiresimon/csc_lab | /csc_ass_1/geometric_arithmetic/geo_arithmetic_mean.py | 1,066 | 4.25 | 4 | from math import *
print("Program to calculate the geometric/arithmetic mean of a set of positive values")
print()
print("N -- Total number of positive values given")
print()
total_num = int(input("Enter the value for 'N' in the question:\n>>> "))
print()
print("Press the ENTER KEY to save each value you enter...")
i = 1
num_list = []
while (i <= total_num):
numbers = int(input("Enter the numbers:\n>>> "))
if numbers > 0 :
num_list.append(numbers)
elif numbers < 0:
break
i+=1
print(num_list)
#To calculate the geometric mean
try:
geo_mean_1 = prod(num_list)
geo_mean_2= pow(geo_mean_1, 1/total_num)
#To calculate the arithmetic mean
ar_mean_1 = sum(num_list)
ar_mean_2 = (ar_mean_1/len(num_list))
print('Here are your answers...')
print()
print(f"The geometric mean of the given set of positive values is {geo_mean_2}")
print(f"The arithmetic mean of the given set of positive values is {ar_mean_2}")
except ZeroDivisionError:
print("Not divisible by zero")
| true |
a9cfa9463756a988acde76df57da14596c800169 | DebbyMurphy/project2_python-exercises | /wk4-exercises_lists/python-lists_q3-append.py | 487 | 4.5625 | 5 | # Q3) Ask the user for three names, append them to a list, then print the list.
# Input
# Izzy
# Archie
# Boston
# Output
# ["Izzy", "archie", "Boston"]
nameslist = []
firstname = input("Hi, what's your first name?! ")
middlename = input(f"Cool, hey {firstname} what about your middle name? ")
lastname = input(f"Thanks. And finally - please enter your last name: ")
nameslist.insert(0, firstname)
nameslist.insert(1, middlename)
nameslist.insert(2, lastname)
print(nameslist)
| true |
83e386a5c63cbd9696b0fa7ce04ca9ac248b6555 | prabhakarchandra/python-samples | /Question4.py | 694 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 11:08:55 2019
@author: v072306
"""
# Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
# Suppose the following input is supplied to the program:
# 34,67,55,33,12,98
# Then, the output should be:
# ['34', '67', '55', '33', '12', '98']
# ('34', '67', '55', '33', '12', '98')
# Hints:
# In case of input data being supplied to the question, it should be assumed to be a console input.
# tuple() method can convert list to tuple
k=input("Enter the list of values: ")
y = list(map(int, k.split(",")))
t = tuple(y)
print(y)
print(t) | true |
f23e9b415175dffbbe1fb1cae40438cc6612d496 | priyam009/Python-Codecademy | /Text Manipulation Examples/x_length_words.py | 521 | 4.125 | 4 | #Create a function called x_length_words that takes a string named sentence and an integer named x as parameters. This function should return True if every word in sentence has a length greater than or equal to x.
def x_length_words(sentence, x):
sentence = sentence.split()
count = 0
for word in sentence:
for letter in word:
count += 1
if count < x:
return False
break
count = 0
return True
print(x_length_words("i like apples", 2))
print(x_length_words("he likes apples", 2))
| true |
27b08fd75ad185244ddb9a44453d83326fe8d88a | priyam009/Python-Codecademy | /Loops Examples/exponents.py | 347 | 4.375 | 4 | #Create a function named exponents that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers.
def exponents(base, powers):
new_lst= []
for i in base:
for j in powers:
new_lst.append(i ** j)
return new_lst
print(exponents([2, 3, 4], [1, 2, 3])) | true |
9275738c76e060d910ef17a4644f8c21b89ce90f | priyam009/Python-Codecademy | /Loops Examples/max_num.py | 276 | 4.1875 | 4 | #Create a function named max_num that takes a list of numbers named nums as a parameter. The function should return the largest number in nums
def max_num(nums):
max = nums[0]
for i in nums:
if i >max:
max = i
return max
print(max_num([50, -10, 0, 75, 20])) | true |
4f906ffbb833dbbfa4a806c8f458fde74e98e3f3 | tyermercado/python-hacker-rank | /divisible_sum_pair.py | 1,857 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 22:32:30 2019
@author: bijayamanandhar
"""
#Github repo:
#https://www.hackerrank.com/challenges/divisible-sum-pairs/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
"""
You are given an array of integers, and a positive integer.
Find and print the number of pairs where and + is divisible by .
For example, and . Our three pairs meeting the criteria are and .
Function Description
Complete the divisibleSumPairs function in the editor below.
It should return the integer count of pairs meeting the criteria.
divisibleSumPairs has the following parameter(s):
n: the integer length of array
ar: an array of integers
k: the integer to divide the pair sum by
Input Format
The first line contains space-separated integers, and .
The second line contains space-separated integers describing the values of .
Constraints
Output Format
Print the number of pairs where and + is evenly divisible by .
Sample Input
6 3
1 3 2 6 1 2
Sample Output
5
Explanation
Here are the valid pairs when :
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the divisibleSumPairs function below.
def divisibleSumPairs(n, k, ar):
#collects number of pairs
res = 0
#iterates thru the length - 1
for i in range(n-1):
#iterates from i+1 to length, searches for the pairs
for j in range(i+1, n):
#when sum equals k
if (ar[i] + ar[j]) % k == 0:
#adds 1 to res
res += 1
return res
# Test Cases:
n = 5
k = 3
ar = [1,2,3,4,1,3,0]
print(divisibleSumPairs(n, k, ar) == 3)
# True ([ar[0]+ar[1]] = 3)\\//([ar[1]+ar[3] = 3)\\//([ar[1]+ar[4] = 3)
| true |
a43edd3f97e3c2229fbf824591fc5a5e0a1894b8 | KickItAndCode/Algorithms | /DynamicProgramming/UniquePaths.py | 1,320 | 4.34375 | 4 | # 62. Unique Paths
# robot is located at the top-left corner of a m x n grid(marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid(marked 'Finish' in the diagram below).
# How many possible unique paths are there?
# Above is a 7 x 3 grid. How many possible unique paths are there?
# Note: m and n will be at most 100.
# Example 1:
# Input: m = 3, n = 2
# Output: 3
# Explanation:
# From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
# 1. Right -> Right -> Down
# 2. Right -> Down -> Right
# 3. Down -> Right -> Right
# Example 2:
# Input: m = 7, n = 3
# Output: 28
# 1 1 1
# 1 0 0
def uniquePaths(m, n):
# initialize a all zero array
dp = [[0 for x in range(n)] for x in range(m)]
# set top row at 1's as there is only one direction it can go
for i in range(m):
dp[i][0] = 1
# set left row vertically as 1 as it has only one direction it can go
for i in range(n):
dp[0][i] = 1
# add the row above it and the side to calculate
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
print(uniquePaths(3, 2))
print(uniquePaths(7, 3))
| true |
86fd55a2d7264324ad169204d4c28024698d59f8 | KickItAndCode/Algorithms | /Graphs, BFS, DFS/2D Board BFS/SurroundedRegions.py | 2,413 | 4.125 | 4 | # 130. Surrounded Regions
# Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
# Example:
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
# X X X X
# X X X X
# X X X X
# X O X X
# Explanation:
# Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
# "Save Every O region "
from collections import deque
def solve(board):
queue = deque([])
# gets every value that is on the edge rows along the boundary
for r in range(len(board)):
for c in range(len(board[0])):
if (r in [0, len(board)-1] or c in [0, len(board[0])-1]) and board[r][c] == "O":
queue.append((r, c))
while queue:
r, c = queue.popleft()
if 0 <= r < len(board) and 0 <= c < len(board[0]) and board[r][c] == "O":
board[r][c] = "D"
queue.append((r-1, c))
queue.append((r+1, c))
queue.append((r, c-1))
queue.append((r, c+1))
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == "O":
board[r][c] = "X"
elif board[r][c] == "D":
board[r][c] = "O"
def solve1(board):
if not any(board):
return
m, n = len(board), len(board[0])
# gets every value that is on the edge rows along the boundary
save = [(i, j) for k in range(max(m, n))
for (i, j) in ((0, k), (m-1, k), (k, 0), (k, n-1))]
while save:
i, j = save.pop()
if 0 <= i < m and 0 <= j < n and board[i][j] == 'O':
board[i][j] = 'S'
save.extend([(i-1, j), (i+1, j), (i, j-1), (i, j+1)])
# Phase 2: Change every 'S' on the board to 'O' and everything else to 'X'.
board[:] = [['X' if c != 'S' else "O" for c in row] for row in board]
return board
print(solve(
[
["X", "X", "X", "X"],
["O", "O", "O", "X"],
["X", "X", "O", "X"],
["X", "O", "X", "X"]
]
))
# result
# X X X X
# X X X X
# X X X X
# X O X X
| true |
70ee7a473dfef293a283af568731e5f637a04d21 | KickItAndCode/Algorithms | /Recursion/TowerOfHanoi.py | 1,906 | 4.15625 | 4 | # Program for Tower of Hanoi
# Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
# 1) Only one disk can be moved at a time.
# 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
# 3) No disk may be placed on top of a smaller disk.
# Approach :
# Take an example for 2 disks :
# Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.
# Step 1 : Shift first disk from 'A' to 'B'.
# Step 2 : Shift second disk from 'A' to 'C'.
# Step 3 : Shift first disk from 'B' to 'C'.
# The pattern here is :
# Shift 'n-1' disks from 'A' to 'B'.
# Shift last disk from 'A' to 'C'.
# Shift 'n-1' disks from 'B' to 'C'.
# Image illustration for 3 disks :
NUMPEGS = 3
# def computeTowerHanoi(numrings):
# def computeTowerHanoiSteps(numrings, src, dst, tmp):
# if numrings > 0:
# computeTowerHanoiSteps(numrings - 1, src, tmp, dst)
# pegs[dst].append(pegs[src].pop())
# results.append([src, dst])
# computeTowerHanoiSteps(numrings - 1, tmp, dst, src)
# results = []
# pegs = [list(reversed(range(1, numrings, +1)))] + [[]
# for _ in range(1, numrings)]
# computeTowerHanoiSteps(numrings, 0, 1, 2)
# return results
# computeTowerHanoi(3)
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n == 1:
print("Move disk 1 from rod", from_rod, "to rod", to_rod)
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
# Driver code
n = 4
TowerOfHanoi(n, 'A', 'C', 'B')
# A, C, B are the name of rods
| true |
4233d6a91fe0b4d2a088cc13bf11a5cc1a0cccee | KickItAndCode/Algorithms | /ArraysListSets/GenerateParentheses.py | 2,883 | 4.125 | 4 | # 22. Generate Parentheses
# Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
# For example, given n = 3, a solution set is:
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
# Approach 2 (Directed Backtracking)
# The 3 Keys To Backtracking
# Our Choice:
# Whether we place a left or right paren at a certain decision point in our recursion.
# Our Constraints:
# We can't place a right paren unless we have left parens to match against.
# Our Goal:
# Place all k left and all k right parens.
# The Key
# At each point of constructing the string of length 2k we make a choice.
# We can place a "(" and recurse or we can place a ")" and recurse.
# But we can't just do that placement, we need 2 critical pieces of information.
# The amount of left parens left to place.
# The amount of right parens left to place.
# We have 2 critical rules at each placement step.
# We can place a left parentheses if we have more than 0 left to place.
# We can only place a right parentheses if there are left parentheses that we can match against.
# We know this is the case when we have less left parentheses to place than right parentheses to place.
# Once we establish these constraints on our branching we know that when we have 0 of both parens to place that we are done, we have an answer in our base case.
def generateParenthesis(n):
def generate(res, left, right, curr):
if left == 0 and right == 0:
res.append(curr)
# At each frame of the recursion we have 2 things we can do:
# 1.) Insert a left parenthesis
# 2.) Insert a right parenthesis
# These represent all of the possibilities of paths we can take from this
# respective call. The path that we can take all depends on the state coming
# into this call.
# Can we insert a left parenthesis? Only if we have lefts remaining to insert
# at this point in the recursion
if left > 0:
generate(res, left - 1, right, curr + "(")
# Can we insert a right parenthesis? Only if the number of left parens needed
# is less than then number of right parens needed.
# This means that there are open left parenthesis to close OTHERWISE WE CANNOT
# USE A RIGHT TO CLOSE ANYTHING. We would lose balance.
if left < right:
generate(res, left, right - 1, curr + ")")
# numLeftParensNeeded -> We did not use a left paren
# numRightParensNeeded - 1 -> We used a right paren
# parenStringInProgress + ")" -> We append a right paren to the string in progress
# result -> Just pass the result list along for the next call to use
res = []
generate(res, n, n, '')
return res
print(generateParenthesis(3))
| true |
3b4f9ea9c6d1257928b6ee539904746f5e7fa6b5 | marc-haddad/cs50-psets | /pset6/credit/credit.py | 2,388 | 4.125 | 4 | # Marc Omar Haddad
# CS50 - pset6: 'Credit'
# September 4, 2019
from cs50 import get_string
# This program uses Luhn's algorithm to check the validity and type of credit cards
def main():
num = get_string("Number: ")
# Repeatedly prompts user for valid numeric input
while (num.isdigit() != True):
num = get_string("Number: ")
# Checks if string is the correct length and if the first 2 chars are valid
if (
(len(num) != 13 and len(num) != 15 and len(num) != 16)
or (num[0] + num[1] != ("34")
and num[0] + num[1] != ("37")
and num[0] + num[1] != ("51")
and num[0] + num[1] != ("52")
and num[0] + num[1] != ("53")
and num[0] + num[1] != ("54")
and num[0] + num[1] != ("55")
and num[0] != ("4"))
):
print('INVALID')
# Checks the result of custom boolean function luhn()
if luhn(num) == False:
print('INVALID')
return 1
# Passing all previous checks means the provided num is valid
# Checks the 'type' of credit card
else:
if (num[0] == '3'):
print('AMEX')
elif (num[0] == '4'):
print('VISA')
else:
print('MASTERCARD')
return 0
# Boolean function that takes a numeric string as input and applies Luhn's algorithm for validity
def luhn(stri):
# Initializes the variable that will contain total sum
add = 0
# Iterates over the string moving backwards starting from the before-last digit, skipping every other digit
for i in range(-2, -(len(stri) + 1), -2):
# Converts from char to int and multiplies by 2
x = int(stri[i]) * 2
# If result has 2 digits, add one individual digit to the other
if x > 9:
x = x % 10 + ((x - (x % 10)) / 10)
add += x
# If result has 1 digit, add it directly
else:
add += x
# Iterates over the rest of the string backwards
for i in range(-1, -(len(stri) + 1), -2):
# Converts chars to ints
x = int(stri[i])
# Adds digits as-is to total sum
add += x
# Checks to see if total sum is divisible by 10 (thus satisfying the conditions of Luhn's algorithm)
if (add % 10 == 0):
return True
else:
return False
if __name__ == "__main__":
main()
| true |
14f03f53b53fee9132afebbc12ed6b72d75315e6 | aaronjrenfroe/Algorithms | /fibonacci_memoize.py | 465 | 4.125 | 4 | # Returns the nth number in the fibonacci sequence
def fib_memo(n, memo):
if n == 0:
return 0
elif memo[n] != None:
return memo[n]
elif n == 1 or n == 2:
memo[n] = 1
else:
memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
return memo[n]
# memo initialiseation cen be done differntly
# but this is the simplest method that keeps fib_memo clean
# inorder to understand what's going on.
n = 0
memo = (n+1)*[None]
print(fib_memo(n, memo)) | true |
c54d475ea800479f4cdf5b2a1f95e3e5efde9452 | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/The while Loop.py | 2,207 | 4.6875 | 5 | The while Loop
The most basic type of loop that we have at our disposal is the while loop. This type of loop repeats itself based on a condition that we pass to it. Here’s the general structure of a while loop:
while CONDITION:
pass
The CONDITION in this statement works the same way that it does for an if statement. When we demonstrated the if statement, we first tried it by simply passing in True as the condition. Let’s see when we try that same condition with a while loop:
>>> while True:
... print("looping")
...
looping
looping
looping
looping
That loop will continue forever, we’ve created an infinite loop. To stop the loop, press Ctrl-C. Infinite loops are one of the potential problems with while loops if we don’t use a condition that we can change from within the loop then it will continue forever if initially true. Here’s how we’ll normally approach using a while loop where we modify something about the condition on each iteration:
>>> count = 1
>>> while count <= 4:
... print("looping")
... count += 1
...
looping
looping
looping
looping
>>>
We can use other loops or conditions inside of our loops; we need only remember to indent four more spaces for each context. If in a nested context, we want to continue to the next iteration or stop the loop entirely. We also have access to the continue and break keywords:
>>> count = 0
>>> while count < 10:
... if count % 2 == 0:
... count += 1
... continue
... print(f"We're counting odd numbers: {count}")
... count += 1
...
We're counting odd numbers: 1
We're counting odd numbers: 3
We're counting odd numbers: 5
We're counting odd numbers: 7
We're counting odd numbers: 9
>>>
In that example, we also show off how to “string interpolation” in Python 3 by prefixing a string literal with an f and then using curly braces to substitute in variables or expressions (in this case the count value).
Here’s an example using the break statement:
>>> count = 1
>>> while count < 10:
... if count % 2 == 0:
... break
... print(f"We're counting odd numbers: {count}")
... count += 1
...
We're counting odd numbers: 1 | true |
fdd668609fcd5bf054e8888d5da465a1a971089a | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/Working with Environment Variables.py | 1,809 | 4.21875 | 4 | Working with Environment Variables
By importing the os package, we’re able to access a lot of miscellaneous operating system level attributes and functions, not the least of which is the environ object. This object behaves like a dictionary, so we can use the subscript operation to read from it.
Let’s create a simple script that will read a 'STAGE' environment variable and print out what stage we’re currently running in:
~/bin/running
#!/usr/bin/env python3.6
import os
stage = os.environ["STAGE"].upper()
output = f"We're running in {stage}"
if stage.startswith("PROD"):
output = "DANGER!!! - " + output
print(output)
We can set the environment variable when we run the script to test the differences:
$ STAGE=staging running
We're running in STAGING
$ STAGE=production running
DANGER!!! - We're running in PRODUCTION
What happens if the 'STAGE' environment variable isn’t set though?
$ running
Traceback (most recent call last):
File "/home/user/bin/running", line 5, in
stage = os.environ["STAGE"].upper()
File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'STAGE'
This potential KeyError is the biggest downfall of using os.environ, and the reason that we will usually use os.getenv.
Handling A Missing Environment Variable
If the 'STAGE' environment variable isn’t set, then we want to default to 'DEV', and we can do that by using the os.getenv function:
~/bin/running
#!/usr/bin/env python3.6
import os
stage = os.getenv("STAGE", "dev").upper()
output = f"We're running in {stage}"
if stage.startswith("PROD"):
output = "DANGER!!! - " + output
print(output)
Now if we run our script without a 'STAGE' we won’t have an error:
$ running
We're running in DEV | true |
e7c1e57d0061f37a815fa05ea988deef32bf1bc0 | jeen-jos/PythonPrograms | /Code/test.py | 709 | 4.375 | 4 | # Follwoing code shows how to print
msg = "Hello world"
print(msg)
print(msg.capitalize())
print(msg.split())
# Taking inputs from user
name = input("enter your name : ")
print("Hello ",name)
# eval() converts entered text into number to evaluate expressions
num= eval(input("Enter the number : "))
print(" The value is ",num*num)
print("the value of 3+4 is ",3+4)
print("5+6 is ",5+6," and 4+7 is ",4+7)
#Optional Arguments of print()
#-------------------------------------
#sep - python insets space between arguments of print()
print("the value of 3+4 is ",3+4,".",sep=' ')
#end - keeps python print() from advancing automatically to next line
print("hello friends",end=' ')
print("Have a great day")
| true |
a9c7bb5f18b5b109b924e0bd5eb0bc2386e6d0eb | rajiarazz/task-2 | /day2/day2.py | 343 | 4.3125 | 4 | #1 ) Consider i = 2, Write a program to convert i to float.
i=2
print(float(i))
#2 )Consider x="Hello" and y="World" , then write a program to concatinate the strings to a single string and print the result.
x="Hello "
y="World"
print(x+y)
#3 ) Consider pi = 3.14 . print the value of pie and its type.
pi=3.14
print(pi)
type(pi) | true |
a32fc4f194acd34c21ef5a5bcfcb3bf9f5d34bc1 | akarnoski/data-structures | /python/data_structures/trie_tree.py | 2,265 | 4.1875 | 4 | """Create a trie tree."""
class Node(object):
"""Build a node object."""
def __init__(self, val=None):
"""Constructor for the Node object."""
self.val = val
self.parent = None
self.children = {}
class TrieTree(object):
"""Create a trie tree object."""
def __init__(self):
"""Constructor for the trie tree object."""
self.size = 0
self.root = Node('*')
def insert(self, string):
"""Insert string into trie tree."""
curr = self.root
string = string + '$'
for letter in string:
print(letter)
if letter in curr.children:
curr = curr.children[letter]
new = False
else:
new_letter = Node(letter)
new_letter.parent = curr
curr.children[letter] = new_letter
curr = new_letter
new = True
if new:
self.size += 1
def size(self):
"""Return size of trie tree."""
return self.size
def contains(self, string):
"""Return true if string is in trie."""
try:
self._node_crawler(string)
return True
except KeyError:
return False
def _val_crawler(self, string):
"""Trie tree crawler helper function that returns values of the nodes
to help me visualize while testing."""
values = []
curr = self.root
values.append(curr.val)
string = string + '$'
try:
for letter in string:
curr = curr.children[letter]
values.append(curr.val)
except KeyError:
raise KeyError('Word not in Trie Tree')
return values
def _node_crawler(self, string):
"""Trie tree crawler helper function that returns list of the nodes
to help me visualize while testing."""
nodes = []
curr = self.root
nodes.append(curr)
string = string + '$'
try:
for letter in string:
curr = curr.children[letter]
nodes.append(curr)
except KeyError:
raise KeyError('Word not in Trie Tree')
return nodes
| true |
0927de7b023d96a01db8047c1955aedfdcd2a9a1 | hillarymonge/class-samples | /fancyremote.py | 856 | 4.25 | 4 | import turtle
from Tkinter import *
def circle(myTurtle):
myTurtle.circle(50)
# create the root Tkinter window and a Frame to go in it
root = Tk()
frame = Frame(root)
# create our turtle
shawn = turtle.Turtle()
# make some simple but
fwd = Button(frame, text='fwd', command=lambda: shawn.forward(50))
left = Button(frame, text='left', command=lambda: shawn.left(90))
right = Button(frame, text ='right', command=lambda: shawn.right(90))
penup = Button(frame, text ='penup', command=lambda:shawn.penup())
pendown = Button(frame, text ='pendown', command=lambda:shawn.pendown())
makecircle = Button(frame, text='makecircle', command=lambda:shawn.circle(50))
# put it all together
fwd.pack(side=LEFT)
left.pack(side=LEFT)
frame.pack()
right.pack(side=LEFT)
penup.pack(side=LEFT)
pendown.pack(side=LEFT)
makecircle.pack(side=LEFT)
turtle.exitonclick()
| true |
2868818bbaaef980a57267f34e8cec8bd6574018 | ShresthaRujal/python_basics | /strings.py | 340 | 4.28125 | 4 | #name = "rujal shrestha";
#print(name);
#print(name[0]); #indexing
#print(name[3:]) # prints all string after 3rd character
#print(name.upper())
#print(name.lower())
#print(name.split(s)) #default is white space
#print formatting
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
x = "Item One : {}".format("ÏNSERT ME!")
print(x)
| true |
1f8975b5b315aa287404ef91c968a3039274215a | Denzaaaaal/python_crash_course | /Chapter_8/user_album.py | 644 | 4.1875 | 4 | def make_album(name, title, no_of_songs=None):
if no_of_songs:
album = {
'artist_name': name,
'album_title': title,
'number_of_songs': no_of_songs,
}
else:
album = {
'artist_name': name,
'album_title': title,
}
return album
while True:
print ("\n(Enter 'quit' to end the program)")
entered_name = input("What is the artist name: ")
if entered_name == 'quit':
break
entered_album = input("What is the albums title: ")
if entered_album == 'quit':
break
print (make_album(entered_name, entered_album)) | true |
5523bdf0039a9d1b2c5a03e00aa8e3a48f6b73d3 | udoyen/andela-homestead | /codecademy/advanced_topics/dictionary/sample.py | 528 | 4.15625 | 4 | movies = {
"Monty Python and the Holy Grail": "Great",
"Monty Python's Life of Brian": "Good",
"Monty Python's Meaning of Life": "Okay"
}
for key in movies:
print(key, movies[key])
print("===================================")
for key, value in movies.items():
print([(key, value)], end=' ')
# print("===================================")
#
# print(list(filter(lambda x: (movies[x], x), movies)))
#
# print("===================================")
#
# print([(key, value) for key, value in movies.items()])
| true |
42db31f4a097ff0c8b38af894441bd4ffe75aa8f | jovyn/100-plus-Python-challenges | /100-exercises/ex16.py | 442 | 4.25 | 4 | '''
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,9,25,49,81
'''
num_lst = input("Enter a sequence of nos. comma separated: ")
num_lst = num_lst.split(",")
new_lst = [ str(int(n)*int(n)) for n in num_lst if int(n) % 2 != 0 ]
s = ","
print(s.join(new_lst))
| true |
52bdee1e48b1e04565e350c5227db664729b1cf7 | prashantravishshahi/pdsnd_github | /User_Input.py | 2,512 | 4.375 | 4 | #definition of input month function.
def get_month():
'''Asks the user for a month and returns the specified month.
Args:
none.
Returns:
(tuple) Lower limit, upper limit of month for the bikeshare data.
'''
months=['january','february','march','april','may','june']
while True:
month =input('\nWhich month of year? Choose january, february, march, april, may or june\n')
month=month.lower()
if(month in months):
break
print("\nI'm sorry, The month you have entered is incorrect. Please try again.")
return month
#definition of input day function.
def get_day():
'''Asks the user for a day and returns the specified day.
Args:
none.
Returns:
(tuple) Lower limit, upper limit of date for the bikeshare data.
'''
days=['sunday','monday','tuesday','wednesday','thursday','friday','saturday']
while True:
day =input('\nWhich day of week? Choose sunday, monday, tuesday, wednesday, thursday, friday or saturday\n')
day=day.lower()
if(day in days):
break
print("\nI'm sorry, The month you have entered is incorrect. Please try again.")
return day
#definition of filters function
def get_filters():
print('Hello! There Let\'s explore some US bikeshare data!')
# get user input for city (chicago, New York City, Washingon).
citys=['chi','new','was']
while True:
city =input('\nPlease choose one of the cities (chicago, new york city, washington)\n You can provide intial 3 letters:- ')
city=city.lower()
city = city[:3]
if(city in citys):
break
print("\nI'm sorry, The City you have entered is incorrect. Please try once more.")
# get user input for filters (Month, Day, Both or not at all)
while True:
filters=['m','d','b','n']
filter =input('\nDo you wish to filter using\m:Month\nd:Day\nb:Both\nn:No filters\nType m, d, b, or n\n')
if(filter in filters):
break
if(filter=='m'):
# get filter criteria of month from user
month=get_month()
day='all'
elif(filter=='d'):
# get filter criteria of day from user
day=get_day()
month='all'
elif(filter=='b'):
# get filter criteria of month and day from user
month=get_month()
day=get_day()
elif(filter=='n'):
day='all'
month='all'
print('-'*100)
return city, month, day | true |
ce981daae2eeda0038941778658b09ced578538b | kelv-yap/sp_dsai_python | /ca3_prac1_tasks/section_2/sec2_task4_submission.py | 780 | 4.3125 | 4 | number_of_months = 6
title = "Calculate the average of your last " + str(number_of_months) + "-months electricity bill"
print("*" * len(title))
print(title)
print("*" * len(title))
print()
bills = []
bill_number = 1
while bill_number <= number_of_months:
try:
input_bill = float(input("Enter Bill #{}: ".format(bill_number)))
bills.append(input_bill)
bill_number += 1
except ValueError:
print("Please enter a numeric value")
print("Your electricity bills for the past " + str(number_of_months) + " months are:")
bill_str_list = []
for bill in bills:
bill_str_list.append("$" + str(bill))
print(*bill_str_list, sep=", ")
average = sum(bills) / number_of_months
print("The average of your electricity bill is {:.2f}".format(average))
| true |
e3ac44b37f2f78dac95229051386a20881b61009 | Afraysse/practice_problems | /missing_num.py | 1,173 | 4.125 | 4 |
"""
SOLUTION 1: Simple Solution - O(N)
keep track of what you've seen in a seperate list.
"""
def find_missing_num(nums, max_num):
# find what number is missing from the list and return it
# there's a way of solving in O(n), but can also solve in O(log N)
# list may be in any order
seen = [False] * max_num
for n in nums:
seen[n - 1] = True
# the false value is the one not yet seen
return seen.index(False) + 1
# SOLUTION RUNTIME: O(N) and requires additional storage -- not ideal
"""
SOLUTION 2: Sorting Solution - O(N log N)
Sort the numbers first, then scan thme to see which one missing.
"""
def misisng_num(nums, max_num):
nums.append(max_num + 1) # adds one larger than the max
nums.sort() # sorts list to make more iterable
last = 0
for i in nums:
if i != last + 1:
return last + 1
last += 1
raise Exception("None are missing!")
""" SOLUTION 3: add the numbers and subtract from expected sum. """
def missing_num(nums, max_num):
expected = sum(range(max_num + 1))
return expected - sum(nums)
# will return the missing number
| true |
e1771a8446c03835dda14e0f77a779a5c8451ae2 | LPisano721/color_picker | /colorpicker.py | 1,767 | 4.21875 | 4 | """
Program: colorpicker.py
Author: Luigi Pisano 10/14/20
example from page 287-288
Simple python GUI based program that showcases the color chooser widget
"""
from breezypythongui import EasyFrame
import tkinter.colorchooser
class ColorPicker(EasyFrame):
"""Displays the result of picking a color."""
def __init__(self):
"""Sets up the window and the widgets."""
EasyFrame.__init__(self, title = "Color Chooser Demo")
# Labels and output fields
self.addLabel(text= "R", row = 0, column = 0)
self.addLabel(text= "G", row = 1, column = 0)
self.addLabel(text= "B", row = 2, column = 0)
self.addLabel(text= "Color", row = 3, column = 0)
self.r = self.addIntegerField(value = 0, row = 0, column = 1)
self.g = self.addIntegerField(value = 0, row = 1, column = 1)
self.b = self.addIntegerField(value = 0, row = 2, column = 1)
self.hex = self.addTextField(text = "#000000", row = 3, column = 1)
# Canvas widget with an initial black color background
self.canvas = self.addCanvas(row = 0, column = 2, rowspan = 4, width = 50, background = "#000000")
# Command button
self.addButton(text = "Pick a Color", row = 4, column = 0, columnspan = 3, command = self.chooseColor)
# Event handling method
def chooseColor(self):
"""Pops up a color chooser from the OS and outputs the results."""
colorTuple = tkinter.colorchooser.askcolor()
if not colorTuple[0]:
return
((r, g, b), hexString) = colorTuple
self.r.setNumber(int(r))
self.g.setNumber(int(g))
self.b.setNumber(int(b))
self.hex.setText(hexString)
self.canvas["background"] = hexString
def main():
"""Instantiates and pops up the window>"""
ColorPicker().mainloop()
#Global call to the main function
main()
| true |
2da51b497199b3dd5b65dcf8b63eb1443965f169 | Harmonylm/Pandas-Challenge | /budget_v1.py | 2,831 | 4.1875 | 4 | # Budget: version 1
# Run with: python3 budget_v1.py
import csv
BUDGET_FILE="budget_data.csv"
month_count = 0 # number of months read
total_pl = 0 # total profit less all losses
max_profit = 0 # largest profit increase seen
max_profit_month = "" # month string with maximum profit increase
max_loss = 0 # largest loss seen
max_loss_month = "" # month string with maximum loss
last_pl = 0 # last month profit/loss value
current_pl = 0 # current month profit/loss value
current_month = "" # current month name
with open(BUDGET_FILE, "r", newline="") as f:
reader = csv.reader(f)
header = next(reader)
# Make sure first word of header is "Date"
if (header[0] != "Date"):
print("ERROR: Unexpected data file format.")
exit(1)
# Read each line of file and perform calculations
for row in reader:
month_count += 1 # count months
current_month = row[0] # this month name
current_pl = int(row[1]) # this month profit/loss value
# Debugging
# print("month_count: ", month_count)
# print("current_month: ", current_month)
# print("current_pl: ", current_pl)
# Check for an increase in profit.
# Assume that we must have had a profit - the profit/loss value must be positive.
# If we increased profit over last month save the value if largest seen so far.
if (current_pl > 0): # had a profit, see if biggest so far
if (current_pl > last_pl): # made more than last month
size = current_pl - last_pl # how much did we grow over last month
if (size > max_profit):
max_profit = size
max_profit_month = current_month
# Check for greatest decrease in profit (decrease between two months).
# Test is that profit/loss value is less than last month.
# Record value if largest loss seen so far.
if (current_pl < last_pl): # had a loss from last month
size = current_pl - last_pl # how much of a loss since last month
if (size < max_loss):
max_loss = size # record the loss
max_loss_month = current_month
# Total all profits and subtract all losses to determine total revenue
total_pl += current_pl
# Update last month value for use in next loop
last_pl = current_pl
# Done - print results.
print("Total Months: ", month_count)
print("Total profit/loss: ", total_pl)
print("Max increase in profit: ", max_profit)
print("Max increase in profit month: ", max_profit_month)
print("Max decrease in profit: ", max_loss)
print("Max decrease in profit month: ", max_loss_month)
| true |
db665202fccf5aef49ee276732e2050ffde1306f | thiamsantos/python-labs | /src/list_ends.py | 416 | 4.1875 | 4 | """
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
"""
def get_list_start_end(initial_list):
return [initial_list[0], initial_list[-1]]
def main():
a = [5, 10, 15, 20, 25]
print(get_list_start_end(a))
if __name__ == "__main__":
main()
| true |
9993766594dea8835043ca71a5e058d4dc8796bf | thiamsantos/python-labs | /src/odd_even.py | 525 | 4.40625 | 4 | """Ask the user for a number.
Depending on whether the number is even or odd, print out an appropriate message to the user.
Hint: how does an even / odd number react differently when divided by 2?
"""
def is_odd(number):
return number % 2 == 1
def main():
number = int(input("Type a number: "))
number_is_odd = is_odd(number)
if number_is_odd:
print("{number} is odd!".format(number=number))
else:
print("{number} is even!".format(number=number))
if __name__ == "__main__":
main()
| true |
4fe16b312f72b931743d74d10805aa3446951398 | Accitri/PythonModule1 | /(4) 06.12.2017/Class work/dataVisualisationWithTurtle.py | 2,854 | 4.1875 | 4 |
import turtle
myTurtle = turtle.Turtle
#defining a function for the basic setup of the turtle
def setupTurtle():
myTurtleInsideFunction = turtle.Turtle()
myTurtleInsideFunction.penup()
myTurtleInsideFunction.setpos(-300, 0)
myTurtleInsideFunction.pendown()
myTurtleInsideFunction.color('red')
myTurtleInsideFunction.pensize(2)
myTurtleInsideFunction.speed(100)
return myTurtleInsideFunction
#calling the setupTurtle function and
#store the result in a variable called myTurtle
myTurtle = setupTurtle()
#define the temperature list
averageTemperatureList = [3, 5, 1, -4, -1, 4, 0, -5, -1, -3, 1, 4]
numberOfRainyDays = [22, 19, 19, 18, 17, 18, 19, 19, 20, 21, 21, 20]
#defining a function that draws a rectangle
def drawTempGraphRectangle():
myTurtle.penup()
myTurtle.setpos(-300, 0)
myTurtle.pendown()
for i in range(0, len(averageTemperatureList)):
if (averageTemperatureList[i] >= 0):
myTurtle.color('green')
if (averageTemperatureList[i] < 0):
myTurtle.color('red')
myTurtle.forward(15)
myTurtle.left(90)
myTurtle.forward(averageTemperatureList[i] * 10)
myTurtle.right(90)
myTurtle.forward(15)
myTurtle.right(90)
myTurtle.forward(averageTemperatureList[i] * 10)
myTurtle.left(90)
#defining function that draws a rectangle
def pulse(height, width):
for i in range(0, len(averageTemperatureList)):
if (averageTemperatureList[i] >= 0):
myTurtle.color('green')
if (averageTemperatureList[i] < 0):
myTurtle.color('red')
myTurtle.left(90)
myTurtle.forward(height * 10)
myTurtle.right(90)
myTurtle.forward(width)
myTurtle.right(90)
myTurtle.forward(height * 10)
myTurtle.left(90)
myTurtle.forward(width)
def drawGraphCircle():
for i in range(0, len(averageTemperatureList)):
if (averageTemperatureList[i] >= 0):
myTurtle.color('green')
if (averageTemperatureList[i] < 0):
myTurtle.color('red')
myTurtle.circle(averageTemperatureList[i] * 10)
def drawRainGraphRectangle():
myTurtle.penup()
myTurtle.setpos(-300, 0)
myTurtle.pendown()
myTurtle.color('blue')
for i in range(0, len(numberOfRainyDays)):
myTurtle.forward(20)
myTurtle.left(90)
myTurtle.forward(numberOfRainyDays[i] * 10)
myTurtle.right(90)
myTurtle.forward(10)
myTurtle.right(90)
myTurtle.forward(numberOfRainyDays[i] * 10)
myTurtle.left(90)
#for temp in averageTemperatureList[i]:
#pulse(temp, 25)
#drawRainGraphRectangle()
#calling the drawGraphRectangle function
#to visualise averageTemperatureList
#drawTempGraphRectangle()
#pulse()
drawGraphCircle()
turtle.done()
| true |
a7e4955daf0d8d355bed55be5d43df8fffff872c | HarshaYadav1997/100daychallange | /day-5/matrixtranspose.py | 481 | 4.1875 | 4 |
rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
matrix.append(list(map(int, input().rstrip().split())))
"tranpose of a matrix is"
for i in matrix:
print(i)
tmatrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print("Transpose of Matrix : ")
for i in tmatrix:
print(i)
| true |
f3f5d8f50592f4d4cb642061f6e4bb57bbe74329 | gbartomeo/mtec2002_assignments | /class11/labs/my_fractions.py | 1,500 | 4.40625 | 4 | """
fractions.py
=====
Create a class called Fraction that represents a numerator and denominator.
Implement the following methods:
1. __init__ with self, numerator and denominator as arguments that sets a numerator and denominator attribute
2. __str__ with self as the only argument... that prints out a fraction as numerator/denominator ...for example, 1/2
3. pretty_print with self as the only argument... it prints out:
1
-
2
4. multiply with self and another Fraction as the arguments... it should alter the numerator and denominator of the current fraction, but it's not necessary to reduce
5. (INTERMEDIATE) add with self and another Fraction as the arguments... it should alter the numerator and denominator of the currecnt fraction, but it's not necessary to reduce
Some example output from the interactive shell:
>>> a = Fraction(1,2)
>>> print a
1/2
>>> a.pretty_print()
1
-
2
>>> a.add(Fraction(1,4))
>>> print a
6/8
>>> a.multiply(Fraction(2,3))
>>> print a
12/24
>>>
"""
class Fraction:
def __init__(self,numerator,denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
self.pretty_print = "%s\n-\n%s" % (self.numerator, self.denominator)
return "%s/%s" % (self.numerator, self.denominator)
def multiply(self,f):
try:
self.x = (self.x*f.x)
self.y = (self.y*f.y)
except AttributeError:
try:
self.x = (self.x*f[0])
self.y = (self.x*f[1])
except:
raise TypeError("What are you trying to multiply by?!") | true |
5e4abdc4bb35aa3cad8a8b740f422f2e4f53b590 | gbartomeo/mtec2002_assignments | /class5/greetings.py | 580 | 4.40625 | 4 | """
greetings.py
=====
Write the following program:
1. Create a list of names and assign to a variable called names
2. Append another name to this list using append
3. Print out the length of this list
4. Loop through each item of this list and print out the name with a greeting, like "hello", appended before it
For example...
Hello Dave
Hello Sue
Hello James
"""
names = ["Mary", "Jane", "Marth", "Jacob", "Dave", "Sue", "James"]
names.append("Kiara")
print "There are %d names in this list!" % len(names)
i = 0
while i < len(names):
print "Hello %s!" % names[i]
i += 1 | true |
2c6f5d75d5a749a332ffafb990764c00e7fd4cb2 | wittywatz/Algorithms | /Algorithms Python/validMountain.py | 597 | 4.375 | 4 | def validMountainArray(arr):
'''
Returns true if the array is a valid mountain
'''
if (len(arr)<3):
return False
index = 0
arrlen = len(arr)
while ((index+1)<=(arrlen-1) and arr[index]<arr[index+1]):
index +=1
if(index == arrlen-1 or index==0):
return False
while((index+1)<=(arrlen-1) and arr[index]>arr[index+1]):
index +=1
if(index < arrlen-1):
return False
else:
return True
| true |
018180c41b27bdd3582dedfa279c0e8f8532fa53 | rbunch-dc/11-18immersivePython101 | /python101.py | 2,768 | 4.40625 | 4 | # print "Hello, World";
# print("Hello, World");
# print """
# It was a dark and stormy night.
# A murder happened.
# """
# print 'Hello, World'
# print 'Khanh "the man" Vu'
print 'Binga O\'Neil\n'
# # Variables
# # - strings, letters, numbers, or any other stuff
# # you can make with a keyboard
# # a variable is just a fast way to refer to something else
# # variables do not make the program faster.
# # They make the program slower!
# # Variables make it easier for us to write programs.
# # theBestClass = "the 11-18 immersive"
# # print theBestClass
# # Data Types
# # - Programming langauges see different types fo variables
# # differently
# # - String - English stuff.
# # - Number - I think you know what this is. Something with numbers (or - or e)
# # # print 3.3e10+"Joe"
# # -- float = it has a . in it
# # -- integer - has no .
# # - Booleans - true or false, on or off, 1 or 0, yes or no, right or left
# # - List - list of things. a single variable with a bunch of parts
# # - Dictionaries - variable of variables
# # - Objects - super dictionaries
# # Primitive Data tyes = string, number, boolean
# month = "November";
# print type(month)
# date = 13
# print type(date)
# dateAsFloat = 13.0
# print type(dateAsFloat)
# aBool = True
# print type(aBool)
# aList = []
# print type(aList)
# aDictionary = {}
# print type(aDictionary)
# # concatenate is programming speak for add things together
# first = "Robert"
# last = "Bunch"
# fullName = first + last;
# fullName = first + " " + last;
# print fullName
# fourteen = 10 + 4
# print fourteen
# fourteen = "10" + "4"
# print fourteen
# # fourteen = 10 + "4"
# # print fourteen
# # cast = change a variable to a new data type
# fourteen = int("10") + 4
# fourteen = int("ten") + 4
# Math = +, -, /, *, %
# print 2+2
# print 2-2
# print 2/2
# print 2*2
# # % = modulus. Moudulus divides the number and gives you the remainder
# print 2%2
# print 2%3
# print 2**3
# print 10**87
# A string and a * and a number = give me X strings
# print "--" * 20
# print "Rob"**20+" The world already has too many Robs"
# Python does not have a simple incrementer
num = 1;
# num++
num += 1
# C
# C++
# Input
# Python 2 = raw_input
# Python 3 = input
# name = raw_input("What is your name? ")
# print type(name)
# conditionals
# a single = sign, means set the left to whateer is on the right
# two = signs, means compare what's on the left, to wahtever is on the right
print 2 == 2
print 2 == 1
print 2 == "2"
secret_number = 5;
if(secret_number == 3):
print "Secret number is 3";
else:
print "Secret number is not 3.";
game_on = True;
i = 0;
# while(game_on):
while(game_on == True):
i+= 1
if(i == 10):
game_on = False
else:
print "Game on!!"
print "Loop exited!" | true |
e50f64e8a117186ebf66b550df6e7a7802b7bdfd | rbunch-dc/11-18immersivePython101 | /dictionaries.py | 1,559 | 4.21875 | 4 | # DICTIONARIES
# Dictionaries are just like lists
# Except... instead of numbered indicies, they
# have English indicies
greg = [
"Greg",
"Male",
"Tall",
"Developer"
]
# If I wanted to know Greg's job, I have to do greg[3]
# No one is going to expect that
# A dictionary is like a list of variables
name = "Greg"
gender = "Male"
height = "Tall"
job = "Developer"
# Key:value pair
greg = {
"name": "Greg",
"gender": "Male",
"height": "Tall",
"Job": "Developer"
}
# print greg["name"]
# print greg["Job"]
# Make a new dictionary
zombie = {} #dictionary
zombies = [] #list
# zombies.append()
zombie['weapon'] = "fist"
zombie['health'] = 100
zombie['speed1'] = 10
print zombie
print zombie['weapon']
for key,value in zombie.items():
print "Zombie has a key of %s with a value of %s" % (key, value)
# in our game, poor zombie loses his weapon (arm falls off)
# we need to remove his "weapon" key
del zombie['weapon']
print zombie
is_nighttime = True
if(is_nighttime):
zombie['health'] += 50
# Put lists and dictionaries together!!!
zombies = []
zombies.append({
'name': 'Hank',
'weapon': 'baseball bat',
'speed': 10
})
zombies.append({
'name': 'Willie',
'weapon': 'axe',
'speed': 3,
'victims': [
'squirrel',
'rabbit',
'racoon'
]
})
# this will get the first zombie in zombies weapon
print zombies[0]['weapon']
# this will get the second victim, in the second zomnbies list of victims
print zombies[1]['victims'][1]
# if we wante to know, zombie1's weapon:
| true |
c59556760fce2bdb2cc045b411aebf78e8214b3a | mesaye85/Calc-with-python-intro- | /calc.py | 1,171 | 4.21875 | 4 | def print_menu():
print("-"* 20)
print(" python Calc")
print("-"* 20)
print("[1] add ")
print("[2] subtract")
print("[3] multiply")
print('[4] Division')
print("[5] My age")
print('[x] Close')
opc = ''
while( opc!= 'x'):
print_menu()
opc = input('Please choose an option:')
num1 = float(input("First number:"))
num2 = float(input("Second number:"))
age = int(input("Your Date of Birth"))
if(opc == '1'):
res = float(num1) + float(num2)
print("Result: " + str(res))
elif (opc == '2'):
res = float(num1) - float(num2)
print("Result: " + str(res))
elif (opc == '3'):
res = float(num1) * float(num2)
print("Result: " + str(res))
elif (opc == '4'):
if (num2 == 0):
print("Don't divide by zero, y will kill us ALL")
else:
res = float(num1) / float(num2)
print("Result: " + str(res))
elif (opc == '5'):
res = (2020) - int(age)
print("Your age is " + str(res))
else:
print("Invalid option, please choose a valid option")
print('Good bye!')
| true |
b65280021b7397d9f85e81ea974600001c8908c1 | posguy99/comp660-fall2020 | /src/M4_future_value_calculator.py | 1,229 | 4.34375 | 4 | #!/usr/bin/env python3
def calculate_future_value(monthly_investment, yearly_interest_rate, years):
monthly_interest_rate = yearly_interest_rate / 12 / 100
months = years * 12
future_value = 0
for i in range(0, months):
future_value += monthly_investment
monthly_interest_amount = future_value * monthly_interest_rate
future_value += monthly_interest_amount
return future_value
def main():
print('Welcome to the Future Value Calculator\n')
# potted choice to make the first pass through the loop work
# _while_ evaluates at the *top* of the loop
choice = 'y'
while choice == 'y':
monthly_investment = float(input('enter your monthly investment:\t'))
yearly_interest_rate = float(input('Enter yearly interest rate:\t'))
years = int(input('Enter number of years:\t\t'))
future_value = calculate_future_value(monthly_investment, yearly_interest_rate, years)
print('Future value:\t\t\t' + str(round(future_value,2)))
# chose to continue at the bottom of the loop...
choice = input('Continue? (y or n)\t\t')
print('Thank you for using the Future Value Calculator')
if __name__ == '__main__':
main()
| true |
1c8c6473e7fe467a4e21bb6707b54ea154764777 | posguy99/comp660-fall2020 | /src/Module 2 Assignment 3.py | 672 | 4.34375 | 4 | #!/usr/bin/env python3
kg_to_lb = 2.20462
earth_grav = 9.807 # m/s^2
moon_grav = 1.62 # m/s^2
mass = float(input("Please enter the mass in lb that you would like to convert to kg: "))
kg = mass / kg_to_lb
print("The converted mass in kg is:", kg)
print("Your weight on Earth is:", kg*earth_grav, "Newtons")
print("Your weight on the Moon is:", kg*moon_grav, "Newtons")
print("The percentage of the weight on the Moon in comparison to what is experienced on Earth:", (kg*moon_grav)/(kg*earth_grav)*100, "%")
print("The percentage of the weight on the Moon in comparison to what is experienced on Earth as an integer:", round((kg*moon_grav)/(kg*earth_grav)*100), "%")
| true |
190bbbc26dd2db956d03a7dbcf9b2edc27bd8599 | posguy99/comp660-fall2020 | /src/M6_Exercise.py | 1,052 | 4.1875 | 4 |
# string traversal
fruit = 'Apple'
# print forwards
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
# exercise 1 - print in reverse
index = len(fruit)
while index:
letter = fruit[index - 1] # because slice is zero-based
print(letter)
index = index - 1
# exercise 2 - what is [:]
print(fruit[:])
# exercise 3 -
def countem(word, char):
count = 0
for i in range(len(word)):
if word[i] == char:
count = count + 1
return count
print(countem(fruit, 'p'))
# **Exercise 4: There is a string method called count that is similar to the
# function in the previous exercise. Read the documentation of this method at:
# Write an invocation that counts the number of times the letter a occurs in
# “banana”.*
print(fruit.count('p'))
# exercise 5 -
str = 'X-DSPAM-Confidence:0.8475'
loc = int(str.find(':')) + 1 # get to char after the colon
score = float(str[loc : ]) # from after the colon to the end
print('score: ', score)
| true |
2d52aa2d9101714688f9bbd6498c17a10e7def6d | Pavan1511/python-program-files | /python programs/data wise notes/29 april/default dict ex3.py | 797 | 4.1875 | 4 | #Program: 3 returning a default value if key is not present in defaultdict
# creating a defaultdict
# control flow --> 1
from collections import defaultdict
# control flow --> 5
def creating_defaultdict():
student = defaultdict(func) # ----> invoke func() ---> 8
print(type(student))
student['usn'] = '1rn16scs18'
student['name'] = 'Arjun'
student['cgpa'] = 7.5
print(student)
print(student['name']) # Arjun
print(student['sem']) # 8 ##control flow --> 7
# control flow --> 6
def func():
return 8
# control flow --> 4
def main():
creating_defaultdict() # control flow --> 8
# control flow --> 2
if __name__ == "__main__":
main() # control flow --> 3
# control flow --> 9
# control flow --> 10 ---os
| true |
ab2d92b7e16305d3ce343c6926e3cce6508959e2 | EricWWright/PythonClassStuff | /aThing.py | 1,369 | 4.125 | 4 | # print("this is a string")
# name = "Eric"
# print(type(name))
# fact = "my favorite game is GTA 5"
# print("my name is " + name + " and I like " + fact)
# # or
# print("my name is ", name, " and i like ", fact)
# # or
# message = "my name is " + name + " and I like " + fact
# print(message)
# # vars
# num = 8
# num2 = 14
# print(num+num2)
# answer = num - num2
# print(answer)
# # vars
# word = "sweet"
# word1 = "cool"
# word2 = "mean"
# word3 = "dark"
# word4 = "mate"
# print("I took a sip of " + word + " tea that was nice and " + word1 + ". With my " + word + " " + word1 + " tea I ate a " + word2 +
# " steak that was cooked to perfection. It started to get " + word3 + " so me and my " + word4 + " decided to call it a night.")
# update vars to inputs
word = input("Type an adjective ")
word1 = input("Type a name ")
word2 = input("Type another name ")
word3 = input("Type a weapon ")
word4 = input("Type another weapon ")
# new madlib
print("On a " + word + " night " + word1 + " was angerd at " + word2 + " because " + word2 + " wasn't being really nice. " + word1 + " decided to pickup a " + word3 +
" and proceed to hit " + word2 + " with it. But " + word2 + " didn't like that so " + word2 + " decided to pick up a " + word4 + " and fight " + word1 + " with it. In an epic battle to the death " + word1 + " was victorious.")
input()
| true |
362394abdf87008e69007c7268050b4397e57a08 | hkam0323/MIT-6.0001 | /Problem set 4a - Permutations.py | 1,980 | 4.5 | 4 | def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
# List of possible permutations
permutation = []
# Base case: If only 1 char, return itself (permutation of 1 char is 1 char)
if len(sequence) == 1:
return ([sequence])
# Recursive case: Find all the different ways to insert first character into
# each permutation of remaining characters
else:
first_char = sequence[0]
remaining_char = sequence[1:]
remaining_char_permutations = get_permutations(remaining_char)
# Adds first_char into remaining_char_permutations
for r in remaining_char_permutations: # r = bc, cb
# Adds first_char to first and last position of remaining_char_permutations
permutation.append(first_char + r) # a, bc
permutation.append(r + first_char) # bc, a
# Adds first_char to all other positions in remaining_char_permutations
for i in range(1, len(r)): # eg. bcd = len 3 --> i = 1, 2
add_permutation = ""
add_permutation += r[0:i] + first_char + r[i:]
permutation.append(add_permutation)
return (permutation)
if __name__ == '__main__':
example_input = 'abc'
print('Input:', example_input)
print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
print('Actual Output:', get_permutations(example_input))
| true |
4dd880f4f2423a147bbeb86ff4d7ad545d0b6513 | baksoy/WebpageScraper | /WebpageScraper.py | 1,155 | 4.15625 | 4 | import urllib2
from bs4 import BeautifulSoup
website = urllib2.urlopen('https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)').read()
# print website
# html_doc = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title"><b>The Dormouse's story</b></p>
#
# <p class="story">Once upon a time there were three little sisters; and their names were
# <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
# <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
# <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
# and they lived at the bottom of a well.</p>
#
# <p class="story">...</p>
# """
#
soup = BeautifulSoup(website, 'html.parser')
# print (soup.prettify())
# print soup.title.string
# print soup.h1.span.string
# print soup.h2.span.string
# for link in soup.find_all('a'):
# print (link.get('href'))
# Extract all text from a web page
# print(soup.get_text())
for link in soup.find_all('a'):
print ("===============")
print (link.string)
print (link.get('href'))
print ("===============")
print (" ")
| true |
44ad837a03b617202d6417f71b911cd4ab5f9add | dpkenna/PracticePython | /Exercise 6.py | 254 | 4.1875 | 4 | # http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
maypal = input('Enter a string: ')
backwise = maypal[::-1]
if maypal == backwise:
print('{} is a palindrome'.format(maypal))
else:
print('{} is not a palindrome'.format(maypal)) | true |
7147f9ddac28af4a1faeec6ff3eb5c01d8353e78 | rmccorm4/BHSDemo.github.io | /rand.py | 246 | 4.1875 | 4 | #Game to guess a number between 1-10, or any range you choose
import random
number = str(random.randint(1, 10))
guess = input("Guess a number between 1 and 10: ")
print(number)
if guess == number:
print("You won!")
else:
print("You lost!")
| true |
d7f536b5654e29a431238f19f3b8efcc93c35440 | AshaS1999/ASHA_S_rmca_s1_A | /ASHA_PYTHON/3-2-2021/q3sum of list.py | 224 | 4.125 | 4 | sum = 0
input_string = input("Enter a list element separated by space ")
list = input_string.split()
print("Calculating sum of element of input list")
sum = 0
for num in list:
sum += int (num)
print("Sum = ",sum) | true |
48dcf7ecbe7d8761756704c15b08f729520ffdb4 | joshuastay/Basic-Login-Code | /login.py | 2,942 | 4.3125 | 4 | import re
class LoginCredentials:
"""
Simple login authentication program
includes a method to create a new user
stores values in a dictionary
"""
def __init__(self):
self.login_dict = dict()
self.status = 1
# method to check if the password meets parameters
def check_pass(self, entry):
check_upper = False
check_lower = False
check_length = False
check_int = False
check_spec = False
for each in entry:
if each.islower() is True:
check_lower = True
else:
continue
for each in entry:
if each.isupper() is True:
check_upper = True
else:
continue
if re.search("\d", entry):
check_int = True
if len(entry) >= 8 and len(entry) <= 20:
check_length = True
if re.search("[!, @, #, $, %]", entry):
check_spec = True
if check_spec and check_length and check_int and check_upper and check_lower:
return True
else:
return False
# new_login prompts user for a new username and password and stores values in the dictionary
def new_login(self):
make_user = True
make_pass = True
while make_user is True:
print("Enter a new username (limit 25 characters, no spaces) ")
username = input("Username: ")
if len(username) > 25 or username.count(" ") > 0:
print("Invalid Username!")
continue
elif username in self.login_dict.keys():
print('Username in use!')
continue
make_user = False
while make_pass is True:
print("Enter a new password (atleast 8 characters, limit 20. Must include lowercase, uppercase, numbers and"
" a special character !, @, #, $, %")
password = input("Enter new password: ")
passvalid = self.check_pass(password)
if passvalid:
self.login_dict[username] = password
break
else:
print("Password Invalid!")
continue
# login method checks the dictionary for a matching username and password
def login(self):
username = input("Username: ")
if self.login_dict.get(username) is not None:
attempts = 3
while attempts > 0:
password = input("Password: ")
if self.login_dict[username] == password:
print("Login Successful!")
break
else:
attempts -= 1
print("Login Failed! attempts remaining: ", attempts)
else:
print("Unrecognized Username!")
| true |
122addb28d5f13854eca172d0be609d3369bea70 | Combatd/Intro_to_Algorithms_CS215 | /social_network_magic_trick/stepsfornaive.py | 470 | 4.1875 | 4 | # counting steps in naive as a function of a
def naive(a, b):
x = a
y = b
z = 0
while x > 0:
z = z + y
x = x - 1
return z
'''
until x (based on value of a) gets to 0, it runs 2 things in loop.
2a
we have to assign the values of 3 variables
3
'''
def time(a):
# The number of steps it takes to execute naive(a, b)
# as a function of a
steps = 0
# your code here
steps = 2 * a + 3
return steps | true |
ce1a001e3dde4aa6bb413ad884cea077d526ecfc | StephTech1/Palindrome | /main.py | 341 | 4.28125 | 4 | #Add title to code
print ("Is your word a Palindrome?")
#Ask user for word
input = str(input("What is your word?"))
palin = input
#create a function to check if a string is reversed
#end to beginning counting down by 1
if palin == palin [::-1] :
#print answers based on input
print("Yes!")
else:
print("No!")
print("Thanks for playing!") | true |
ecacdeb6cd2c390e04e834191197100135c3d374 | convex1/data-science-commons | /Python/filter_operations.py | 2,074 | 4.1875 | 4 | import pandas as pd
import numpy as np
"""
create dummy dataframe about dragon ball z characters earth location and other information
"""
data = {"name": ["goku", "gohan"], "power": [200, 400], city": ["NY", "SEA"]}
dragon_ball_on_earth = pd.DataFrame(data=data)
"""
~~ABOUT~~
Use vectorization instead of using for loops to assign new values.
You can use them to filter values easily. Try to do it whenever possible.
It will be possible in most cases except a few minor complicated cases where for loop might be required.
Vector operation is better than Scala operations.
"""
"""
Common filter values:
These are some common ways to filter your dataframe
"""
dragon_ball_on_earth[dragon_ball_on_earth['name'] == "goku"]
dragon_ball_on_earth[dragon_ball_on_earth['name'].isnull()]
dragon_ball_on_earth[dragon_ball_on_earth['name'].notnull()]
dragon_ball_on_earth[dragon_ball_on_earth['name'].isna()]
dragon_ball_on_earth[dragon_ball_on_earth['name'] < "a"]
"""
create new series (column) by using vectorization
there is one single condition and one single outcome except the default
"""
dragon_ball_on_earth['is_goku'] = np.where(dragon_ball_on_earth['name'] == "goku", 1, 0)
characters_with_power_100_or_more = np.where((dragon_ball_on_earth['name'].notnull()) & (dragon_ball_on_earth['power'] > 100), 1, 0)
#you can also just get the indices of the rows that satisfy your condition
dataframe_indices = np.where(dragon_ball_on_earth['name'] == "goku")
"""
How to assign the series column based on multiple conditions?
Use np.select() instead of np.where()
np.select() can take multiple conditions and multiple outcomes
"""
conditions =[[dragon_ball_on_earth['name'] == "goku"],
[dragon_ball_on_earth['name'] == "gohan"],
[dragon_ball_on_earth['power_level'].isin([100, 200, 400])]]
outcomes = [1,2]
#conditions and outcomes are from the assigned variables above
#zero below is the default value to be assigned in case the conditions are not satisfied
dragon_ball_on_earth['coded_name'] = np.select(conditions, outcomes, 0)
| true |
530de8ff2ed5d46e819d098591c2deb56e081623 | Psuedomonas/Learn-Python-3 | /Strings.py | 508 | 4.15625 | 4 | str1 = '''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
str2 = 'What\'s your name?'
str3 = "What's your name?"
str4 = "This is the first sentence.\
This is the second sentence."
str5 = '''Yubba dubba. \n The grass is greener \t after the rain.'''
print(str1, str2, str3, str4, str5)
age = 25
name = 'Sawroop'
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
| true |
e8b37ca27deb3bc5997c06b9d840ddb5239edc63 | reidpat/GeeringUp | /oop.py | 809 | 4.125 | 4 | # creates a class
class Dog:
# ALL dogs are good
good = True
# runs when each "Dog" (member of Class) is created
def __init__ (self, name, age):
self.name = name
self.age = age
self.fed = False
# function exclusive to Dog
def bark(self):
print(self.name + " starts to bark!")
# create a function outside of class
def feed(dog):
dog.fed = True
def isDogFed(dog):
if (dog.fed == True):
return True
elif (dog.fed == False):
return False
else:
# how do we get here?
print("Dog is confused.")
# return dog.fed
# ----------- create some dogs -------------------
doggo = Dog("Bowser", "7")
# b = Dog()
# ----------- play with our dogs! ----------------
doggo.bark()
# bark()
print(isDogFed(doggo))
feed(doggo)
print(isDogFed(doggo))
print(doggo.good)
| true |
0b07faeed17c71745c16e7131ddcc19bca79dd7b | yeeshenhao/Web | /2011-T1 Python/yeesh_p02/yeesh_p02_q06.py | 609 | 4.59375 | 5 | ## Filename: yeesh_p02_q06.py
## Name: Yee Shen Hao
## Description: Write a program that sorts three integers. The integers are entered from standard input and
##stored in variables num1, num2, and num3, respectively. The program sorts the numbers
##so that num1 > num2 > num3. The result is displayed as a sorted list in descending order
# User input
num1 = int(input("Enter 1st integer:"))
num2 = int(input("Enter 2nd integer:"))
num3 = int(input("Enter 3rd integer:"))
#Create list
sort = [num1,num2,num3]
#Print
print("In descending order:", sorted(sort, reverse=True))
end = input("Press ENTER to exit")
| true |
a26f57626165a2dec8c1ab86e68d862d6e1639f3 | UgeneGorelik/Python_Advanced | /ContexManagerStudy.py | 1,623 | 4.40625 | 4 | from sqlite3 import connect
#with means in the below example:
#open file and close file when done
#means with keyword means start with something
#and in the end end with something
with open('tst.txt') as f:
pass
#we declare a class that will runn using context manager type implementation
class temptable:
def __init__(self,cur):
self.cur=cur
#this will happen on instantiating the class
def __enter__(self):
print("__enter__")
#sqllite create table
self.cur.execute('create table points(x int, y int)')
#this happen when instantation ends
def __exit__(self, exc_type, exc_val, exc_tb):
print("_exit_")
#sqllite drop table
self.cur.execute('drop table points')
with connect('test.db') as conn:
#declare Sqllite cursor for running DB queries
cur = conn.cursor()
#here we start instantiationg the temptable class so __enter__ from the temptable class will run
with temptable(cur):
#run insert to DB query
cur.execute('insert into points (x, y) values(1, 1)')
cur.execute('insert into points (x, y) values(1, 2)')
cur.execute('insert into points (x, y) values(2, 1)')
cur.execute('insert into points (x, y) values(2, 2)')
# run select to DB query
for row in cur.execute("select x, y from points"):
print(row)
for row in cur.execute('select sum(x * y) from points'):
print(row)
# here we end instantiationg the temptable class so exit from the temptable class will run | true |
5e28de8f0613ba5ae0f50dc0c019c8716e6e4e09 | mdimovich/PythonCode | /Old Tutorial Code/pythonTut27 (Recursion).py | 602 | 4.1875 | 4 | # Recursive Functions in Python
# Recursive Factorial Function
def factorial(num):
if num <= 1:
return 1
else:
result = num * factorial(num-1)
return result
print(factorial(4))
# 1, 1, 2, 3, 5, 8, 13
# Fibonacci Sequence: Fn = Fn-1 + Fn-2
# Where F0 = 0 and F1 = 1
def fibonacci(num):
if num == 0:
return 0;
elif num == 1:
return 1;
else:
result = fibonacci(num-1)+fibonacci(num-2)
return result
amount = int(input("Enter the numer of fibonacci numbers you want: "))
for i in range(1, amount+1):
print(fibonacci(i))
| true |
e0a3095c64fd1e4fddb49f2dff25ef0b1b829e04 | mdimovich/PythonCode | /Old Tutorial Code/pythonTut4.py | 737 | 4.34375 | 4 | #Enter Calculation: 5 * 6
# 5*6 = 30
#Store the user input of 2 numbers and the operator of choice
num1, operator, num2 = input("Enter Calculation ").split()
#Convert the strings into integers
num1 = int(num1)
num2 = int(num2)
# if + then we need to provide output based on addition
#Print result
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-":
print("{} - {} = {}".format(num1,num2,num1-num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1,num2, num1/num2))
elif operator == "%":
print("{} % {} = {}".format(num1,num2, num1%num2))
else:
print("Use either + - * / or % next time")
| true |
1730623fc10aa70a47b2e1cc3fe5aa42ac08ee59 | mdimovich/PythonCode | /Old Tutorial Code/pythonTut3.py | 328 | 4.25 | 4 | #Problem: Receive Miles and Convert To Kilometers
#km = miles * 1.60934
#Enter Miles, Output 5 Miles Equals 8.04 Kilometers
miles = input ("Enter Miles: ")
#Convert miles to integer
miles = int(miles)
#Kilometer Equation
kilometers = miles * 1.60934
#Data Output
print("{} Miles equals {} Kilometers".format(miles, kilometers)) | true |
5956dee8f7bd60bfcddd0f74bd487ae132c70547 | devSubho51347/Python-Ds-Algo-Problems | /Linked list/Segrate even and odd nodes in a linked list.py | 1,884 | 4.125 | 4 | ## Creation of a node of linked list
class Node:
def __init__(self,data):
self.data = data
self.next = None
# Method to create the linked list
def create_linked_list(arr):
head = None
tail = None
for ele in arr:
newNode = Node(ele)
if head is None:
head = newNode
tail = newNode
else:
tail.next = newNode
tail = newNode
return head
# Method to print the linked list
def print_linked_list(head):
while head is not None:
if head.next is None:
print(head.data)
break
else:
print(head.data, end = " ->")
head = head.next
def sort_even_odds(head):
first_odd_node = None
prev_even_node = None
head1 = head
if head.next is None:
return head
if head1.data % 2 != 0:
first_odd_node = head1
prev = None
current = None
while head.next is not None:
prev = head
current = prev.next
if (current.data % 2 != 0) and (prev.data % 2 == 0):
prev_even_node = prev
first_odd_node = current
head = head.next
elif (prev.data % 2 != 0) and (current.data % 2 == 0):
if head1.data % 2 != 0:
prev.next = current.next
current.next = first_odd_node
head1 = current
prev_even_node = current
else:
prev.next = current.next
current.next = first_odd_node
prev_even_node.next = current
prev_even_node = current
else:
head = head.next
return head1
arr = [int(x) for x in input().split()]
head = create_linked_list(arr)
print_linked_list(head)
new_head = sort_even_odds(head)
print("Even and Odd Linked List")
print_linked_list(new_head) | true |
aeae7d9948ca357f80b8c955e078b3f8dd227677 | devSubho51347/Python-Ds-Algo-Problems | /Linked list/AppendLastNToFirst.py | 1,644 | 4.1875 | 4 | # Description
'''
You have been given a singly linked list of integer
along with an integer 'N'. Write a function to append the last 'N'
nodes towards the front of the singly linked list and returns
the new head to the list.
'''
# Solved question using two pointer approach
def AppendLastToFirst(head,n):
ptr1 = head
ptr2 = head
head1 = head
head2 = head
while head.next is not None:
if n > 0:
ptr1 = head.next
head = head.next
n = n - 1
elif n == 0:
ptr1 = head.next
ptr2 = head1.next
head = head.next
head1 = head1.next
if n > 0:
return head2
ptr1.next = head2
head = ptr2.next
ptr2.next = None
return head
class Node:
def __init__(self,data):
self.data = data
self.next = None
# Method to create the linked list
def create_linked_list(arr):
head = None
tail = None
for ele in arr:
newNode = Node(ele)
if head is None:
head = newNode
tail = newNode
else:
tail.next = newNode
tail = newNode
return head
# Method to print the linked list
def print_linked_list(head):
while head is not None:
if head.next is None:
print(head.data)
break
else:
print(head.data, end = " ->")
head = head.next
arr = [int(x) for x in input().split()]
n = int(input())
head = create_linked_list(arr)
print_linked_list(head)
print("New Linked List")
new_head = AppendLastToFirst(head,n)
print_linked_list(new_head)
| true |
559618c6a03eb8547eed2891b4ac7ed038e92b3b | KhadijaAbbasi/python-program-to-take-input-from-user-and-add-into-tuple | /tuple.py | 244 | 4.15625 | 4 | tuple_items = ()
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
user_input = int(input("Enter a number: "))
tuple_items += (user_input,)
print(f"Items added to tuple are {tuple_items}")
| true |
4472c1ba6c824fb9021d05ef985d4394cc6a61f9 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/7_collections/practise/pr_3.py | 1,452 | 4.59375 | 5 | #
#
# Buffet: A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple.
#
# Use a for loop to print each food the restaurant offers.
# Try to modify one of the items, and make sure that Python rejects the change.
# The restaurant changes its menu, replacing two of the items with different foods.
# Add a block of code that rewrites the tuple, and then use a for loop to print each of the items on the revised menu.
# Use slicing for get last two items of foods.
# Use slicing for get every second item of food.
# Reverse your food order.
#
# Done
buffet_style = ('meat', 'fish', 'potatoes', 'pizza', 'dessert')
for dishes in buffet_style:
print(f'{dishes}')
########################################################
# Try to modify
# buffet_style[1] = ('sea fish')
# print(buffet_style)
#########################################################
# changes menu
new_menu = list(buffet_style)
new_menu[0] = 'chicken', 'makarones'
print(tuple(new_menu))
#########################################################
# rewrites the tuple
buffet_style = new_menu
print('New menu', buffet_style)
for menu in buffet_style:
print('New menu Done', menu)
#########################################################
# Use slicing
print(buffet_style[-2:])
#########################################################
# Reverse your food order
print(buffet_style[::-1])
| true |
1944dfdcadc11363e212ae18c4703f0fdf0e6e85 | YuriiKhomych/ITEA-BC | /Vlad_Hytun/8_files/HW/HW81_Hytun.py | 1,509 | 4.59375 | 5 | # 1. According to Wikipedia, a semordnilap is a word or phrase that spells
# a different word or phrase backwards. ("Semordnilap" is itself
# "palindromes" spelled backwards.)
# Write a semordnilap recogniser that accepts a file name (pointing to a list of words)
# from the program arguments and finds
# and prints all pairs of words that are semordnilaps to the screen.
# For example, if "stressed" and "desserts" is part of the word list, the
# the output should include the pair "stressed desserts". Note, by the way,
# that each pair by itself forms a palindrome!
import codecs
import re
filename = 'polindrome frases.txt'
def semordnilap(filename):
with codecs.open(filename, 'r', encoding='utf-8') as file_obj:
cashe_data = file_obj.readlines()
# print(cashe_data)
with codecs.open(f'{filename}_check.', 'w+', encoding='utf-8') as file_obj2:
# print(cashe_data)
# print(cashe_data2)
for line in cashe_data:
if line.strip().replace(' ', '').lower()[:len(line.strip().replace(' ', ''))//2] !=\
line.strip().replace(' ', '').lower()[:len(line.strip().replace(' ', ''))//2:-1]:
# print(f'{line.rstrip()} --- It is NOT semordnilap!')
file_obj2.writelines(f'{line.rstrip()} --- It is NOT semordnilap!\n')
else:
# print(f'{line.rstrip()} --- It is semordnilap!')
file_obj2.writelines(f'{line.rstrip()} --- It is semordnilap!\n')
semordnilap(filename)
| true |
0d5c313729151e7a85b242ac9c962fde609e3ddf | YuriiKhomych/ITEA-BC | /Vlad_Hytun/5_functions/practise/P52-Hytun_Vlad.py | 330 | 4.1875 | 4 | # 2. Define a function that computes the length of a
# given list or string. (It is true that Python has
# the len() function built in, but writing it yourself
# is nevertheless a good exercise.)
def my_len(str):
count_symbol = 0
for i in str:
count_symbol += 1
return count_symbol
print(my_len('djfkdflk')) | true |
7182a3fc269c6e81fff77f6a66921c7469c6746b | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/7_collections/HW/hw_6.py | 726 | 4.34375 | 4 | #
#
# Pets: Make several dictionaries, where the name of each dictionary is the name of a pet.
#
# In each dictionary, include the kind of animal and the owner’s name.
# Store these dictionaries in a list called pets.
# Next, loop through your list and as you do print everything you know about each pet.
#
# DONE
chappy = {
'name': 'Chappy',
'kind': 'robot',
'owners': 'Sophi',
}
tom = {
'name': 'Tom',
'kind': 'yard cat',
'owners': 'Lina',
}
keks = {
'name': 'Keks',
'kind': 'toyteryer',
'owners': 'Sveta',
}
pets = [chappy, tom, keks]
for pet in pets:
print(f'We know about {pet["name"]}')
for key, value in pet.items():
print(f'{key} : {value}')
| true |
71c997605a5578583cd9de46f7bdbe283dd99ff4 | YuriiKhomych/ITEA-BC | /Sergey_Naumchick/5_functions/05_PR_03.py | 411 | 4.1875 | 4 | '''3. Write a function that takes a character (i.e. a
string of length 1) and returns True if it is a vowel,
False otherwise.'''
VOLVED = 'aeiouy'
my_input = ""
while len(my_input) != 1:
my_input = input("please input only one symbol: ")
def my_func(func):
if func in VOLVED:
return True
else:
return False
if (my_func(my_input))==True:
print("True")
else: print("False")
| true |
fdce28c8eb106cdcc1f205ac12a2f813a893aaeb | YuriiKhomych/ITEA-BC | /Patenko_Victoria/3_conditions/homework3.1.py | 2,979 | 4.25 | 4 | my_fav_brand = ["toyota", "audi", "land rover"]
my_fav_model = ["camry", "r8", "range rover"]
my_fav_color = ["blue", "black", "gray"]
price = 3000
brand: "str" = input("Brand of your car is: ")
if brand not in my_fav_brand:
print("Got it!")
else:
print("Good choice!")
price_1 = price + 100
model = input("Model of your car is: ")
if model not in my_fav_model:
print("As you wish")
else:
print("Good choice!")
price_2 = price_1 + 100
color = input("Color of your car is: ")
if color not in my_fav_color:
print("OK")
else:
print("Good choice!")
price_3 = price_2 + 100
try:
year = int(input("Year of your car is: "))
except ValueError as error:
print("Try again")
year = int(input("Year of your car is: "))
except Exception as error:
print(error)
else:
print("Good but let's try a bit older one")
finally:
year = year - 1
print("Year of your car is: ", year)
price_4 = price_3 + 100
try:
engine_volume = float(input("Engine volume of your car is: "))
except Exeption as error:
print(error)
engine_volume = int(input("Engine volume of your car is: "))
else:
engine_volume = engine_volume + 0.1
print("Maybe a bit more?")
print("Engine volume of your car is: ", engine_volume)
price_5 = price_4 + 100
odometer = int(input("Odometer of your car is: "))
if odometer < 1000:
print("Did you even use it?")
if odometer > 50000:
print("Wow! Such a traveler!")
if odometer >= 100000:
print("Don't know when to stop, huh?")
price_6 = price_5 + 100
phone_number = int(input("Your phone number: "))
print("Great! We'll call you!")
end_price = price_6 + 100
print("Let's sum up!")
print("Brand of your car is: ", brand)
print("Model of your car is: ", model)
print("Color of your car is: ", color)
print("Year of your car is: ", year)
print("Engine volume of your car is: ", engine_volume)
print("Odometer of your car is: ", odometer)
print("Price of the car is: ", end_price)
total_rating = [ ]
if brand == "toyota":
if model in my_fav_model and year == 2012:
total_rating.append("Exellent choice!")
elif model in my_fav_model and year <= 2012:
total_rating.append("Try somthing new")
elif model not in my_fav_model and year <= 2012:
total_rating.append("Would you like to change model?")
elif model not in my_fav_model and year >= 2012:
total_rating.append("Not bad")
elif model in my_fav_model and year >= 2012:
total_rating.append("Ha! We are on the same page!")
else:
total_rating.append("Could be better")
elif brand in my_fav_brand:
if model in my_fav_model and color in my_fav_color:
total_rating.append("Great choice!")
if model in my_fav_model and color not in my_fav_color:
total_rating.append("Well, that's nice too")
else:
total_rating.append("You could do better")
else:
total_rating.append("We sure have different taste")
print("Total rating: ", total_rating) | true |
80ef3072710719831cc6968b4d049e964b94faa4 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/7_collections/HW/hw_2.py | 1,823 | 4.375 | 4 | #
#
# My Pizzas, Your Pizzas: Make a copy of the list of pizzas, and call it friend_pizzas.
# Then, do the following:
#
# Add a new pizza to the original list. ########## Done
# Add a different pizza to the list friend_pizzas. ######### Done
# Prove that you have two separate lists.
#
# Print the message, My favorite pizzas are:, and then use a for
# loop to print the first list. ## Done
#
# Print the message, My friend’s favorite pizzas are:, and then use a
# for loop to print the second list. Make sure each new pizza is stored
# in the appropriate list.
#
# Done, maybe
friend_pizzas = {
'mix': 'all we have will be on your pizza',
'paperoni': 'paperoni, cheese, hot souse and tomatos',
'diablo': 'Salami, tomato sauce, sweet pepper and chilli',
}
pizzas = {
'mix': 'all we have will be on your pizza',
'paperoni': 'paperoni, cheese, hot souse and tomatos',
'diablo': 'Salami, tomato sauce, sweet pepper and chilli',
}
pizzas['four friends'] = 'Tomato sauce, mozzarella, bacon, hunting sausages, bogarsky pepper'
friend_pizzas['BBQ'] = 'BBQ sauce, mozzarella cheese, bacon, hunting sausages, smoked chicken'
print('Pizza friend_pizzas', friend_pizzas)
print('Pizza pizzas', pizzas)
for pizza in pizzas:
# favorite = input('Enter favorite pizzas: ').lower()
# if favorite in pizzas:
print(f'My friend’s favorite pizzas are - {pizza.title()}, ' f'the ingredients is {pizzas[pizza]}.')
# break
# else:
# print('Sorry ))')
for pizza in friend_pizzas:
# favorite = input('Enter favorite pizzas my friends: ').lower()
# if favorite in friend_pizzas:
print(f'My favorite is - {pizza.title()} pizza, ' f'the ingredients is {friend_pizzas[pizza]}.')
# break
# else:
# print('Sorry ))') | true |
14e5cd2b86f8e1df5ac05d69416b2a2455e3b47b | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/7_collections/practise/pr_1.py | 1,296 | 4.65625 | 5 | #
#
# Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza
# names in a list, and then use a for loop to print the name of each pizza.
#
# Modify your for loop to print a sentence using the name of the pizza
# instead of printing just the name of the pizza. For each pizza you should
# have one line of output containing a simple statement like: I like pepperoni pizza.
# Add a line at the end of your program, outside the for loop, that states
# how much you like pizza. The output should consist of three or more lines
# about the kinds of pizza you like and then an additional sentence, such as I really love pizza!
#
# pizzas = {
# 'vegetariana': 'Sous, royal cheese, tomatoes, corn, broccoli, green peppers, oregano',
# 'margherita': 'mozzarella cheese, fresh basil, salt and olive oil',
# 'diablo': 'Salami, tomato sauce, sweet pepper and chilli',
# }
#
# vegetariana = 'Sous, royal cheese, tomatoes, corn, broccoli, green peppers, oregano'
# margherita = 'mozzarella cheese, fresh basil, salt and olive oil'
# diablo = 'Salami, tomato sauce, sweet pepper and chilli'
favorite_pizza = ['vegetariana', 'margherita', 'diablo']
for pizz in favorite_pizza:
print(pizz)
print(f'Im so much love {favorite_pizza[2]} pizza')
| true |
2e6fe0e1de69caccd003f1de0d9e2d43562d254b | YuriiKhomych/ITEA-BC | /Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_4.py | 628 | 4.21875 | 4 | my_string = "AV is largest Analytics community of India"
# 4. Return first word from string.
# result: `AV`
my_string.split(' ')[0]
# 5. Return last word from string.
# result: `India`
my_string.split(' ')[-1]
# 6. Get two symbols of each word in string
# result: `['AV', 'is', 'la', 'An', 'co', 'of', 'In']`
my_string = "AV is largest Analytics community of India"
my_string_sep = my_string.split(' ')
new_string = []
for item in my_string_sep:
j = item[0:2]
new_string.append(j)
print(new_string)
my_string2 = 'Amit 34-3456 12-05-2007, XYZ 56-4532 11-11-2011, ABC 67-8945 12-01-2009'
# 7. Get date from string
| true |
85f79e9a11264fbecf65e7c7e41e7cf36bfdc7bc | YuriiKhomych/ITEA-BC | /Nemchynov_Artur/5_functions/Practise#5.1.py | 475 | 4.125 | 4 | # . Define a function `max()` that takes two numbers as arguments
# and returns the largest of them. Use the if-then-else construct
# available in Python. (It is true that Python has the `max()` function
# built in, but writing it yourself is nevertheless a good exercise.)"""
def max_in_list(lst):
max = 0
for n in lst:
if n > max:
max = n
return max
print(max_in_list([2,3,4,5,6,7,8,8,9,10]))
print(max_in_list([38,2,3,4]))
print(max_in_list([9,2,3,4,28])) | true |
598d6b24b64826bff334de88948e23abe3e01762 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/9_functional_programming/HW9/hw_1.py | 1,292 | 4.46875 | 4 | # The third person singular verb form in English is distinguished by the suffix
# -s, which is added to the stem of the infinitive form: run -> runs. A simple
# set of rules can be given as follows:
# If the verb ends in y, remove it and add ies If the verb ends in o, ch, s, sh,
# x or z, add es By default just add s Your task in this exercise is to define a
# function make_3sg_form() which given a verb in infinitive form returns its third
# person singular form. Test your function with words like try, brush, run and fix.
# Note however that the rules must be regarded as heuristic, in the sense that you
# must not expect them to work for all cases. Tip: Check out the string method endswith().
# DOne + test
# my_file = 'text_file/test.txt'
def singular(my_file):
text = open(my_file)
words = text.read().lower().split()
text.close()
sing_word = []
for word in words:
len_word = len(word)
if word.endswith('y'):
sing_word.append(str(word)[:(len_word-1)] + 'ies')
elif word.endswith(('o', 's', 'x', 'z')):
sing_word.append(str(word)[:(len_word - 1)] + 'es')
elif word.endswith(('ch', 'sh')):
sing_word.append(str(word)[:(len_word - 2)] + 'es')
return sing_word
# print(singular(my_file))
| true |
29b9026eeaf7d582b512ded6d6deb8ee3cf4da6d | YuriiKhomych/ITEA-BC | /Andrii_Bakhmach/4_iterations/4_3_exercise.py | 303 | 4.15625 | 4 | #Write a Python program that accepts a sequence of lines (blank line to terminate) as input
#and prints the lines as output (all characters in lower case).
our_line = input("please, input you text: ")
if our_line is None:
print("input your text once more")
else:
print(our_line.lower())
| true |
a3d0bef46700b4471601bc766aaf75d7e1c64cf7 | YuriiKhomych/ITEA-BC | /Vlad_Hytun/7_collections/practise/P75_Hytun.py | 804 | 4.90625 | 5 | # 5. Rivers:
# Make a dictionary containing three major rivers and the country each river runs through.
# One key-value pair might be `'nile': 'egypt'`.
# * Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
# * Use a loop to print the name of each river included in the dictionary.
# * Use a loop to print the name of each country included in the dictionary.
rivers_in_country = {
'Dnipro': 'Ukraine',
'Nile': 'Egypt',
'Dynai': 'Romain',
}
for river, country in rivers_in_country.items():
print(f'The {river} run through {country}')
for river in rivers_in_country.keys():
print(f'The {river} included in rivers_in_country dict')
for country in rivers_in_country.values():
print(f'The {country} included in rivers_in_country dict')
| true |
76cdeb563c3329f18ce11051aa902ca2a18f6bf7 | YuriiKhomych/ITEA-BC | /Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_3.py | 585 | 4.28125 | 4 | # 3. Define a function `overlapping()` that takes two lists and
# returns True if they have at least one member in common,
# False otherwise. You may use your `is_member()` function,
# or the in operator, but for the sake of the exercise,
# you should (also) write it using two nested for-loops.
a = (1, "a", "b", "c", 3, "x", "y", "z")
b = (2, "f", "g", "h", 4, "o", "p", "q")
c = (5, "i", "j", "k", 1, "s", "m", "o")
def overlapping(x,y):
for item_x in x:
for item_y in y:
if item_x == item_y:
return True
return False
overlapping(a,b)
| true |
fb85dfcc07245c05844294fc7bd12ff25175d642 | YuriiKhomych/ITEA-BC | /Andrii_Bakhmach/5_functions/HW/5_5_exercise.py | 488 | 4.15625 | 4 | #Write a function `is_member()` that takes a value
#i.e. a number, string, etc) x and a list of values a,
#and returns True if x is a member of a, False otherwise.
#(Note that this is exactly what the `in` operator does, but
#for the sake of the exercise you should pretend Python
#id not have this operator.)
def is_member():
list_a = input("Input a list of values: ").split()
x = input("Input a number: ")
if x in list_a:
return True
else:
return False
| true |
26673a4cb7762f89c06e0bb5dab3387415aabb75 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/4_iterations/practise2.py | 338 | 4.25 | 4 | # Write a Python program to count the number of even
# and odd numbers from a series of numbers.
number = int(input('Make your choice number: '))
even = 0
odd = 0
for i in range(number):
if i % 2 == 0:
even += 1
elif i % 2 != 0:
odd += 1
print(f'The odd numbers is {odd}')
print(f'The even numbers is {even}')
| true |
94cfe965059c1be0c455f78f4dd83c2b8df387f7 | YuriiKhomych/ITEA-BC | /Vlad_Hytun/7_collections/hw/HW74_Hytun.py | 632 | 4.1875 | 4 | # # Dictionary
# 4. Favorite Numbers:
# * Use a dictionary to store people’s favorite numbers.
# * Think of five names, and use them as keys in your dictionary.
# * Think of a favorite number for each person, and store each as a value in your dictionary.
# * Print each person’s name and their favorite number.
# * For even more fun, poll a few friends and get some actual data for your program.
favorite_numbers_dict = {
"Vlad": "13",
"Ksu": "26",
"Katya": "15",
"Den": "27",
"Dad": "01",
}
for name, number in favorite_numbers_dict.items():
print(f'One {name} like {number}')
| true |
84c50cc665fa7f67d2bbe261ce6c657a6adf8da1 | YuriiKhomych/ITEA-BC | /Andrii_Ravlyk/7_collections/practise/pr4_person.py | 440 | 4.21875 | 4 | '''4. Person:
* Use a dictionary to store information about a person you know.
* Store their first name, last name, age, and the city in which they live.
* You should have keys such as first_name, last_name, age, and city.
* Print each piece of information stored in your dictionary.'''
my_dict = {"first_name":"Anna", "last name":"Lee", "age":"21", "city":"Kyiv"}
for key in my_dict.keys():
print (f'{my_dict[key]}')
| true |
73bb85c2b0ddb1b71fd7d9495dee92ff2afa1a22 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/9_functional_programming/HW9/hw_2.py | 1,325 | 4.375 | 4 | # In English, the present participle is formed by adding the suffix -ing
# to the infinite form: go -> going. A simple set of heuristic rules can
# be given as follows: If the verb ends in e, drop the e and add ing
# (if not exception: be, see, flee, knee, etc.)
# If the verb ends in ie, change ie to y and add ing For words consisting of consonant-vowel-consonant,
# double the final letter before adding ing By default just add ing Your task in
# this exercise is to define a function make_ing_form() which given a verb in
# infinitive form returns its present participle form.
# Test your function with words such as lie, see, move and hug.
# However, you must not expect such simple rules to work for all cases.
# Done + test
from hw_3 import my_timer
# my_file = 'text_file/test.txt'
my_excaption = 'be, see, flee, knee'
@my_timer
def participle(my_file):
text = open(my_file)
words = text.read().lower().split()
text.close()
part_word = []
for word in words:
len_word = len(word)
if word not in my_excaption:
if word.endswith('ie'):
part_word.append(str(word)[:(len_word - 2)] + 'y' + 'ing')
elif word.endswith('e'):
part_word.append(str(word)[:(len_word - 1)] + 'ing')
return part_word
# print(participle(my_file)) | true |
3f2566abf3dc5144058177b9ed8ec52799b9fd87 | YuriiKhomych/ITEA-BC | /Sergii_Davydenko/4_iterations/practise1.py | 224 | 4.1875 | 4 | # Write a Python program that prints all the numbers from 0 to 6 except 3 and 6.
# Note : Use 'continue' statement.
# Expected Output : 0 1 2 4 5
for i in range(0, 6):
if i == 3:
continue
print(i, end=", ")
| true |
2edb0b06caf01ff2ec134e1f8589b12ecc867fe6 | YuriiKhomych/ITEA-BC | /Sergey_Naumchick/7_Collections/PR/PR_07_05.py | 710 | 4.90625 | 5 | '''5. Rivers:
Make a dictionary containing three major rivers and the country each river runs through.
One key-value pair might be `'nile': 'egypt'`.
* Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
* Use a loop to print the name of each river included in the dictionary.
* Use a loop to print the name of each country included in the dictionary.'''
dict_rivers = {"Nile": "Egipt", "Don": "Ukraine", "Syrdarya": "Tajikistan"}
for country, river in dict_rivers.items():
print(f"The {country} runs throught {river}")
print()
for key_river in dict_rivers.keys():
print(key_river)
print()
for river, country in dict_rivers.items():
print(country)
| true |
e6bc0f5408a6c4bcccf6c5ab27cf8539c595d08a | shailesh/angle_btwn_hrs_min | /angle_btw_hrs_min.py | 713 | 4.15625 | 4 | def calcAngle(hour,minute):
# validating the inputs here
if (hour < 0 or minute < 0 or hour > 12 or minute > 60): print('Wrong input')
if (hour == 12): hour = 0
if (minute == 60): minute = 0
# Calculating the angles moved by hour and minute hands with reference to 12:00
hour_angle, minute_angle = 0.5 * (hour * 60 + minute), 6 * minute
# finding the difference between two angles
abs_angle = abs(hour_angle - minute_angle)
# Returning the smaller angle of two possible angles (min or max will not make much diff or no diff)
angle = min(360 - abs_angle, abs_angle)
return angle
# driver program
hour = 6
minute = 15
print('Angle ', calcAngle(hour,minute))
| true |
0021e305037992731bdc891d8d6bf4bd35d227bd | vwang0/causal_inference | /misc/pi_MC_simulation.py | 737 | 4.15625 | 4 | '''
Monte Carlo Simulation: pi
N: total number of darts
random.random() gives you a random floating point number in the range [0.0, 1.0)
(so including 0.0, but not including 1.0 which is also known as a semi-open range).
random.uniform(a, b) gives you a random floating point number in the range [a, b],
(where rounding may end up giving you b).
random.random() generates a random float uniformly in the semi-open range [0.0, 1.0)
random.uniform() generates a random float uniformly in the range [0.0, 1.0].
'''
import random
def simu_pi(N):
inside = 0
for i in range(N):
x = random.uniform(0,1)
y = random.uniform(0,1)
if (x**2+y**2)<=1:
inside +=1
pi = 4*inside/N
return pi
| true |
f391340953675e637a74ca5ac0473961f4e69b38 | yukikokurashima/Python-Practice | /Python3.2.py | 542 | 4.1875 | 4 | def calc_average(scores):
return sum(scores) / 5
def determine_grade(score):
if 90 <= score <= 100:
result = "A"
elif 80 <= score <= 89:
result = "B"
elif 70 <= score <= 79:
result = "C"
elif 60 <= score <= 69:
result = "D"
else:
result = "F"
return result
scores = []
for _ in range(5):
score = int(input("Please enter five test scores: "))
print("Letter Grade is:", determine_grade(score))
scores.append(score)
avg = calc_average(scores)
print("Average test scores:", avg, "Letter Grade is:", determine_grade(avg))
| true |
435b42c6946277df30947069bdf071ff21c60448 | yaksas443/SimplyPython | /days.py | 415 | 4.34375 | 4 | # Source: Understanding Computer Applications with BlueJ - X
# Accept number of days and display the result after converting it into number of years, number of months and the remaining number of days
days = int(raw_input("Enter number of days : "))
years = days / 365
rem = days % 365
months = rem / 30
rem = rem % 30
print "\nYears: " + str(years)
print "\nMonths: " + str(months)
print "\nDays: " + str(rem) | true |
b659ec2d05bbcc676a3a9eed647941edddb48601 | yaksas443/SimplyPython | /sumfactorial.py | 443 | 4.21875 | 4 | # Source: https://adriann.github.io/programming_problems.html
# Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
# To convert str to int use int()
# to concatenate int to str, first convert it to str
def sumFactorial(number):
count = 0
sum=0
for count in range(0,number):
sum = sum + count
return sum
num = raw_input ("Please enter a number: ")
print "Sum: " + str(sumFactorial(int(num)))
| true |
87fd6a86c8de17dbbcdedc073a6c5c7c4b19d396 | mariavarley/PythonExercises | /pyweek2.py | 428 | 4.15625 | 4 | #!/usr/bin/python
num = int(input("Please Enter a number\n"))
check = int(input("Please Enter a number to divide with\n"))
if num%4 == 0:
print("The number is divisible by 4")
elif num%2 == 0:
print("The number is an even number")
else:
print("The number is an odd number")
if num%check == 0:
print("The number, {0} divides into {1} evenly".format(check, num))
else:
print("These numbers do not divide evenly")
| true |
bca3a78b6ee4b68f4efc0ca71186e9299121bd90 | Sav1ors/labs | /Bubble_Sort.py | 384 | 4.15625 | 4 | def bubbleSort(list):
for passnum in range(len(list)-1,0,-1):
for i in range(passnum):
if list[i]>list[i+1]:
temp = list[i]
list[i] = list[i+1]
list[i+1] = temp
list = []
for i in range(int(input('Enter the number of list items\n'))):
list.append(int(input('Input elements\n')))
bubbleSort(list)
print(list) | true |
bfba95ff46cc7730d8736d352b900c4dd89d00c4 | mekhrimary/python3 | /countdown.py | 1,121 | 4.15625 | 4 | # Recursive function as a countdown
def main():
"""Run main function."""
number = get_number()
while number == 0:
number = get_number()
print('\nStart:')
countdown(number)
def get_number() -> int:
"""Input and check a number from 1 to 100."""
try:
num = int(input('Enter a positive integer from 1 to 100: '))
# if num is not in range 1-100, it will be reassignment = 0
if num <= 0:
print('Wrong value (your number <= 0), try again.')
num = 0
elif num > 100:
print('Wrong value (your number > 100), try again.')
num = 0
except ValueError:
# if exeption, num will be assignment = 0
print('Wrong value (not a number), try again.')
num = 0
finally:
# return num (num = 0 if not in range or exception)
return num
def countdown(n: int) -> None:
"""Run recursive function."""
if n == 1:
print('1\nDone!')
else:
print(n)
countdown(n - 1)
if __name__ == '__main__':
main()
| true |
fadc2a22e5db5f8b2887067699ee05c721328e7c | mekhrimary/python3 | /lettersstatsemma.py | 1,818 | 4.125 | 4 | # Use string.punctuation for other symbols (!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~)
import string
def main() -> None:
'''Run the main function-driver.'''
print('This program analyzes the use of letters in a passage')
print('from "Emma" by Jane Austen:\n')
print('Emma Woodhouse, handsome, clever, and rich, with a comfortable home')
print('and happy disposition, seemed to unite some of the best blessings of')
print('existence; and had lived nearly twenty-one years in the world with')
print('very little to distress or vex her [and so on]...')
# 1. Get a dictionary of text sentences.
text = input_text()
# 2. Analyze sentences and return a dictionary of lettes's usage.
stats = count_letters(text)
# 3. Print statistics
print_stats(stats)
def input_text() -> list:
'''Open file and return a text.'''
file_text = list()
with open('fromEmma.txt', 'r') as fin:
for line in fin:
file_text.append(line.strip())
return file_text
def count_letters(phrases: list) -> dict:
'''Counts a usage of every letter and return as a dictionary.'''
usage = dict()
punkts = string.punctuation + string.whitespace
for sentence in phrases:
for symbol in sentence:
if symbol not in punkts:
if symbol not in usage:
usage[symbol.lower()] = 1
else:
usage[symbol.lower()] += 1
return usage
def print_stats(usage: dict) -> None:
'''Print statistics sorted by letters.'''
letters = sorted(list(usage.keys()))
print('\nStatistics (letters in alphabetical order):')
for letter in letters:
print(f'\t{letter}: {usage[letter]:3d} times')
if __name__ == '__main__':
main()
| true |
6ee057f17a4b7b82142808545a47ae6b5d0cc2bf | leonlinsx/ABP-code | /Python-projects/crackle_pop.py | 682 | 4.3125 | 4 | '''
recurse application
Write a program that prints out the numbers 1 to 100 (inclusive).
If the number is divisible by 3, print Crackle instead of the number.
If it's divisible by 5, print Pop.
If it's divisible by both 3 and 5, print CracklePop.
You can use any language.
'''
class CracklePop:
def __init__(self):
pass
def main(self):
# from 1 to 100 (inclusive)
for i in range(1, 101):
# handle the both case first
if i % 3 == 0 and i % 5 == 0:
print("CracklePop")
elif i % 3 == 0:
print("Crackle")
elif i % 5 == 0:
print("Pop")
else:
print(i)
return None
crackle_pop = CracklePop()
crackle_pop.main()
| true |
6982b7b8cf932a3c9e59e5909c3dfd6d1d6716d0 | Ayush-1211/Python | /Advanced OOP/9. Polymorphism.py | 1,130 | 4.46875 | 4 | '''
Polymorphism: Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class.
In inheritance, the child class inherits the methods from the parent class.
'''
class User:
def sign_in(self):
print('Logged In!!')
def attack(self):
print('Do nothing!!')
class Wizard(User):
def __init__(self,name,power):
self.name = name
self.power = power
def attack(self):
User.attack(self)
print(f'{self.name} attacking with {self.power}% of power.')
class Archer(User):
def __init__(self,name,arrows):
self.name = name
self.arrows = arrows
def attack(self):
print(f'{self.name} attacking with Arrows and {self.arrows} arrows left.')
wizard1 = Wizard('Ayush',89)
archer1 = Archer('Kohli',20)
print('Example 1:')
def player_attack(char):
char.attack()
player_attack(wizard1)
player_attack(archer1)
print('Example 2:')
for char in [wizard1,archer1]:
char.attack()
print('Example 3:')
wizard1.attack() | true |
bd25b715de543f5ad54f7adc3fa0da0f237f86dd | dartleader/Learning | /Python/How to Think Like A Computer Scientist/4/exercises/8.py | 373 | 4.4375 | 4 | #Write a function area_of_circle(r) which returns the area of a circle with radius r.
def area_of_circle(r):
"""Calculate area of a circle with radius r and return it.""" #Docstring
#Declare temporary variable to hold the area.
area = 0
#Calculate area.
area = 3.14159 * r
#Return area.
return area
print(input(area_of_circle("What is the radius of the circle?")))
| true |
b4f6d71f352434965960284a54113bc719abb2c6 | Zidan2k9/PythonFundamentals | /loops.py | 733 | 4.15625 | 4 | # A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
people = ['Zain','Rida','Zaid','Mom','Dad']
for person in people:
print('Current person is ' , person)
#Break out
for person in people:
if person == 'Zaid':
break
print('Current person is ' , person)
#Continue
for person in people:
if person == 'Mom':
continue
print('Current person is ', person)
#Range
for i in range(len(people)):
print('Current person',people[i])
for i in range(0,11):
print('Number ',i)
# While loops execute a set of statements as long as a condition is true.
count = 0
while count <= 10:
print('Count ', count)
count += 1
| true |
fb7e04ae9c850d0d23b8e69a6d1c29533514f771 | ToddDiFronzo/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 575 | 4.125 | 4 | """ INTERSECTION OF MULTIPLE LISTS
1. Understand:
Goal: find intersection of multiple lists of integers
Test case
---------
Input: list of lists
[1,2,3,4,5]
[12,7,2,9,1]
[99,2,7,1]
Output: (1,2)
2. Plan:
NOTE: skipping this one.
"""
if __name__ == "__main__":
arrays = []
arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])
arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])
arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])
print(intersection(arrays))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.