blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
63a9ad33825620de6667c0d694471fbe8e939149 | Garima-sharma814/The-faulty-calculator | /faultycalculator.py | 1,596 | 4.3125 | 4 | # faulty calculator
# Design a calculator which will correctly solve all the problems except the following ones:
# if the combination of number contain 56 and 9 it will give you 77 as the answer no matter what operation your perform
# same for 45 and 3 , 56 and 6
# Your program should take operator and two numbers as input from the user and then return the result
a = int(input("Enter the first number: ")) # First number input
b = int(input("Enter the second number: ")) # second Number input
# select the operation
print("Please choose the Arithematic operation you want to perform")
c = input(" Press + for addition\n Press - for subtraction\n Press * for multiplication\n Press / for divide\n Your selection is: ")
# faults in the program
if a == 56 and b == 9 or b == 56 and a == 9: # First Fault
print("The answer is 77")
elif a == 45 and b == 3 or b == 45 and a == 3: # Second Fault
print("The answer is 555")
elif a == 56 and b == 6 or b == 56 and a == 6: # third fault
print("The answer is 4")
# correct calculations
elif c == "+": # Addition
print("The addition is ", a+b)
elif c == "-": # subtraction
if(a > b):
print("The subtraction is", a-b)
else:
print("ERROR")
elif c == "*": # Multiplication
print("The Multiplication is", a*b)
elif c == "/": # Division
print("The division is", a/b)
else:
# If you have not choosen the operator among the mentioned
print("Invalid Operator")
| true |
ce9b53ac17bff836d778e08c55000090e9a3b1c3 | MAD-reasoning/Python-Programming | /Elementry/Elementry_04.py | 324 | 4.28125 | 4 | # Write a program that asks the user for a number and prints the sum of the numbers 1 to number.
try:
num_sum = 0
number = int(input("Enter a natural number: "))
for i in range(1, number+1):
num_sum += i
except ValueError:
print("Enter a valid number")
else:
print("Sum = ", num_sum)
| true |
e29ff540a0375f255ae163e88d222460ee72e8d9 | jay-bhamare/Python_for_Everybody_Specialization_University_of_Michigan | /PY4E_Python_Data_Structures/Assignment 8.4.py | 996 | 4.1875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: jayvant
#
# Created: 08/04/2020
# Copyright: (c) jayvant 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
# Assignment 8.4
# Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
# The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
# When the program completes, sort and print the resulting words in alphabetical order.
# You can download the sample data at http://www.py4e.com/code3/romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
for i in line.split():
if not i in lst:
lst.append(i)
lst.sort()
print (lst)
| true |
6be03d03fa0505d440baa4a07c9726fb6c752644 | TuhinChandra/PythonLearning | /Basics/Shaswata/test2_video8_Variables.py | 889 | 4.53125 | 5 | print('Variables examples are here...')
x = 10
# Anything in python is an Object unlike other languages
print('x=', x, sep='')
print('type of x :', type(x))
print('id of x :', id(x))
y = 15
print('y=', y, sep='')
print('id of y :', id(y))
# Now see the id of y will change to id of x
y = 10
print('# Now see the id of y has changed to id of x')
print('y=', y, sep='')
print('id of y :', id(y))
# Objects are immutable in python
x = x + 1
print('# Objects are immutable in python thus it would change its id to new')
print('x=', x, sep='')
print('id of x :', id(x))
print('y=', y, sep='')
print('id of y :', id(y))
# Variables of any type can be changed to any other at any time
x = 3.5
print('# Variables of any type can be changed to any other at any time')
print('x=', x, sep='')
print('type of x :', type(x))
x = 'It\'s a String'
print('x=', x, sep='')
print('type of x :', type(x))
| true |
66858c07ada89061322b79ebf6898778d2bce2b8 | aricaldoni/band-name-generator | /main.py | 390 | 4.28125 | 4 | #Welcome message
print("Welcome to the authomatic Band Name generator.")
#Ask the user for the city that they grew up in
city = input("What city did you grow up in?: \n")
#Ask the user for the name of a pet
pet = input("What is the name of your pet: \n")
#Combine the name of their city and pet and show them their band name.
print("The suggested name for your Band is "+ city + " " + pet)
| true |
5c90d207ec78f0c29467ad3e5f7a66bca9d21e44 | JaredJWoods/CIS106-Jared-Woods | /ses8/PS8p5 [JW].py | 1,144 | 4.1875 | 4 | def incomeTax(gross):
if gross >= 500001:
rate = 0.30
print("You are in the highest tax bracket with a 30% federal income tax rate.")
elif gross >= 200000 and gross <= 500000:
rate = 0.20
print("You are in the middle tax bracket with a 20% federal income tax rate.")
else:
rate = 0.15
print("You are in the lowest tax bracket with a 15% federal income tax rate.")
taxOwed = float(gross * rate)
return rate, taxOwed
#------------------program starts here-------------------
print("Would you like me to calculate your federal income tax?")
choice = str(input("Type 'yes' or 'no': "))
while choice == "yes":
print("Thank you for selecting yes.")
gross = float(input("Please enter your gross income: $"))
print()
print("You entered a gross income of $",gross)
rate, taxOwed = incomeTax(gross)
percent = int (rate*100)
print("You have a tax rate of",percent,"%")
print("The amount of tax you owe is: $",taxOwed)
print()
choice = input("Would you like to compute your income tax again? Enter 'yes' or 'no': ")
print("Thank you for using our income tax calculator. Good bye.")
| true |
28cde805af45660b4d1f69504a1f709f5a9d28a9 | sofiacavallo/python-challenge | /PyBank/Drafts/homework_attempt_4.py | 2,126 | 4.1875 | 4 | # Reading / Processing CSV
# Dependencies
import csv
import os
# Files to load and output
budget_data = "budget_data.csv"
budget_analysis = "budget_analysis.txt"
# Read the csv and convert it into a list of dictionaries
with open(budget_data) as budget_data:
reader = csv.reader(budget_data)
# Read the header row
header = next(reader)
# Initialize a variable called total_months (count of all month values in the CSV)
total_months = 0
# Initialize a variable called net_total (sum of all postive/negative 'profit/loss' values in the CSV)
net_total = 0
# First row advances reader by one line. Otherwise % change comp with 0, mathematical error.
first_row = next(reader)
# Initialize variable for previous row.
previous_row = int(first_row[1])
# Define list called Net Change list
net_change_list = []
#Count total number of months in the data sets. Also the unique values in first column after the header. NOTE: row[1] is the 'Profit/Loss' value, and it is a STRING, thus needing a conversion. int() converts whatever is passed into to an integer
for row in reader:
total_months = total_months + 1
#Calculate net total of profits and losses
net_total = net_total + int(row[1])
#Calculate changes in profits/losses over period. First track the net change. Keep moving prev row forward.
net_change = int(row[1]) - previous_row
previous_row = int(row[1])
net_change_list = net_change_list + [net_change]
# Calculate average percent change
averageChange = sum(net_change_list) / len(net_change_list)
# Print out the data points of interest as the final budget analysis
print("Financial Analysis")
print("-------------------")
print("Total Months: ", {total_months})
print("Total: ", {net_total})
print("Average Change: ", {averageChange})
print("Greatest Increase in Profits: ", {max(net_change_list)})
print("Greatest Decrease in Profits: ", {min(net_change_list)})
# Write the output .txt file
f= open("budget_analysis.txt","w+") | true |
67a4705ab7e55c17de86ac966540fb552e4b645c | qaespence/Udemy_PythonBootcamp | /6_Methods_and_Functions/Homework.py | 2,178 | 4.4375 | 4 |
# Udemy course - Complete Python Bootcamp
# Section 6 Homework Assignment
# Write a function that computes the volume of a sphere given its radius
def vol(rad):
return (4.0/3)*(3.14159)*(rad**3)
print(vol(2))
# Write a function that checks whether a number is in a given range
# (Inclusive of high and low)
def ran_check(num,low,high):
if num in range(low,high+1):
print(f'The number {num} is between {low} and {high}.')
else:
print(f'The number {num} is outside the range of {low} and {high}.')
def ran_bool(num,low,high):
return num in range(low,high+1)
ran_check(3,1,10)
print(ran_bool(3,1,10))
# Write a Python function that accepts a string and calculate the number
# of upper case letters and lower case letters
def up_low(s):
lower_chars = 0
upper_chars = 0
for char in s:
if char.isupper():
upper_chars += 1
if char.islower():
lower_chars += 1
print(f'Original String : {s}')
print(f'No. of Upper case characters : {upper_chars}')
print(f'No. of Lower case characters : {lower_chars}')
up_low('Hello Mr. Rogers, how are you this fine Tuesday?')
# Write a Python function thay takes a list and returns a new list with
# unique elements of the first list
def unique_list(l):
unique_list = []
for num in l:
if num not in unique_list:
unique_list.append(num)
return unique_list
print(unique_list([1,1,1,1,2,2,3,3,3,3,4,5]))
# Write a Python function to multiple all the numbers in a list
def multiply(numbers):
result = 1
for num in numbers:
result *= num
return result
print(multiply([1,2,3,-4]))
# Write a Python function that checks whether a passed string is a
# palindrome or not
def palindrome(s):
words = s.split()
combined = "".join(words).lower()
return combined == combined[::-1]
print(palindrome('helleh'))
# Write a Python function to check whether a string is a pangram or not
import string
def ispangram(str, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str.lower())
print(ispangram("The quick brown fox jumps over the lazy dog"))
| true |
5948ceed31db511b3ec6894e8c76e9a3f80f9865 | lynnvmara/CIS106-Lynn-Marasigan | /Session 5/Extra Credit.py | 935 | 4.21875 | 4 | print("What is your last name?")
name = input()
print("How many hours?")
hours = int(input())
print("What is your rate per hour?")
rate = int(input())
if hours > 40:
print(name + "'s regular pay for the first 40 hours is $" + str(rate) + " per hour for a total of $" + str(40 * rate) + ". The " + str(hours - 40) + " hours of overtime have an overtime pay of $" + str(rate * 1.5) + " per hour for a total of $" + str((hours - 40) * (rate * 1.5)) + ".")
print(name + "'s gross pay is $" + str((40 * rate) + ((hours - 40) * (rate * 1.5))) + " for $" + str(rate) + " per hour over " + str(hours) + " hours.")
else:
print(name + "'s regular pay is $" + str(rate) + " per hour for a total of $" + str(hours * rate) + ". " + name + " did not work any overtime, so " + name + " gets $0 for 0 hours of overtime.")
print(name + "'s gross pay is $" + str(hours * rate) + " for $" + str(rate) + " per hour over " + str(hours) + " hours.") | true |
c25c418679ffdeb532dffb1409fbfe486167ca5a | lynnvmara/CIS106-Lynn-Marasigan | /Session 7/Assignment 2.py | 237 | 4.125 | 4 | print("What is the starting value?")
start = int(input())
print("What is the stop value?")
stop = int(input())
print("What is the increment value?")
increment = int(input())
while start <= stop:
print(start)
start = start + increment | true |
34c244ca5ffea4bd647dd29bc2eb7bccfa436db8 | radunm/jobeasy-algorithms-course | /HW_1.py | 1,789 | 4.1875 | 4 | # Sum of 3 modified
# Rewrite a program with any number of digits.
# Instead of 3 digits, you should sum digits up from n digits number,
# Where User enters n manually. n > 0
from random import randint
min_rand = 1
max_rand = "9"
result = 0
digit = int(input("Please, enter digit: "))
digit -= 1
while digit > 0:
min_rand *= 10
max_rand += "9"
digit -= 1
max_rand = int(max_rand)
random_number = randint(min_rand, max_rand)
print(f'Random number {random_number}')
while random_number > 0:
result = result + (random_number % 10)
random_number = random_number // 10
print(f"Sum: {result}")
# Find max number from 3 values, entered manually from a keyboard
one = int(input("Enter first digit: "))
two = int(input("Enter second digit: "))
three = int(input("Enter third digit: "))
def compare(x, y, z):
if x > y:
if x > z:
return x
else:
return z
else:
if y > z:
return y
else:
return z
print(f"You enter {one}, {two}, {three}")
print(f"Max number {compare(one, two, three)}")
# Count odd and even numbers. Count odd and even digits of the whole number. E.g, if entered number 34560,
# then 3 digits will be even (4, 6, and 0) and 2 odd digits (3 and 5).
digit = abs(int(input("Enter whole number: ")))
odd = []
even = []
countodd = 0
counteven = 0
if digit != 0:
while digit > 0:
temp = digit % 10
if temp % 2 == 0:
even.append(temp)
counteven += 1
else:
odd.append(temp)
countodd += 1
digit = digit // 10
else:
even.append(digit)
counteven += 1
even.reverse()
odd.reverse()
print(f"Number consist of {counteven} even digits {even} and {countodd} odd {odd}.")
| true |
998649baa7285122e041cdaf4a5dfbe984bc7c86 | vishnuap/Algorithms | /Chapter-03-Arrays/Zip-It/Zip-It.py | 1,449 | 4.875 | 5 | # Chapter-3: Arrays
# Zip-It
# 1. Create a function that accepts two arrays and combines their values sequentially into a new array at alternating indices starting with the first array. Extra values of either array should be included afterwards. Given [1,2] and [10,20,30], return [1,10,2,20,30]
# 2. Combine the two arrays in the same way but in the first array instead of creating a new array
# Assume the arguments being passed are both arrays
# Assume use of built in functions (for doing this without builtin functions, use the approach from the Array-Insert-At solution earlier in this chapter)
# 1
def zipIt(arr1, arr2):
result = []
length = len(arr1) + len(arr2)
for i in range(0, length):
if i < len(arr1):
result.append(arr1[i])
if i < len(arr2):
result.append(arr2[i])
return result
# 2
def zipIt2(arr1, arr2):
arr1Len = len(arr1)
arr2Len = len(arr2)
idx = 0
while (len(arr1) < arr1Len + arr2Len):
if (idx < arr1Len):
arr1.insert((idx * 2) + 1, arr2[idx])
else:
arr1.insert(len(arr1), arr2[idx])
idx += 1
myArr1 = [1,2,3,4,5]
myArr2 = [10,20,30,40,50]
print("The original arrays are {} and {}").format(myArr1, myArr2)
print("The zipped array is {}").format(zipIt(myArr1, myArr2))
print("The zipped array is {}").format(zipIt(myArr2, myArr1))
zipIt2(myArr1, myArr2)
print("The zipped array is {}").format(myArr1)
| true |
c847c6634e70a105c0fd65c0f83619e55e07937f | vishnuap/Algorithms | /Chapter-01-Fundamentals/You-Say-Its-Your-Birthday/You-say-its-your-Birthday.py | 385 | 4.21875 | 4 | # Chapter-1: Fundamentals
# You-say-its-your-Birthday:
# If 2 given numbers represent your birth month and day in either order, log "How did you know?", else log "Just another day..."
myBDate = [3, 6]
def bd(num1, num2):
if num1 in myBDate and num2 in myBDate:
print("How did you know?")
else:
print("Just another day...")
bd(1, 2)
bd(3, 6)
bd(6, 3)
bd(5 ,4) | true |
56c6b7dc97ec4603e5ab899bd72463ba3b15db7f | vishnuap/Algorithms | /Chapter-03-Arrays/Array-Nth-Largest/Array-Nth-Largest.py | 2,588 | 4.40625 | 4 | # Chapter-3: Arrays
# Array-Nth-Largest
# Given 'arr' and 'N', return the Nth largest element, where N-1 elements are larger. Return null if needed
# Assume the arguments are an array with integers and an integer and both are passed to the function
# Since we want Nth largest such that N-1 elements are larger, if there are duplicates in the array, then Nth largest will not necessarily be the Nth element from the last in a sorted-in-ascending-order array. Hence the sorted array will have to be looped through to find the Nth largest element
import math
def nthLargest(arr, num):
if num > len(arr):
return None
sortedArray = sort(arr)
length = len(sortedArray)
max = sortedArray[-1]
count = 1
for i in range(length - 2, -1, -1):
if (sortedArray[i] < max):
if count == num - 1:
return sortedArray[i]
else:
max = sortedArray[i]
count += 1
return None
# I am implementing a Radix sort. Currently works with only positive integers
# Will use push() built-in function
def sort(arr):
buckets = [] # empty array to hold the intermediate values
bucketLen = 0 # length of each bucket
bucketIdx = 0
length = len(arr)
div = 10
curSize = 0
maxSize = 0
iter = 0
# Find the maximum number of digits comprising any element in the array. That will decide how many iterations we go into
for i in range(0, length):
curSize = int(math.log10(arr[i])) + 1
maxSize = maxSize if maxSize > curSize else curSize
# Now iterate over the array to sort it. per Wikipedia, I am doing an LSD radix sort (least significant digit)
while iter < maxSize:
# create the empty buckets
buckets = [[] for i in range(0,10)]
# Populate the buckets
for i in range(0, length):
# Find the lest significant digit to sorton. With each iteration, this moves 1 digit to the left
bucketIdx = (arr[i] % div) / (div / 10)
buckets[bucketIdx].append(arr[i])
# Reset the array.
arr = []
# Write contents of buckets back into array
for i in range(0, 10):
for j in range(0, len(buckets[i])):
arr.append(buckets[i][j])
# increment the divisor
div *= 10
# increment the iteration count
iter += 1
# return the sorted array
return arr
myArr = [42, 1, 4, 72, 42, 72, 42, 72]
myNum = 4
print("The Nth largest in {} where N = {} is {}").format(myArr, myNum, nthLargest(myArr, myNum))
| true |
3dc49d530e386fd3b266e007bc640f34d7046ef2 | vishnuap/Algorithms | /Chapter-01-Fundamentals/Always-Hungry/Always-Hungry.py | 489 | 4.1875 | 4 | # Chapter-1: Fundamentals
# Always-Hungry
# Create a function that accepts an array and prints "yummy" each time one of the values is equal to "food". If no array element is "food", then print "I'm hungry" once
# Assume the argument passed is an array
def yummy(arr):
hungry = 1
for i in range(0, len(arr)):
if arr[i] == 'food':
hungry = 0
print("Yummy")
if hungry:
print("I'm hungry")
myArr = ['I', 'food', 'to', 'food']
yummy(myArr)
| true |
93cb895cbc0a72249e25dac5489153f304dcac91 | vishnuap/Algorithms | /The-Basic-13/Print-Ints-and-Sum-0-255/Print-Ints-and-Sum-0-255.py | 260 | 4.28125 | 4 | # The Basic 13
# Print-Ints-and-Sum-0-255
# Print integers from 0 to 255. With each integer print the sum so far
def printIntsSum():
sum = 0
for i in range(0, 256):
sum += i
print("{} - Sum so far = {}").format(i, sum)
printIntsSum()
| true |
23355dd307a13236d38a8bde6571435771f8f1c2 | vishnuap/Algorithms | /Chapter-03-Arrays/Array-Nth-to-Last/Array-Nth-to-Last.py | 453 | 4.46875 | 4 | # Chapter-3: Arrays
# Array-Nth-to-Last
# Return the element that is N from array's end. Given ([5,2,3,6,4,9,7], 3), return 4. If the array is too short return null
# Assume the arguments are an array and an integer and both are passed
def nthToLast(arr, num):
return None if num > len(arr) else arr[-1 * num]
myArr = [5,2,3,6,4,9,7]
myNum = 3
print("Th element that is {} from the last in {} is {}").format(myNum, myArr, nthToLast(myArr, myNum))
| true |
2dee4ac13bfc34d72b3a4bb04d199ab8be5de782 | vishnuap/Algorithms | /Chapter-01-Fundamentals/What-Really-Happened/What-Really-Happened.py | 1,334 | 4.15625 | 4 | # Chapter-1: Fundamentals
# What-really-Happened
# (refer to Poor Kenny for background)
# Kyle notes that the chance of one disaster is totally unrelated to the chance of another. Change whatHappensToday() to whatReallyHappensToday(). In this new function test for each disaster independantly instead of assuming exactly one disaster will happen. In other words, in this new function, all five might occur today or none. Maybe kenny will survive!!
# Assume the probabilities of disasters from the Poor-Kenny question
# 10% chance of volcano, 15% chance of tsunami, 20% chance of earthquake, 25% chance of blizzard and 30% chance of meteor strike
import random as rd
def whatReallyHappensToday():
rVol = int(rd.random() * 20)
rTsu = int(rd.random() * 20)
rEqu = int(rd.random() * 20)
rBli = int(rd.random() * 20)
rMet = int(rd.random() * 20)
none = 1
if rVol >= 0 and rVol <= 1:
print("Volcano")
none = 0
if rTsu >= 0 and rTsu <= 2:
print("Tsunami")
none = 0
if rEqu >= 0 and rEqu <= 3:
print("Earthquake")
none = 0
if rBli >= 0 and rBli <= 4:
print("Blizzard")
none = 0
if rMet >= 0 and rMet <= 5:
print("Meteor Strike")
none = 0
if none:
print("Nothing Happens Today")
whatReallyHappensToday()
| true |
c86a6295b69a14f635b5433edd3ad9f1b6044ca6 | vishnuap/Algorithms | /Chapter-04-Strings-AssociativeArrays/Drop-the-Mike/drop-the-mike.py | 997 | 4.25 | 4 | # Create a function that accepts an input string, removes leading and trailing white spaces (at beginning and ending only), capitalizes the first letter of every word and returns the string. If original string contains the word Mike anywhere, immediately return "stunned silence" instead. Given " tomorrow never dies ", return "Tomorrow Never Dies". Given " Watch Mike and Mike ", return "stunned silence"
# used built-in functions/methods
# lower() - converts the full string into lower case
# index(str2) - provides the starting position of str2 inside str1. If not found, throws an exception
# strip() - strips the leading and trailing whitespaces
# title() - converts the string into titlecase i.e., capitalize first letter in each word of the string
def dropIt(str):
try:
i = str.lower().index('mike')
except:
return str.strip().title()
else:
return "stunned silence"
myStr = " tomorrow never dies "
# myStr = "mike and Mike"
print(dropIt(myStr))
| true |
0d0ffaa8f3359bedd40bb5a1495339eecb8f03bc | vishnuap/Algorithms | /Chapter-01-Fundamentals/Multiples-of-3-But-Not-All/Multiples-of-3-but-not-all.py | 386 | 4.65625 | 5 | # Chapter-1: Fundamentals
# Multiples of 3 - but not all:
# Using FOR, print multiples of 3 from -300 to 0. Skip -3 and -6
# multiples from -300 down means multiply 3 with -100 and down. -3 and -6 are 3 * -1 AND 3 * -2. So if we skip them, the multipliers are -100 down to -3.
for i in range(-100, 1):
if ((i != -1) and (i != -2)):
print("Multiple of 3: {}").format(i * 3) | true |
905092abe8da1ea55e92a9d4a6b7f34565f2597b | vishnuap/Algorithms | /Chapter-02-Fundamentals-2/Statistics-Until-Doubles/Statistics-Until-Doubles.py | 838 | 4.1875 | 4 | # Chapter-2: Fundamentals-2
# Statistics-Until-Doubles
# Implement a 20-sided die that randomly returns integers between 1 and 20 (inclusive). Roll the die, tracking statistics until you get a value twice in a row. After that display number of rolls, min, max and average
import random as rd
def stats():
done = False
max = 1
min = 20
sum = 0
count = 0
prev = 0
roll = 0
while not done:
roll = rd.randint(1,20)
max = max if max > roll else roll
min = min if min < roll else roll
sum += roll
count += 1
if (prev == roll):
done = True
else:
prev = roll
print("After {} rolls, the value repeated is {}. The stats are Max = {}; Min = {}; Sum = {}; Avg = {}").format(count, prev, max, min, sum, sum * 1.0 / count)
stats()
| true |
31b22e49ea518465e4e9b84f9bce3ff9ac222f46 | f-alrajih/Simple-Calculator | /directions.py | 2,879 | 4.5625 | 5 | # Welcome, Faisal, to your first project in Python!
# Today's project is to build a simple calculator that allows the user to choose what type of operation they want to do (add, subtract, multiply, or divide) and then takes the two numbers the user gives it and does the operation.
# You will need to build four different functions for this assignment:
# 1. A function called add_two_numbers with inputs x and y. The function returns the sum of those two numbers.
# 2. A function called subract_two_numbers with inputs x and y. The function returns the difference of those two numbers.
# 3. A function called multiply_two_numbers with inputs x and y. The function returns the product of those two numbers.
# 4. A function called divide_two_numbers with inputs x and y. The function returns the quotient of those two numbers.
# Once you finish these four functions and test them, come to me and I'll give you more directions!
# -------------
# Great! You're ready to move on to creating a menu for the user to select from.
# Create a function called calculator_menu that prints four different strings:
# "Select 1 to add"
# "Select 2 to subtract"
# "Select 3 to multiply"
# "Select 4 to divide"
# Test the calculator_menu() by calling it.
# -------------
# Great! We wrote our menu. But, we need some directions for the user to follow.
# Create a function called greeting_and_directions that prints a greeting and directions for the menu:
# "Welcome to Faisal's Simple Calculator!"
# "Choose one of the options below, then press enter."
# -------------
# Awesome! We're so close!
# Now, we need some kind of way to get the user's answer to our directions so that we know what kind of operation to do. This is called user input.
# Create a variable called menu_choice that takes the user's input when asked "What would you like to do?"
# -------------
# Cool! Let's create two more variables, first_number and second_number, that ask the user for their first and second numbers.
# -------------
# Looking awesome! Let's create a conditional that figures what operation to do based on the user's menu choice.
# If menu_choice equals 1, call add_two_numbers()
# If menu_choice equals 2, call subtract_two_numbers()
# If menu_choice equals 3, call multiply_two_numbers()
# If menu_choice equals 4, call divide_two_numbers()
# ----------
# Okay, so it looks like we have two problems: we can't see the menu and the greeting, and we can't see the answer. Let's fix that.
# Call greeting_and_directions() and calculator_menu() above where you define menu_choice.
# -----------
# Great! We can see the greeting and menu, but we still can't see the answer.
# Go to your conditional statements where you checked for the value of menu choice. Print whatever add_two_numbers(), subtract_two_numbers(), multiply_two_numbers(), and divide_two_numbers() returns.
| true |
9d6b104a638a7d302a5aa5f89467ce47d7b5e972 | tarunvelagala/python-75-hackathon | /input_output.py | 239 | 4.125 | 4 | # Input Example
name, age = [i for i in input('Enter name and age:').split()]
# Output Example
print('Hello "{}", Your age is {}'.format(name, age))
print('Hello %s, Your age is %s' % (name, age))
print('Hello', name, 'Your age is', age)
| true |
2ccf71624478a3e9867ca75475630053040631b2 | dheerajsharma25/python | /assignment8/assignment9/ass9_1.py | 437 | 4.3125 | 4 | #Q.1- Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class circle:
def __init__(self,radius):
self.radius=radius
def area(self):
getarea=math.pi*self.radius*self.radius
print(getarea)
def circumference(self):
result=2*math.pi*self.radius
print(result)
a=circle(int(input("enter the radius:")))
a.area()
a.circumference() | true |
47f111e1242d64f5655027c836ebfa25b802f312 | dheerajsharma25/python | /assignment10/ass10_4.py | 646 | 4.15625 | 4 | #Q.4- Create a class Shape.Initialize it with length and breadth Create the method Area.
class shape:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
self.result=self.length*self.breadth
class rectangle(shape):
def arearect(self):
print("area of rectangle:",self.result)
class square(shape):
def areasqur(self):
print("area of square:",self.result)
r=rectangle(int(input("length of rectangle:")),int(input("breadth of rectangle:")))
r.area()
r.arearect()
s=square(int(input("length of square:")),int(input("breadth of square:")))
s.area()
s.areasqur() | true |
c0c4d692956d733993d63a42fdfdcf609c9b7eba | sv1996/PythonPractice | /sortList.py | 509 | 4.28125 | 4 | number =[3,1,5,12,8,0]
sorted_list =sorted(number)
print("Sorted list is " , sorted_list)
#original lst remain unhanged
print("Original list is " , number)
# print list in reverse order
print("Reverse soretd list is " , sorted(number , reverse =True))
#original list remain unchanged
print("Original list is " , number)
#sort the list within itself
lst =[1,20,5.5,4.2]
lst.sort()
print("Sorted list is" , lst)
lst =[1,2,3,4,5]
abc = lst
abc.append(6)
#print original list
print("Original List is " , lst)
| true |
a528ae279f5773160001dd56b9ffb7df47714a86 | viditvora11/GK-quiz | /Python assements/v2 (Instructions and welcome)/v2a_instructions_and_welcome.py | 707 | 4.4375 | 4 | #Asking if they want to know the quiz rules.
rule = input("\nDo you want to read the rules or continue without the rules? \npress y to learn the rules or x to continue without knowing the rules : ")#Asking for the input
if rule == "y" or rule == "yes": #Use if function
print("\nThe basic rules are as follows \n 1. Enter the answer in a,b,c,d.\n 2. Press enter if you don't know the answer.\n(Know that you will not get the point for if you press enter)")#Printing rules
elif rule == "x" : #using elif to the previous if for asking if they want to know the rules to the quiz.
print("You may continue without the rules.")
elif rule == "no":
print("You may continue without the rules.")
| true |
c57799bb1ea76d52ec15085c90ede41dc76ea625 | Punkrockechidna/PythonCourse | /advanced_python/functional_programming/map.py | 294 | 4.125 | 4 | # MAP
# previous version
# def multiply_by_2(li):
# new_list = []
# for item in li:
# new_list.append(items * 2)
# return new_list
# using map
def multiply_by_2(item):
return item * 2
print(list(map(multiply_by_2, [1, 2, 3]))) #not calling function, just running it
| true |
7c61b9cc81d4ae45d91866e38ec0051b045cdc00 | khatriajay/pythonprograms | /in_out_list_.py | 418 | 4.4375 | 4 | #! /usr/bin/env python3
#Python3 program for checking if you have a pet with name entered.
petname= ['rosie', 'jack', 'roxy', 'blossom'] #Define a list with pet names
print (' Enter your pet name')
name = input()
if name not in petname: #Check if name exists in list
print ('You dont have a pet named ' + name )
else:
print ('Your pet ' + name + ' missed you while you were away')
| true |
0cc442ea2ed19f5130e5cdff5886b6dce22441c4 | tayadehritik/NightShift | /fact.py | 217 | 4.1875 | 4 | args = int(input())
def factorial(num):
fact = num
for i in range(num-1,1,-1):
fact = fact * i
return fact
for i in range(args):
num = int(input())
fact = factorial(num)
print(fact)
| true |
cd067c9c7ee918b908e31959d1e77d36dae5b36d | destrauxx/famped.github.io | /turtles.py | 469 | 4.125 | 4 | def is_palindrome(s):
tmp = s[:]
tmp.reverse()
print(s, 'input list')
print(tmp, 'reversed list')
if tmp == s:
return True
else:
return
def word(n):
result = []
for _ in range(n):
element = input('Enter element: ')
result.append(element)
if is_palindrome(result):
print(f'{result} - is palindrome')
else:
print(f'{result} - not a palindrome')
word(3) | true |
42160b7b926a67cfea2f482584f39c38e11c4c17 | ssenviel/Python_Projects-Udemy_zero_to_hero | /Generators_play.py | 909 | 4.46875 | 4 | """
problem 1:
create a Generator that generates the squares of numbers up to some number 'N'
problem 2:
create a generator that yields "n" random number between a low and high number
NOTE: use random.randrange or random.randint
problem 3:
use the iter() function to convert the string 'hello' into an iterator.
"""
import random
def square_generator(N):
i=0
while i < N:
yield i**2
i += 1
def random_generator(N, start, stop):
"""
NOTE: need to figure out how to get unique random numbers
"""
i=0
while i < N:
yield random.randrange(start, stop)
i += 1
def convert_str_to_iter():
my_string = 'hello'
my_str_iter = iter(my_string)
for char in range(0, len(my_string)):
print(next(my_str_iter))
convert_str_to_iter()
| true |
bd160ff2bbf7bc2b6c004d39a51180a45c0e9a84 | MarceloSaied/py | /python/helloworld/python1.py | 485 | 4.15625 | 4 | # print ("hello world")
# counter = 100 # An integer assignment
# miles = 1000.0 # A floating point
# name = "John" # A string
import datetime
currentDate = datetime.date.today()
currentDate=currentDate.strftime('%a %d %b %y')
print(currentDate)
# print (counter)
# print (miles)
# print (name)
# print ("test")
# name = input("what is your name?")
# print (name)
# name = "John" # A string
# print (name.upper())
# print(name.capitalize())
| true |
c648e44b121c114f7fc4d4d28b83700720388604 | jw3329/algorithm-implementation | /sort/selectionsort.py | 600 | 4.1875 | 4 | def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# find minimum element, and swap with its element from the start
def selectionsort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
# after finishing searching, swap it
swap(arr, min_index, i)
import random
arr = random.sample(range(1000), 100)
print('before sorted value:\n', arr)
selectionsort(arr)
print('after calling selectionsort:\n', arr)
print('sorted?', sorted(arr) == arr) | true |
fbee41e0deb8a6a257f6a4a6977151eb79d273f0 | akomawar/Python-codes | /Practise_Assignments/reverse.py | 238 | 4.375 | 4 | while 1:
string=input("Eneter your string: ")
reverse=string[::-1]
print("Reverse order is : ",reverse)
if(string==reverse):
print('yes it is an palindrome')
else:
print('No it is not a palindrome')
| true |
01956a8f807fea39c05553178b47c9b4a81b73c8 | MarkChuCarroll/pcomb | /python/calc.py | 2,172 | 4.34375 | 4 | # A simple example of using parser combinators to build an arithmetic
# expression parser.
from pcomb import *
## Actions
def digits_to_number(digits, running=0):
"""Convert a list of digits to an integer"""
if len(digits) == 0:
return running
else:
r = (running * 10) + int(digits[0])
return digits_to_number(digits[1:], r)
def unary_to_number(n):
if n[0] == None:
return n[1]
else:
return -n[1]
def eval_add(lst):
"""Evaluate an addition expression. For addition rules, the parser will return
[number, [[op, number], [op, number], ...]]
To evaluate that, we start with the first element of the list as result value,
and then we iterate over the pairs that make up the rest of the list, adding
or subtracting depending on the operator.
"""
first = lst[0]
result = first
for n in lst[1]:
if n[0] == '+':
result += n[1]
else:
result -= n[1]
return result
def eval_mult(lst):
"""Evaluate a multiplication expression. This is the same idea as evaluating
addition, but with multiplication and division operators instead of addition and
subtraction.
"""
first = lst[0]
result = first
for n in lst[1]:
if n[0] == '*':
result = result * n[1]
else:
result = result / n[1]
return result
## The Grammar
# expr : add_expr ( ( '*' | '/' ) add_expr )*
# add_expr : unary_expr ( ( '+' | '-' ) unary_expr )*
# unary_expr : ( '-' )? simple
# simple : number | parens
# parens : '(' expr ')'
# number: digit+
digit = Parser.match(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
number = Action(digit.many(1), digits_to_number)
parens = Action(Parser.match(['(']) & Reference('expr') & Parser.match([')']),
lambda result: result[1])
simple = number | parens
unary_expr = Action(Parser.match(['-']).opt() & simple, unary_to_number)
mult_expr = Action(unary_expr & (Parser.match(['*', '/']) & unary_expr).many(), eval_mult)
add_expr = Action(mult_expr & (Parser.match(['-', '+']) & mult_expr).many(), eval_add)
expr = add_expr
Reference.register_named_parser('expr', add_expr)
inp = StringParserInput("1+2*(3+5*4)*(6+7)")
print(expr.parse(inp).output)
| true |
7cfd67cc83713cec92f7ce1807bcaeed84028c0b | sprajwol/python_assignment_II | /assignment_Q11.py | 863 | 4.71875 | 5 | # # 11. Create a variable, filename. Assuming that it has a three-letter
# # extension, and using slice operations, find the extension. For
# # README.txt, the extension should be txt. Write code using slice
# # operations that will give the name without the extension. Does your
# # code work on filenames of arbitrary length?
# filename = input("Enter the filename with extension:")
# name = filename[:-4]
# print(name)
# 11. Create a variable, filename. Assuming that it has a three-letter
# extension, and using slice operations, find the extension. For
# README.txt, the extension should be txt. Write code using slice
# operations that will give the name without the extension. Does your
# code work on filenames of arbitrary length?
filename = input("Enter a file name with three letter extension:")
only_filename = filename[:-4]
print(only_filename)
| true |
487db65523fc0db80945c254b577d3a9a3cf7f61 | sprajwol/python_assignment_II | /assignment_Q7.py | 1,054 | 4.25 | 4 | # 7. Create a list of tuples of first name, last name, and age for your
# friends and colleagues. If you don't know the age, put in None.
# Calculate the average age, skipping over any None values. Print out
# each name, followed by old or young if they are above or below the
# average age.
import statistics
list_of_data = [("Prajwol", "Shakya", 23), ("Momika", "Sherestha", 22), ("Ashish", "Maharjan", 24), ("Shirisha", "Maharjan", 22), ("Ananda", "Pandey", 25),
("Pramisha", "Kapali", 18), ("Adarsha", "Thapa", 20), ("Tejwol", "Shakya", 18), ("Aayushma", "Shakya", None), ("Shoojan", "Maharjan", 28), ("Subha", "Maharjan", 22)]
age_list = [each_tuple[2]
for each_tuple in list_of_data if each_tuple[2] != None]
print(age_list)
avg_age = statistics.mean(age_list)
for each_tuple in list_of_data:
if (each_tuple[2] == None):
print(each_tuple[0], "!!!No Data!!!")
elif (each_tuple[2] < avg_age):
print(each_tuple[0], "young")
elif (each_tuple[2] > avg_age):
print(each_tuple[0], "old")
| true |
e53d462fc353654d6ebbc5e3b1ad3b654e135a75 | korzair74/Homework | /Homework_4-20/family.py | 235 | 4.34375 | 4 | """
Create a variable called family
Assign it a list of at least 3 names of family members as strings
Loop through the list and print everyone's name
"""
family = ['Shea', 'Owen', 'Chris']
for name in family:
print(name) | true |
aebd73b4f15e97b86345ee31cd6e0df8e6e57b6d | matthpn2/Library-Database-Application | /backend_database.py | 1,929 | 4.53125 | 5 | import sqlite3
class Database:
'''
SQLite database which can be viewed, searched, inserted, deleted, updated and closed upon.
'''
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
self.cursor.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
self.connection.commit()
def viewData(self):
'''
Fetches and returns all the rows in the books table.
'''
self.cursor.execute("SELECT * FROM books")
rows = self.cursor.fetchall()
return rows
def insertData(self, title, author, year, isbn):
'''
Inserts data into the books table, given user input.
'''
self.cursor.execute("INSERT INTO books VALUES (NULL, ?, ?, ? , ?)", (title, author, year, isbn))
self.connection.commit()
def searchData(self, title = "", author = "", year = "", isbn = ""):
'''
Fetchs and returns the rows of the books table that matches the user search query.
'''
self.cursor.execute("SELECT * FROM books WHERE title = ? OR author = ? or year = ? or isbn = ?", (title, author, year, isbn))
rows = self.cursor.fetchall()
return rows
def deleteData(self, id):
'''
Deletes data from the books table, using the book id.
'''
self.cursor.execute("DELETE FROM books WHERE id = ?", (id,))
self.connection.commit()
def updateData(self, id, title, author, year, isbn):
'''
Updates data from books table, using the book id.
'''
self.cursor.execute("UPDATE books SET title = ?, author = ?, year = ?, isbn = ? WHERE id = ?", (title, author, year, isbn, id))
self.connection.commit()
def __del__(self):
self.connection.close() | true |
4e5d7c36099415e09ff077fba1e06bc3262950dc | samhita-alla/flytesnacks | /cookbook/core/basic/task.py | 2,089 | 4.15625 | 4 | """
Tasks
------
This example shows how to write a task in flytekit python.
Recap: In Flyte a task is a fundamental building block and an extension point. Flyte has multiple plugins for tasks,
which can be either a backend-plugin or can be a simple extension that is available in flytekit.
A task in flytekit can be 2 types:
1. A task that has a python function associated with it. The execution of the task would be an execution of this
function
#. A task that does not have a python function, for e.g a SQL query or some other portable task like Sagemaker prebuilt
algorithms, or something that just invokes an API
This section will talk about how to write a Python Function task. Other type of tasks will be covered in later sections
"""
# %%
# For any task in flyte, there is always one required import
from flytekit import task
# %%
# A ``PythonFunctionTask`` must always be decorated with the ``@task`` ``flytekit.task`` decorator.
# The task itself is a regular python function, with one exception, it needs all the inputs and outputs to be clearly
# annotated with the types. The types are regular python types; we'll go over more on this in the type-system section.
# :py:func:`flytekit.task`
@task
def square(n: int) -> int:
"""
Parameters:
n (int): name of the parameter for the task will be derived from the name of the input variable
the type will be automatically deduced to be Types.Integer
Return:
int: The label for the output will be automatically assigned and type will be deduced from the annotation
"""
return n * n
# %%
# In this task, one input is ``n`` which has type ``int``.
# the task ``square`` takes the number ``n`` and returns a new integer (squared value)
#
# .. note::
#
# Flytekit will assign a default name to the output variable like ``out0``
# In case of multiple outputs, each output will be numbered in the order
# starting with 0. For e.g. -> ``out0, out1, out2, ...``
#
# Flyte tasks can be executed like normal functions
if __name__ == "__main__":
print(square(n=10))
| true |
5fe0ad7defc54cb146a4d187e0ec03c001da7b82 | manrajpannu/ccc-solutions | /ccc-solutions/2014/Triangle.py | 1,239 | 4.21875 | 4 | # Triangle
# Manraj Pannu
# 593368
# ICS3U0A
# 23 Oct 2018
firstAngle = int(input()) # input: the first angle of the triangle
secondAngle = int(input()) # input: the second angle of the triangle
thirdAngle = int(input()) # input: the third angle of the triangle
totalAngle = (firstAngle + secondAngle + thirdAngle) # calculates the total angle of the triangle
if (firstAngle == 60 and secondAngle == 60 and thirdAngle == 60) : # checks if all the angles have 60 degree angles
print('Equilateral') # output: that the triangle is equilateral
elif (totalAngle == 180 and (firstAngle == secondAngle or secondAngle == thirdAngle or firstAngle == thirdAngle) ): # checks if all the angles equal to 180 and that atleast two of the angles are the same
print('Isosceles') # output: that the triangle is equilateral
elif (totalAngle == 180 and (firstAngle != secondAngle and secondAngle != thirdAngle and firstAngle != thirdAngle) ): # checks if all the angles equal to 180 and that all of the angles arent the same
print('Scalene') # output: that the triangle is equilateral
else : # works if all other conditional statements are false
print('Error') #output : that there is no proper inputs for it to be a triangle
| true |
871d961154232ad57478058b1f58f6ca47c9f03f | JustinLaureano/python_projects | /python_practice/is_prime.py | 563 | 4.3125 | 4 | """
Define a function isPrime/is_prime() that takes one integer argument and
returns true/True or false/False depending on if the integer is a prime.
Per Wikipedia, a prime number (or a prime) is a natural number greater than 1
that has no positive divisors other than 1 and itself.
"""
def is_prime(num):
if num < 2:
return '{} is not prime.'.format(num)
for x in range(2, num):
if int(num) % x == 0:
return '{} is not prime.'.format(num, x)
return '{} is prime.'.format(num)
print(is_prime(-1))
print(is_prime(13))
| true |
e84bee8c7f1151fde0a1d9be3c1bf96400ac5949 | JustinLaureano/python_projects | /python_practice/max_subarray_sum.py | 924 | 4.21875 | 4 | """
The maximum sum subarray problem consists in finding the maximum sum of a
contiguous subsequence in an array or list of integers:
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum
sum is the sum of the whole array. If the list is made up of only negative
numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list
or array is also a valid sublist/subarray.
"""
def maxSequence(arr):
max = []
for x in range(len(arr)):
for pos, number in enumerate(arr):
subarray = arr[pos:x + 1]
total = 0
for num in subarray:
total += num
if total > sum(max):
max = subarray
return max, sum(max)
print(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
# should be 6: [4, -1, 2, 1]
| true |
dea1a14a5d21acab0295d8cf41cfc85deae87015 | itspayaswini/PPA-Assignments | /exception.py | 221 | 4.15625 | 4 | numerator=int(input("enter the numerator "))
denominator=int(input("enter the denominator "))
try:
result= (numerator/denominator)
print(result)
except ZeroDivisionError as error:
print("Division by zero!")
| true |
5db2515b14384ef59c4dc2459305b3d4f0f91853 | perfectgait/eopi | /python2/7.2-replace_and_remove/telex_encoding.py | 1,401 | 4.25 | 4 | """
Telex encode an array of characters by replacing punctuations with their spelled out value.
"""
__author__ = "Matt Rathbun"
__email__ = "mrathbun80@gmail.com"
__version__ = "1.0"
def telex_encode(array):
"""
Telex encode an array of characters using the map of special characters
"""
special_string_length = 0
char_map = {
'.': 'DOT',
',': 'COMMA',
'?': 'QUESTION MARK',
'!': 'EXCLAMATION MARK'
}
for char in array:
if char in char_map:
# Make sure to subtract one for the special character that is being replaced
special_string_length += len(char_map[char]) - 1
if special_string_length > 0:
current_index = len(array) - 1
array += [''] * special_string_length
write_index = len(array) - 1
while current_index >= 0:
if array[current_index] in char_map:
for i in range(len(char_map[array[current_index]]) - 1, -1, -1):
array[write_index] = char_map[array[current_index]][i]
write_index -= 1
else:
array[write_index] = array[current_index]
write_index -= 1
current_index -= 1
return array
string = raw_input('String: ')
original_string = string
print 'The telex encoding of the string %s is %s' % (original_string, ''.join(telex_encode(list(string)))) | true |
2d9b2e241a24df7fa44ce2fd51be999d07a1d40e | Vangasse/NumPyTutorial | /NumPySortSearch.py | 725 | 4.28125 | 4 | # %%
import numpy as np
import matplotlib.pyplot as plt
# %% How to get the indices of the sorted array using NumPy in Python?
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
print(np.argsort(a))
# %% Finding the k smallest values of a NumPy array
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
k = 3
print(np.sort(a)[:k])
# %% How to get the n-largest values of an array using NumPy?
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7])
k = 3
print(np.sort(a)[-k:])
# %% Sort the values in a matrix
a = np.array([2, 4, 8, 6, 1, 9, 5, 3, 7]).reshape([3, 3])
print(a)
a = np.sort(np.ravel(a)).reshape([3, 3])
print(a)
# %% Filter out integers from float numpy array
a = np.array([1.0, 1.2, 2.2, 2.0, 3.0, 2.0])
print(a[a != a.astype(int)] )
# %% | true |
c4d8a7398a895035637e2c36ca6c26f9a2fdf666 | gmendiol-cisco/aer-python-game | /brehall_number-guessing-game.py | 1,073 | 4.1875 | 4 | #random number generator
import random
number=random.randint(1,100)
#define variables.
TOP_NUM=100
MAXGUESS=10
guesscount=0
#game rules
print("Welcome to the Number Guessing Game...")
print("I'm thinking of a number between 1 and", TOP_NUM,". You have", MAXGUESS,"chances to figure it out." )
#collect information
while guesscount <= MAXGUESS:
print("What do you guess?")
guesscount = guesscount + 1
guess = input()
guess = int(guess)
#if guess > TOP_NUM
# print("please choose a number between 1 and", TOP_NUM,")
if guess > TOP_NUM:
print("please guess a number between 1 and", TOP_NUM)
elif guess < 1:
print("please guess a number between 1 and", TOP_NUM)
elif guess < number:
print("I will give you a hint, your guess is too low")
elif guess > number:
print("I will give you a hint, your guess is too high")
elif guess == number:
break
if guesscount > MAXGUESS:
print("I am sorry but you have exceeded your guess count, the number I was thinking of was", number)
if guess == number:
print("Great job!, you have guessed my number")
| true |
ac233558523fd4d10a3f327417816cf9aafcfa9c | kchaoui/me | /week2/exercise1.py | 1,958 | 4.65625 | 5 | """
Commenting skills:
TODO: above every line of code comment what you THINK the line below does.
TODO: execute that line and write what actually happened next to it.
See example for first print statement
"""
import platform
# I think this will print "hello! Let's get started" by calling the print function.
print("hello! Let's get started") # it printed "hello! Let's get started"
some_words = ['what', 'does', 'this', 'line', 'do', '?']
#I think this will print the string contained in the list some_words
for word in some_words:
print(word) #this printed the words from the list in a column, each word from the list is assigned to'word'
#I think this will also print the string contained in the list some_words, x is the index of the string
for x in some_words:
print(x) #this also printed the words from the list in a column, the function assigns each word to 'x'
#I think it will print the string some_words
print(some_words) #prints the string some_words in square brackets and in a row
#I think this will print the phrase 'some_words contains more than 3 words' if the string contains more than 3 words, which it does
if len(some_words) > 3:
print('some_words contains more than 3 words') #it printed 'some_words contains more than 3 words' since there are more than 3 words in the string
#I think this will print out a namedtuple () in round brackets with information about my computer: system, node, release, version, machine, and processor.
def usefulFunction():
"""
You may want to look up what uname does before you guess
what the line below does:
https://docs.python.org/3/library/platform.html#platform.uname
"""
print(platform.uname()) #prints the following computer details: (system='Darwin', node='17kchaoui17', release='19.0.0', version='Darwin Kernel Version 19.0.0: Thu Oct 17 16:17:15 PDT 2019; root:xnu-6153.41.3~29/RELEASE_X86_64', machine='x86_64', processor='i386')
usefulFunction()
| true |
94101d0179b9826da4e12ed61fbb1f08cf93e7e5 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsEasy/543_Diameter_of_binary_tree.py | 2,650 | 4.40625 | 4 | '''
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
Idea:
At a given node, the maximum diameter seen till now is:
max ( left subtree max diameter, right sub tree max diamater, diameter including the current root)
diameter including the current root = 1 + maxPathStartingAtLeftChild + 1 + maxPathStartingAtRightChild
We also compute what the current node can offer interms of the number of edges if thi is selected to be in the diameter.
We pass up the maxdiameter till now and what the current node can offer if it is selected to be part of the diameter.
Why we need what the current node can offer?
Because in the node that called this node, to compute the diameter through that ode it needs to know the max path available in the
left chi;ld and right child then add 2 to it because it is contributing two edges.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def diameterOfBinaryTreeHelper(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# Base case
if not root:
return (0,0)
# Base case 2
elif not root.left and not root.right:
#print " At " + str(root.val)
return (0,0)
else:
(leftDiameter, leftMaxPath) = self.diameterOfBinaryTreeHelper(root.left)
(rightDiameter, rightMaxPath) = self.diameterOfBinaryTreeHelper(root.right)
diameterthroughRoot = 0
if(root.left):
diameterthroughRoot += 1 + leftMaxPath
if(root.right):
diameterthroughRoot += 1 + rightMaxPath
maxDiameterTillNow = max(leftDiameter, rightDiameter, diameterthroughRoot)
maxPathStartingAtRoot = 1 + max(leftMaxPath, rightMaxPath)
#print " At " + str(root.val)
#print " Max dia till now " + str(maxDiameterTillNow) + " max path startig at root " + str(maxPathStartingAtRoot)
return (maxDiameterTillNow, maxPathStartingAtRoot)
def diameterOfBinaryTree(self, root):
return self.diameterOfBinaryTreeHelper(root)[0]
| true |
5ac54dd56d88f98d8a0877706ef05f53f0bcbec1 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsEasy/461_HammingDistance.py | 1,254 | 4.15625 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Hints: XOR followed by count set bits. Counting set bits can be done in many ways. Lookup table in O(1). Brutoforce O(n) Brian- Kerninghan Thets(n)
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
"""
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
differing_positions = x ^ y
# Count set bits
# c = 0
# while(differing_positions):
# differing_positions &= differing_positions - 1
# c += 1
# return c
# Look up Table:
c = 0
bits_by_number = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
mask = 0xF
shifter = 4
for i in range(8):
c += bits_by_number[differing_positions & mask]
differing_positions = differing_positions >> shifter
return c
if __name__ == '__main__':
x = Solution()
print x.hammingDistance(1577962638, 1727613287)
| true |
41df50dd1f20e926992b910468b7c44859377dfe | Aurales/DataStructuresHomework | /Data Structures/Lab 04/Lab04A_KyleMunoz.py | 367 | 4.1875 | 4 | #Kyle Munoz
#Collatz Conjecture Recursively
def CollatzConjecture(n, c = 0):
if n == 1:
print("Steps Taken: ",c)
elif n % 2==0:
return CollatzConjecture(n/2, c + 1)
else:
return CollatzConjecture(((n * 3) + 1), c + 1)
def main():
x = int(input("What number would you like to try? "))
CollatzConjecture(x, c = 0)
main()
| true |
736b387e21f6927a74aedffd1580eb89d92a4f06 | feyfey27/python | /age_calculator.py | 669 | 4.25 | 4 | from datetime import datetime, date
def check_birthdate(year, month, day):
today = datetime.now()
birthdate = datetime(year, month, day)
if birthdate > today:
return False
else:
return True
def calculate_age(year,month,day):
today = datetime.now()
birthdate = datetime(year, month, day)
age = today - birthdate
print("You are %s years old" % (age.days / 365))
year = int(input("Enter year of birth: "))
month = int(input("Enter month of birth: "))
day = int(input("Enter day of birth: "))
if check_birthdate(year, month, day)==True:
calculate_age(year, month, day)
else:
print("invalid birthdate.")
# import datetime
# x = datetime.datetime.now()
| true |
84f9b09013e04222ed26dfc6af70fcc91dcf2324 | aindrila2412/DSA-1 | /Booking.com/power_set.py | 1,609 | 4.1875 | 4 | """
Given an integer array nums of unique elements, return all possible subsets
(the power set).
The solution set must not contain duplicate subsets. Return the solution in
any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
"""
def power_sets(nums):
"""
We define a backtrack function named backtrack(first, curr) which takes the
index of first element to add and a current combination as arguments.
1. If the current combination is done, we add the combination to the final
output.
2. Otherwise, we iterate over the indexes i from first to the length of the
entire sequence n.
- Add integer nums[i] into the current combination curr.
- Proceed to add more integers into the combination : backtrack(i + 1,
curr).
- Backtrack by removing nums[i] from curr.
"""
def backtrack(first=0, curr=[]):
# if the combination is done
if len(curr) == k:
output.append(curr[:])
return
for i in range(first, n):
# add nums[i] into the current combination
curr.append(nums[i])
# use next integers to complete the combination
backtrack(i + 1, curr)
# backtrack
curr.pop()
output = []
n = len(nums)
for k in range(n + 1):
backtrack()
return output
if __name__ == "__main__":
print(power_sets([1, 2, 3]))
| true |
b77cdbe352caec79714a00d9de8536ecb1bf15a6 | aindrila2412/DSA-1 | /Recursion/reverse_a_stack.py | 1,350 | 4.25 | 4 | """
Reverse a Stack in O(1) space using Recursion.
Example 1
Input: st = [1, 5, 3, 2, 4]
Output:[4, 2, 3, 5, 1]
Explanation: After reversing the stack [1, 5, 3, 2, 4]
becomes [4, 2, 3, 5, 1].
Example 2
Input: st = [5, 17, 100, 11]
Output: [11, 100, 17, 5]
Explanation: After reversing the stack [5, 17, 100, 11]
becomes [11, 100, 17, 5]
"""
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def top(self):
if self.is_empty():
return None
return self.stack[-1]
def pop(self):
if self.is_empty():
raise Exception("Underflow condition.")
return self.stack.pop()
def push(self, elm):
self.stack.append(elm)
def print_stack(self):
print(self.stack)
def insert_at_bottom(s, tmp_emp):
if s.is_empty():
s.push(tmp_emp)
else:
current_top = s.top()
s.pop()
insert_at_bottom(s, tmp_emp)
s.push(current_top)
def reverse_stack(s: Stack):
if s.is_empty():
return
tmp_elm = s.top()
s.pop()
reverse_stack(s)
insert_at_bottom(s, tmp_elm)
if __name__ == "__main__":
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
s.push(5)
s.print_stack()
reverse_stack(s)
s.print_stack()
| true |
391ce6e49583edf602e8dca5690384ca5e614bfe | aindrila2412/DSA-1 | /Recursion/ways_to_climb_stairs.py | 1,342 | 4.125 | 4 | """
Given a staircase of n steps and a set of possible steps that we can climb at
a time named possibleSteps, create a function that returns the number of ways
a person can reach to the top of staircase.
Example:
Input:
n = 10
possibleSteps = [2,4,5,8]
Output: 11
Explanation:
[2,2,2,2,2], [2,2,2,4], [2,2,4,2], [2,4,2,2], [4,2,2,2], [4,4,2],
[2,4,4], [4,2,4], [5,5], [8,2], [2,8]
idea here is lets say if someone is at step 2, number of ways one can
jump to step 10 is (10-2)->8 ways and similarly
ways(10) = ways(10-2) + ways(10-4) + ways(10-5) + ways(10-8)
i.e:
ways(10) = ways(8) + ways(6) + ways(5) + ways(2)
ways to jump to 10-2
[2,2,2,2], [4,4] ,[2,2,4], [8], [2,4,2], [4,2,2]
"""
def wtj(stair, possible_steps, call_stack) -> int:
call_stack.append(stair)
print(call_stack)
if stair == 0: # only one way to jumping to step 0
call_stack.pop()
print(call_stack)
return 1
no_of_ways = 0
for steps in possible_steps:
if stair - steps >= 0:
no_of_ways += wtj(stair - steps, possible_steps, call_stack)
call_stack.pop()
print(call_stack)
return no_of_ways
if __name__ == "__main__":
stairs = 10
possible_steps = [2, 4, 5, 8]
print(wtj(10, possible_steps, []))
| true |
03eaa82c091996233aece88866bdf83c04b43d0a | aindrila2412/DSA-1 | /crackingTheCodingInterview/ArrayAndStrings/largest_number_at_least_twice_of_others.py | 1,445 | 4.3125 | 4 | """
You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much
as every other number in the array. If it is, return the index of the largest
element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Example 3:
Input: nums = [1]
Output: 0
Explanation: 1 is trivially at least twice the value as any other number
because there are no other numbers.
"""
def dominantIndex(nums):
"""
1. Iterate through the array and find largest, l_index
2. Iterate the array again and find if largest > 2*nums[i], if not
return -1
3. if yes return l_index
[1,2,3,4]
[3,6,1,0]
"""
if len(nums) == 1:
return 0
largest = -1
l_index = -1
for index, i in enumerate(nums):
if i > largest:
largest = i
l_index = index
print(largest, l_index)
for i in range(len(nums)):
if i == l_index:
pass
elif (2 * nums[i]) > largest:
print(nums[i], i)
return -1
return l_index
if __name__ == "__main__":
print(dominantIndex([3, 6, 1, 0]))
| true |
9bb56f95c93a03afdd983e623f94dad18e526228 | alicetientran/CodeWithTienAndHieu | /1-introduction/Task1-tien.py | 914 | 4.3125 | 4 | """
Task:
Ask the user for a number
Tell the user if the number is odd or even
Hint: use % operator
Extras:
If the number is a multiple of 3, print "Third time's a charm"
Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).
If {check} divides evenly into {num}, print "They are in a family".
If not, print "They are strangers"
"""
#number = int(input('Enter a number'))
#answer = number % 2
#if answer > 0:
#print("This is an odd number.")
#else:
#print("This is an even number.")
charm = int(input('Enter a number'))
task_2 = charm % 3
print(charm)
print(task_2)
if task_2 == 0:
print("Third time is a charm.")
#num = int(input("Enter the first number"))
#check = int(input("Enter the second number"))
#task_3 = check % num
#if task_3 > 0:
#print("They are strangers")
#else:
#print("They are in a family") | true |
b24e15f6714bd51c24148ecc514362f850623233 | houtan1/Python_Data_Cleaner | /helloworld.py | 888 | 4.25 | 4 | # run with python helloworld.py
# print("hello world")
# tab delimited text dataset downloaded from https://doi.pangaea.de/10.1594/PANGAEA.885775 as Doering-etal_2018.tab
# let's read in that data
file = open("data/Doering-etal_2018.tab", "r")
line = file.readlines()
# print(line[28])
# print(len(line))
for x in range(29, len(line)):
# print(line[x].split('\t'))
# print(len(line[x].split('\t')))
thisArray = line[x].split('\t')
# print(len(thisArray))
if thisArray[11] == "\n":
print("Missing Age! Length(mm): " + thisArray[9] + " Diameter(mm): " + thisArray[10])
file.close()
# the above script opens the tab delimited data file in read format
# it then reads the data portion of the file, row by row
# the script searches for data rows which are missing the value for age
# it flags those rows and informs the user of their length and diameter values
| true |
adde8bcdf70592e681d642befa152e0737ffc754 | marat-biriushev/PY4E | /py.py | 2,071 | 4.21875 | 4 | #!/usr/bin/python3
def f(x, y = 1):
"""
Returns x * y
:param x: int first integer to be added.
:param y: int second integer to be added (Not requared, 1 by default).
:return : int multiplication of x and y.
"""
return x * y
x = 5
#print(f(2))
#a = int(input('type a number'))
#b = int(input('type another number'))
#try:
# print(a / b)
#except ZeroDivisionError:
# print('b cannot be zero. Try again')
def fac(x):
"""
Returns x!
:param x: int integer to be added
:return : int integer x!
"""
if x == 1 or x == 0:
return 1
else:
return x * fac(x-1)
print(fac(4))
#class Orange:
#
# def __init__ (self, weight, color, mold):
# """ all weights are in oz"""
# self.weight = weight
# self.color = color
class Orange():
def __init__(self):
"sfsdf"
self.weight = 6
self.color = 'orange'
self.mold = 0
def rot(self, days, temp):
self.mold = days*(temp* .1)
#################################
#########INHERITANCE#############
#################################
lass Adult():
def __init__(self, name, height, weight, eye):
"comment"
self.name = name
self.height = height
self.weight = weight
self.eye = eye
def print_name(self):
print(self.name)
tom = Adult("Tom", 6, 100, "green")
tom.print_name()
class Kid(Adult):
def print_cartoon(self, fav_cartoon):
print("{}'s favorite cartoon id {}".format(self.name, fav_cartoon))
child = Kid("Lauren", 3, 50, "blue")
child.print_name()
child.print_cartoon('TEST')
####################################################
#################################
#########Composition#############
#################################
class Dog():
def __init__(self, name, breed, owner):
self.name = name
self.breed = breed
self.owner = owner
class Person():
def __init__(self, name):
self.name = name
mik = Person("Mik Jagger")
dog = Dog("Stanley", "Bulldog", mik)
print(dog.owner.name)
| true |
0f71e4012a72306a5c67cae91d404a2229d641c4 | marat-biriushev/PY4E | /ex_7_1.py | 2,122 | 4.625 | 5 | #!/usr/bin/python3
''' Exercise 1: Write a program to read through a file
and print the contents of the file (line by line) all
in upper case.'''
fname = input('Enter a filename: ')
fhand = open(fname)
for line in fhand:
line = line.upper()
line = line.rstrip()
print(line)
############################################
#!/usr/bin/python3
''' Exercise 2: Write a program to prompt for a
file name, and then read through the file and look for
lines of the form: X-DSPAM-Confidence: 0.8475
When you encounter a line that starts with "X-DSPAM-Confidence:"
pull apart the line to extract the floating-point number on the line.
Count these lines and then compute the total of the spam confidence
values from these lines. When you reach the end of the file, print out
the average spam confidence. Average spam confidence: 0.750718518519 '''
fname = input('Enter the filename: ')
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
exit()
count = 0
snum = 0
for line in fhand:
line = line.rstrip()
if line.find('X-DSPAM-Confidence:') == -1:
continue
print(line, float(line[19:]))
snum = snum + float(line[19:])
count += 1
print(snum / count)
print('###########################')
############################
''' Exercise 3: Sometimes when programmers get bored or want to have
a bit of fun, they add a harmless Easter Egg to their program.
Modify the program that prompts the user for the file name so that
it prints a funny message when the user types in the exact file
name "na na boo boo". The program should behave normally for all
other files which exist and don't exist.'''
fname = input('Enter the file name: ')
search = input('Type what are you searching for: ')
if fname == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
exit()
try:
fhand = open(fname)
except:
print('File cannot be opened!', fname)
exit()
count = 0
for line in fhand:
line = line.rstrip()
if line.find(search) == -1:
continue
count += 1
print('Thete were {} {} lines in {}'.format(count, search, fname))
| true |
63d20821cc349256ae4929da0ef0a2691713a831 | gchristofferson/credit.py | /credit.py | 2,681 | 4.15625 | 4 | from cs50 import get_int
import math
# prompt user for credit card
# validate that we have a positive integer between 13 and 16 digits
while True:
ccNum = get_int('Enter Credit Card Number: ')
if ccNum >= 0:
break
# reset value of ccNum
copyCCNum = ccNum
count = 0
# count the number of digits in the integer provided by user
while ccNum > 0:
ccNum = math.floor(ccNum / 10)
count += 1
# if user provides a number less than 13 or more than 16, print 'INVALID'
if count < 13 or count > 16:
print('INVALID')
quit()
# reset value of ccNum
ccNum = copyCCNum
# access company identifier (2 digits) at the beginning of card number
divNum = 1
if count == 13:
divNum = 100000000000
elif count == 14:
divNum = 1000000000000
elif count == 15:
divNum = 10000000000000
elif count == 16:
divNum = 100000000000000
identifier = math.floor(ccNum / divNum)
# validate the identifier and assign company to the number if valid
company = ''
if identifier == 34 or identifier == 37:
company = 'AMEX'
elif identifier >= 40 and identifier <= 49:
company = 'VISA'
elif identifier >= 51 and identifier <= 55:
company = 'MASTERCARD'
# if no valid identifier is found, print 'INVALID'
if company == '':
print('INVALID')
# if card doesn't have required number of digits for the company, print 'INVALID'
if company == 'AMEX' and count != 15:
print('INVALID')
quit()
if company == 'VISA' and count < 13:
print('INVALID')
quit()
if company == 'VISA' and count > 16:
print('INVALID')
quit()
if company == 'MASTERCARD' and count != 16:
print('INVALID')
quit()
# validat that we have a real credit card number
# for valid company and number, start with second-to-last digit & multiply every other digit by 2 & then sum those digits
product, splitA, splitB, theSum, secondLastNum = 0, 0, 0, 0, 0
while ccNum > 0:
ccNum = math.floor(ccNum / 10)
secondLastNum = math.floor(ccNum % 10)
product = math.floor(secondLastNum * 2)
splitA = math.floor(product % 10)
splitB = math.floor(product / 10)
theSum = math.floor(theSum + (splitA + splitB))
ccNum = math.floor(ccNum / 10)
ccNum = copyCCNum
# add sum to remaining digits
lastNum = 0
while ccNum > 0:
lastNum = math.floor(ccNum % 10)
ccNum = math.floor(ccNum / 100)
theSum = math.floor(theSum + lastNum)
# validate checksum
lastNumDigit = theSum % 10
if company == 'AMEX' and lastNumDigit == 0:
print('AMEX')
quit()
elif company == 'VISA' and lastNumDigit == 0:
print('VISA')
quit()
elif company == 'MASTERCARD' and lastNumDigit == 0:
print('MASTERCARD')
quit()
else:
print('INVALID')
quit() | true |
72b76b4fdadfd01b0139c323b6412008fd70e90d | omi-akif/My_Codes | /Python/DataAnalysis/MIS401/Class Resource/1st Class/MIS401-Class 1.py | 1,402 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[12]:
# In[17]:
Name ='Kazi' #Assigning String Variable
# In[56]:
Age=28 #assigning variable
# In[15]:
Name #Printing varibale without using Print
# In[16]:
Age #Printing varibale without using Print
# In[18]:
Name
# In[19]:
print(Name)
# In[21]:
print(Age)
# In[23]:
print(type(Age)) #printing type of age variable
# In[24]:
type(Name)
# In[25]:
num1=47 #assigning num1 and num2
num2=9
# In[34]:
num1%num2 # We have used +,_,*,/,**,//,%
# In[35]:
100000000000**10 # 1 Trillion*power10
# In[36]:
amount=100000 #assigning varibale
Interest_rate=.12
Years=7
# In[40]:
Final_Amount=amount*Interest_rate*Years
# In[41]:
print(Final_Amount)
# In[49]:
final_amount=amount+(amount*Interest_rate*Years)
# In[50]:
print(final_amount)
# In[47]:
Interst=(amount*Interest_rate)/100
# In[48]:
print(Interst)
# In[55]:
Height=1.73
Weight=87
BMI=Weight/(Height)**2
# In[54]:
print(BMI)
# In[59]:
a="Dhaka"
b="Cumilla"
# In[60]:
a+b
# In[62]:
c="100"
# In[63]:
c*10
# In[64]:
new_c=int(c)
# In[65]:
new_c
# In[66]:
d=100
# In[67]:
new_d=float(d)
# In[68]:
new_d
# In[69]:
old_d=int(new_d)
# In[70]:
type(old_d)
# In[71]:
old_d
# In[72]:
e=120
# In[73]:
type(e)
# In[74]:
new_e=str(e)
# In[75]:
new_e
# In[ ]:
| true |
954959ab38ebc709a8f81657b636fcf5f6d3ede3 | tiago-falves/FPRO-Python | /RE/Outros/min_path.py | 1,790 | 4.15625 | 4 | """
5. Minimum path
Write a function min_path(matrix, a, b, visited=[]) that discovers the minimum path
between a and b inside the matrix maze without going through visited twice. Positions a
and b are tuples (line, column), matrix is a matrix of booleans with False indicating no
obstacle and True indicating an obstacle and visited is a list of visited tuples. Valid
movements include all 8 adjacent tiles.
For the maze of the following figure, a minimum path between a and b, in yellow, is 4:
b
a
Save the program in the file min_path.py inside the folder PE3.
For example:
mx = [
[False]*4,
[False, True, False, False],
[False, True, False, False],
[False]*4
]
min_path(mx, (2, 0), (0, 3)) returns the integer 4
min_path(mx, (3, 1), (0, 1)) returns the integer 3
min_path(mx, (0, 0), (3, 3)) returns the integer 4
"""
inf = 1e100
def min_path(matrix, a, b, visited=[]):
if (a[0]<0 or len(matrix ) <= a[0] or a[1]<0 or len(matrix[0]) <= a[1]):
return inf
if a in visited:
return inf
if matrix[a[0]][a[1]]:
return inf
if a == b:
return 0
visited.append(a)
potNW = (a[0]-1, a[1]-1); potNN = (a[0], a[1]-1); potNE = (a[0]+1, a[1]-1)
potWW = (a[0]-1, a[1] ); potEE = (a[0]+1, a[1] )
potSW = (a[0]-1, a[1]+1); potSS = (a[0], a[1]+1); potSE = (a[0]+1, a[1]+1)
l = [potNW, potNE,\
potSW, potSE,\
potNN, potWW, potEE, potSS]
r = inf
for t in l:
r = min(r, min_path(matrix, t, b, visited[:]))
return r+1
"""
mx = [\
[False]*4,\
[False, True, False, False],\
[False, True, False, False],\
[False]*4\
]
print(min_path(mx, (2, 0), (0, 3)))
print(min_path(mx, (3, 1), (0, 1)))
print(min_path(mx, (0, 0), (3, 3)))
"""
| true |
c0896304188088cb6bfa4644741f6ac469b07a28 | absupriya/Applied-Algorithms | /1. Bubble sort/bubble_sort.py | 2,273 | 4.375 | 4 | #Reading the entire input file
orig_file=open('input.txt','r').readlines()
#Convert the input data from strings to integer data type
orig_file = list(map(int, orig_file))
#Create an empty list to hold the average elapsed time and the number of inputs
avg_elap_time_list=[]
num_of_inputs_to_sort=[]
#Setting up the array length in the frequency of 500
for alen in range(500,10001,500):
#Filtering out the requisite input data to be sorted from the original array list.
file=orig_file[0:alen]
#Running the algorithm to run for the same input data 3 times.
for runs in range(3):
elapsed_time=0
#Calculation of the running time.
"""Below 2 lines of code to calculate the running time was referred to in the website
https://stackoverflow.com/questions/15707056/get-time-of-execution-of-a-block-of-code-in-python-2-7"""
import timeit
start_time = timeit.default_timer()
#Bubble sort begins
#Reading through the entire array of numbers
for i in range(0,alen):
#Reading through the array list from the end
for j in range(alen-1,i,-1):
if file[j] < file[j-1]:
file[j], file[j-1] = file[j-1], file[j]
#Bubble sort ends
#Calculating the elapsed time
stop_time = timeit.default_timer()
run_time = stop_time - start_time
elapsed_time=+ run_time
#Calculate the average elapsed time for each iterations
avg_elapsed_time=round((elapsed_time/3),6)
#Append the time and number of inputs to a list for plotting graphs
avg_elap_time_list.append(avg_elapsed_time)
num_of_inputs_to_sort.append(alen)
#importing pyplot package from matplotlib library.
"""Below code to plot the graph was referred to in the website
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot"""
import matplotlib.pyplot as plt
#Defining the x-axis and y-axis data and labels to plot the graph
x=num_of_inputs_to_sort
y=avg_elap_time_list
plt.plot(x, y,'r')
plt.xlabel('Number of Inputs')
plt.ylabel('Time')
plt.title("Bubble sort running time versus the number of inputs")
plt.show() | true |
77eeda8905113f1cbd1d2fe1e13685c814ebe662 | denisefavila/python-playground | /src/linked_list/swap_nodes_in_pair.py | 720 | 4.125 | 4 | from typing import Optional
from src.linked_list.node import Node
def swap_pairs(head: Optional[Node]) -> Optional[Node]:
"""
Given a linked list, swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes
(i.e., only nodes themselves may be changed.)
"""
dummy = previous_node = Node(0, head)
while previous_node.next and previous_node.next.next:
current_node = previous_node.next
next_node = current_node.next
previous_node.next = current_node.next
current_node.next = next_node.next
next_node.next = current_node
previous_node = current_node
return dummy.next
| true |
45c1771c5a496bf65e92c07f5fcb8a6d5891f5f4 | chuanski/py104 | /LPTHW/2017-04-26-10-31-18.py | 1,422 | 4.53125 | 5 | # -*- coding: utf-8 -*-
# [Learn Python the Hard Way](https://learnpythonthehardway.org/book)
# [douban link](https://book.douban.com/subject/11941213/)
# ex6.py Strings and Text
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
yy = 'Those who know %s and those who %s.' % (binary, do_not)
yysq = "Those who know %s and those who %s."
#yysq_1 = "Those who know %s and those who %s." % (binary)
yydq = 'Those who know %s and those who %s.'
# - seems that there is no difference between ' and " \
# except which kind of quotation you want to output in the whole sentence.
# - if there are no arguements after the formatting string, the '%s' will be \
# considered as a string but not a format declaration
# - if the number of arguments does not match that of the formatting strings, \
# the interpreter will report an error.
print x
print y
print yy
print yysq
print yydq
print "I said: %r." % x
print "I also said: '%s'." % y
print "I also said: '"' I said: %s."' % y
print "I also said: ' I said: '%r'." % y
# single and double quotations are used consecutively.
hilarious = False # the first letter 'F' is uppercase.
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w+e
# CHANGELOG
#
# - 2017-04-26 --create
| true |
4504fdabb7ca47f4c3e20e13050b12971cadb240 | BhagyeshDudhediya/PythonPrograms | /5-list.py | 2,285 | 4.5625 | 5 | #!/usr/bin/python3
import sys;
# Lists are the most versatile of Python's compound data types.
# A list contains items separated by commas and enclosed within square brackets ([]).
# To some extent, lists are similar to arrays in C.
# One of the differences between them is that all the items belonging to a list can be of different data type.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print ("list: ", list) # Prints complete list
print ("list[0]: ", list[0]) # Prints first element of the list
print ("list[1:3]: ", list[1:3]) # Prints elements starting from 2nd till 3rd
print ("list[2:]: ", list[2:]) # Prints elements starting from 3rd element
print ("tinylist *2: ", tinylist * 2) # Prints list two times
print ("list + tinylist: ", list + tinylist) # Prints concatenated lists
# Lists in python are read-write list, we can change the value of a list variable
list[3] = 'xyz'
print (list)
### TUPLES IN PYTHON ###
print ("\n\n## TUPLES ##")
# A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas.
# Unlike lists, however, tuples are enclosed within parenthesis.
# The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed,
# while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print ("tuple: ", tuple) # Prints complete tuple
print ("tuple[0]: ", tuple[0]) # Prints first element of the tuple
print ("tuple[1:3]: ", tuple[1:3]) # Prints elements starting from 2nd till 3rd
print ("tuple[2:]: ", tuple[2:]) # Prints elements starting from 3rd element
print ("tinytuple *2: ", tinytuple * 2) # Prints tuple two times
print ("tuple + tinytuple: ", tuple + tinytuple) # Prints concatenated tuples
# Tuples are just readbale, one cannot modify any element in tuple
# Following line when uncommented throws error: TypeError: 'tuple' object does not support item assignment
# tuple[2] = 123
| true |
ed871e8bf632e9db119245d7b68af57af885343a | BhagyeshDudhediya/PythonPrograms | /2-quoted-strings.py | 994 | 4.3125 | 4 | #!/usr/bin/python
# A program to demonstrate use of multiline statements, quoted string in python
import sys;
item_1 = 10;
item_2 = 20;
item_3 = 30;
total_1 = item_1 + item_2 + item_3;
# Following is valid as well:
total_2 = item_1 + \
item_2 + \
item_3 + \
10;
print("total_1 is:", total_1);
print("\ntotal_2 is:", total_2, "\nDone..");
# NOTE: Python does not have multi-line comment feature in it.
# Following is the way quotations are used for a string
# Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
# as long as the same type of quote starts and ends the string.
# The triple quotes are used to span the string across multiple lines
word = 'word'
statement = "This is a statement";
multiline_string = """This is a multi-line string
You can call it a paragraph if you wish..!!
Choice is yours..:P""";
print("\n\nWord:", word, "\n\nStatement:", statement, "\n\nMulti-line string: ", multiline_string);
| true |
4df0cac6d76dda3a1af63e399d508cec7159e781 | BhagyeshDudhediya/PythonPrograms | /18-loop-cntl-statements.py | 2,145 | 4.53125 | 5 | #!/usr/bin/python3
# The Loop control statements change the execution from its normal sequence. When the execution leaves a scope,
# all automatic objects that were created in that scope are destroyed.
# There are 3 loop control statements:
# 1. break, 2. continue, 3. pass
# BREAK STATEMENT
# The break statement is used for premature termination of the current loop. After abandoning the loop,
# execution at the next statement is resumed, just like the traditional break statement in C.
# The most common use of break is when some external condition is triggered requiring a hasty exit from a loop.
# The break statement can be used in both while and for loops.
# If you are using nested loops, the break statement stops the execution of the innermost loop and
# starts executing the next line of the code after the block.
print ('Break Statement:');
my_num=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
print ('list', numbers);
for num in numbers:
if num==my_num:
print ('number',my_num,'found in list')
break
else:
print ('number',my_num,'not found in list')
# CONTINUE STATEMENT
# The continue statement in Python returns the control to the beginning of the current loop.
# When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.
# The continue statement can be used in both while and for loops.
print ('\nContinue Statement:');
var = 10 # Second Example
while var > 0:
var = var - 1;
if var == 5:
print ("var == 5, so continue..")
continue
print ('Current variable value :', var)
# PASS STATEMENT
# It is used when a statement is required syntactically but you do not want any command or code to execute.
# The pass statement is a null operation; nothing happens when it executes. The pass statement is also
# useful in places where your code will eventually go, but has not been written yet i.e. in stubs).
print ('\nPass Statement')
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
| true |
49da84798e3df53e56671287c625dc5d725e42f3 | Niloy28/Python-programming-exercises | /Solutions/Q14.py | 578 | 4.1875 | 4 | # Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
# Suppose the following input is supplied to the program:
# Hello world!
# Then, the output should be:
# UPPER CASE 1
# LOWER CASE 9
in_str = input()
words = in_str.split()
upper_letters = lower_letters = 0
for word in words:
for char in word:
if char.isupper():
upper_letters += 1
elif char.islower():
lower_letters += 1
print(f"UPPER CASE {upper_letters}")
print(f"LOWER CASE {lower_letters}")
| true |
345ce55214f53b15b5c95309c21ad414da483d78 | Niloy28/Python-programming-exercises | /Solutions/Q24.py | 528 | 4.125 | 4 | # Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.
# Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
# And add document for your own function
def square(root):
'''Return square of root
The input must be an integer'''
return root ** 2
print(abs.__doc__)
print(round.__doc__)
print(square.__doc__)
| true |
da81d7c444c0465736cf3fc0e085db8fa8c607e1 | Niloy28/Python-programming-exercises | /Solutions/Q22.py | 692 | 4.40625 | 4 | # Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# or:2
# to:1
from collections import defaultdict
frequency = dict()
s = input()
words = s.split()
for word in words:
frequency[word] = frequency.get(word, 0) + 1
keys = frequency.keys()
keys = sorted(keys)
for key in keys:
print(f"{key}:{frequency[key]}")
| true |
b2ba0782b339b8a9d555378872260f0bae6852e6 | Niloy28/Python-programming-exercises | /Solutions/Q53.py | 603 | 4.3125 | 4 | # Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument.
# Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
class Shape(object):
def __init__(self, length=0):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length ** 2
shape = Shape()
square = Square(3)
print(f"{shape.area():.2f}")
print(f"{square.area():.2f}")
| true |
0870d3f73baba9157e9efc8e59cdf6bf630af41a | Niloy28/Python-programming-exercises | /Solutions/Q57.py | 365 | 4.40625 | 4 | # Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address.
# Both user names and company names are composed of letters only.
import re
email_id = input()
pattern = r"([\w._]+)@([\w._]+)[.](com)"
match = re.search(pattern, email_id)
if match:
print(match.group(1))
| true |
0b69e07cf5ee6963767afa0539a63c54292fda1d | olayinka91/PythonAssignments | /RunLenghtEncoding.py | 848 | 4.34375 | 4 | """Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.
Write a python function which performs the run length encoding for a given String and returns the run length encoded String.
Provide different String values and test your program
Sample Input Expected Output
AAAABBBBCCCCCCCC 4A4B8C"""
def encode(message):
name = message
output = ''
count = 1
for i in range(len(name)):
if i < len(name)-1 and name[i] == name[i+1]:
count += 1
else:
output += str(count) + name[i]
count = 1
return output
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
| true |
4f701b58fcf157bd5f96991e082a8b00a6bb220c | scottshepard/advent-of-code | /2015/day17/day17.py | 1,869 | 4.125 | 4 | # --- Day 17: No Such Thing as Too Much ---
#
# The elves bought too much eggnog again - 150 liters this time. To fit it all
# into your refrigerator, you'll need to move it into smaller containers.
# You take an inventory of the capacities of the available containers.
#
# For example, suppose you have containers of size 20, 15, 10, 5, and 5 liters.
# If you need to store 25 liters, there are four ways to do it:
#
# 15 and 10
# 20 and 5 (the first 5)
# 20 and 5 (the second 5)
# 15, 5, and 5
#
# Filling all containers entirely, how many different combinations of
# containers can exactly fit all 150 liters of eggnog?
#
# --- Part Two ---
#
# While playing with all the containers in the kitchen, another load of eggnog
# arrives! The shipping and receiving department is requesting as many
# containers as you can spare.
#
# Find the minimum number of containers that can exactly fit all 150 liters of
# eggnog. How many different ways can you fill that number of containers and
# still hold exactly 150 litres?
#
# In the example above, the minimum number of containers was two.
# There were three ways to use that many containers, and so the answer there
# would be 3.
#
# -----------------------------------------------------------------------------
from itertools import combinations
import re
if __name__ == '__main__':
target = 150
fileobject = open('day17.txt')
data = fileobject.read()
containers = [int(x) for x in re.split('\n', data)]
bools = []
lens = []
for i in range(len(containers)):
combos = combinations(containers, i+1)
for combo in combos:
bools.append(sum(combo) == 150)
lens.append(len(combo))
print("Part 1:", sum(bools))
# Correct answer is 1638
print("Part 2:", len([b for n, b in zip(lens, bools) if b and n == 4]))
# Correct answer is 17
| true |
e67363c2be2fc782679324cffb7afa0900c3b493 | NovaStrikeexe/FtermLabs | /Massive.py | 697 | 4.1875 | 4 | import random
n = 0
n = int(input("Enter the number of columns from 2 and more:"))
if n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
else:
m = [][]
for i in range(0, n):
for j in range(0, n):
m[i][j] = random.randint(0, 200)
print("Massive m:\n", m)
"""n = 0
n = int(input("Enter the number of columns from 2 and more:"))
while n < 2:
print("The array must consist of at least two columns !")
n = int(input("Enter the number of columns from 2 and more:"))
#int N.random(0, 200)
m = [[n for _ in range(0, n)] for _ in range(0, n)]
print(m)""" | true |
b51ea3673b3366bc2bc8646a49888b13c2dca444 | sanneabhilash/python_learning | /Concepts_with_examples/inbuild_methods_on_lists.py | 350 | 4.25 | 4 | my_list = [2, 1, 3, 6, 5, 4]
print(my_list)
my_list.append(7)
my_list.append(8)
my_list.append("HelloWorld")
print(my_list)
my_list.remove("HelloWorld") # sorting of mixed list throws error, so removing string
my_list.sort() # The original object is modified
print(my_list) # sort by default ascending
my_list.sort(reverse=True)
print(my_list)
| true |
db7b4af913e90310e154910ef8e11eb52269890b | sanneabhilash/python_learning | /Concepts_with_examples/listOperations.py | 2,139 | 4.40625 | 4 | # List is an ordered sequence of items. List is mutable
# List once created can be modified.
my_list = ["apples", "bananas", "oranges", "kiwis"]
print("--------------")
print(my_list)
print("--------------")
# accessing list using index
print(my_list[0])
print(my_list[3])
# slicing list
print(my_list[1:4])
print(my_list[-2:])
print(my_list[:-2])
print("--------------")
# iterating over list
for item in my_list:
print(item)
print("--------------")
# check if item exists
if "apples" in my_list:
print("Yes")
print("--------------")
# modify list element
my_list[2] = "guava"
print(my_list)
print("---------------")
# list is mutable. try delete an element from list
del my_list[2]
print("list destructor")
# delete list
del my_list
print("--------------")
my_list = ["apples", "bananas", "oranges", "kiwis"]
print("list is mutable. try append an element to an list")
my_list.append("pomegranate")
print(my_list)
print("--------------")
# reverse list
print(my_list[::-1])
print("--------------")
# sort list
print(sorted(my_list))
print("--------------")
# concatenate lists
my_list1 = ["apples", "bananas"]
my_list2 = ["oranges", "kiwis"]
print(my_list1 + my_list2)
print("--------------")
# list index method
my_list = ["apple", "banana", "orange", "kiwi"]
print(my_list.index("orange"))
print("--------------")
# convert a list into set
my_list = ['apples', 'bananas', 'kiwis', 'oranges']
my_list = set(my_list)
print(type(my_list))
print(my_list)
print("--------------")
# convert list to an dictionary
my_list = [['a', "apple"], ['b', "banana"], ['c', "cat"], ['d', "dog"]]
dict1 = dict(i for i in my_list)
print(dict1)
print("--------------")
# convert a list to an string
my_list = ["apple", "banana", "orange", "kiwi"]
strtest = ','.join(my_list)
print(strtest)
# list copy : shallow copy and deep copy methods
import copy
my_list = ["apple", "banana", "orange", "kiwi"]
print("--------------")
new_list = copy.copy(my_list)
print(my_list, id(my_list))
print(new_list, id(new_list))
print("--------------")
new_list = copy.deepcopy(my_list)
print(my_list, id(my_list))
print(new_list, id(new_list)) | true |
01677a7c933fa163221e27a8bea963a35b8888be | oddsorevans/eveCalc | /main.py | 2,991 | 4.34375 | 4 | # get current day and find distance from give holiday (christmas) in this case
from datetime import date
import json
#made a global to be used in functions
holidayList = []
#finds the distance between 2 dates. Prints distance for testing
def dateDistance(date, holiday):
distance = abs(date - holiday).days
print(distance)
return distance
#The holiday has a dummy year, since that could change depending on the current date.
#To get around that, the program finds the year of the next time the holiday will occur
#dependent on the date given
def findYear(date, holiday):
if date.month < holiday.month:
holiday = holiday.replace(date.year)
elif date.month > holiday.month:
holiday = holiday.replace(date.year + 1)
else:
if date.day > holiday.day:
holiday = holiday.replace(date.year + 1)
else:
holiday = holiday.replace(date.year)
return holiday
#check if a given variable is in the list, and return true or false
def findInList(list, variable):
present = False
for i in list:
if i == variable:
present = True
return present
#get user input
def userInput():
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
#keep window open until they get the correct answer
correctInput = False
while correctInput == False:
if desired == "options":
print(holidayList)
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
else:
if findInList(holidayList, desired) == True:
correctInput = True
else:
print("That is not a valid holiday")
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
return desired
def main():
#take contents of json and load into dictionary
holidayDict = {}
scratch = open("holidays.json", 'r')
temp = scratch.read()
holidayDict = (json.loads(temp))
#create list with all the titles so that the user knows input options
#as well as something to check their input on
for i in holidayDict["holidayList"]:
holidayList.append(i)
desired = userInput()
print(holidayDict["holidayList"][desired])
#d1 can be altered to custom date to test year finding function
d1 = date.today()
#1 is a dummy year. Will be used to check if it is a user created year
holiday = date(holidayDict["holidayList"][desired]["year"],holidayDict["holidayList"][desired]["month"],holidayDict["holidayList"][desired]["day"])
holiday = findYear(d1, holiday)
eve = "Merry " + desired
#print out eve for distance. If date distance is 0, it is that day
#and never concatenates eve
for i in range(0, dateDistance(d1, holiday)):
eve = eve + " eve"
eve = eve + "!"
print(eve)
main() | true |
70fec296d60c640fc3f7886ee624a2ca90a16799 | pdeitel/PythonFundamentalsLiveLessons | /examples/ch02/snippets_py/02_06.py | 1,577 | 4.15625 | 4 | # Section 2.6 snippets
name = input("What's your name? ")
name
print(name)
name = input("What's your name? ")
name
print(name)
# Function input Always Returns a String
value1 = input('Enter first number: ')
value2 = input('Enter second number: ')
value1 + value2
# Getting an Integer from the User
value = input('Enter an integer: ')
value = int(value)
value
another_value = int(input('Enter another integer: '))
another_value
value + another_value
bad_value = int(input('Enter another integer: '))
int(10.5)
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
| true |
4a9dddf948d68d000c1da8065c0d4762eba63a8c | lokesh-pathak/Python-Programs | /ex21.py | 516 | 4.21875 | 4 | # Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it.
# Represent the frequency listing as a Python dictionary.
# Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
def char_freq(str):
frequency = {}
for n in str:
key = frequency.keys()
if n in key:
frequency[n] += 1
else:
frequency[n] = 1
return frequency
#test
print char_freq('abbabcbdbabdbdbabababcbcbab')
print char_freq('qqqqqqqqqbuyfcvadkdnigfnclddncidug')
| true |
0bdc8ceb19ab6e4f6f305bc33ca8682917661dff | lokesh-pathak/Python-Programs | /ex41.py | 1,135 | 4.21875 | 4 | # In a game of Lingo, there is a hidden word, five characters long.
# The object of the game is to find this word by guessing,
# and in return receive two kinds of clues:
# 1) the characters that are fully correct, with respect to identity as well as to position, and
# 2) the characters that are indeed present in the word, but which are placed in the wrong position.
# Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of
# 1) and ordinary parentheses to mark characters correct in the sense of
# 2) Assuming, for example, that the program conceals the word "tiger",
# you should be able to interact with it in the following way:
# snake
# Clue: snak(e)
# fiest
# Clue: f[i](e)s(t)
# times
# Clue: [t][i]m[e]s
# tiger
# Clue: [t][i][g][e][r]
def lingo():
word='tiger'
guess=raw_input()
while guess!=word:
pos=-1
output=''
for char in guess:
pos+=1
if char in word:
if word[pos]==guess[pos]:
output+='['+char+']'
else:
output+='('+char+')'
else:
output+=char
print 'clue:' +output
guess=raw_input()
print 'Found!'
#test
lingo()
| true |
8eafb237ab16ac14decc606b7ee80e4e82119196 | lokesh-pathak/Python-Programs | /ex33.py | 918 | 4.84375 | 5 | # 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 user 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 re
def Semordnilap():
f=open('file_path','r+')
file=f.readlines()
for line in file:
line = line.strip()
z=list(line.split())
for word in z:
p=word[::-1]
for x in z:
if x==p:
print [word,x]
print ("the line is not semordnilap")
f.close()
#test
# Semordnilap('stressed','desserts')
# Semordnilap('stressed','dessert')
Semordnilap()
| true |
97d90fb94f6427ae1c13eba623ea4e9ce7665670 | lokesh-pathak/Python-Programs | /ex1.py | 269 | 4.28125 | 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.
def max(num1, num2):
if num1 > num2:
return num1
else:
return num2
#test
print max(3, 5)
print max(10, 6)
| true |
d242694b3d8ac4b4a5ed9c01c00269ee4c6dca2d | GanLay20/The-Python-Workbook-1 | /pyworkbookex003.py | 226 | 4.125 | 4 | print("The area calculator")
lenth = float(input("Enter The Lenth In Feet >>> "))
width = float(input("Enter The Width In Feet >>> "))
print(lenth)
print(width)
area = lenth * width
print("The Area Is: ", area, " Square Feet") | true |
87e9c3980f14dde7910ba0314d7dd24427849ba2 | GanLay20/The-Python-Workbook-1 | /pyworkbookex014.py | 381 | 4.3125 | 4 | print("Enter you height in FEET followed by INCHES")
feet_height = int(input("Feet:\n>>> "))
inch_height = int(input("Inches:\n>>> "))
print("Your height is", feet_height, "feet", inch_height, "inches\n")
# 1 inch = 2.54cm // 1 foot = 30.48
feet_cm = feet_height * 30.48
inch_cm = inch_height * 2.54
total_height = feet_cm + inch_cm
print("Your height is", total_height, "cm") | true |
276158e1754954c9cb1017c535d83bdaaff28867 | Iboatwright/mod9homework | /sum_of_numbers.py | 1,750 | 4.53125 | 5 | # sum_of_numbers.py
# Exercise selected: Chapter 10 program 3
# Name of program: Sum of Numbers
# Description of program: This program opens a file named numbers.dat
# that contains a list of integers and calculates the sum of all the
# integers. The numbers.dat file is assumed to be a string of positive
# integers separated by \n.
#
# Ivan Boatwright
# March 19, 2016
def main():
# Local variables
fileName = 'numbers.dat'
nums = []
numSum = 0
# Display the intro to the user.
fluffy_intro()
# Assign the integer contents of the file to the nums array.
get_file_contents(fileName, nums)
# Store the sum of the nums array in the numSum variable.
numSum = sum(nums)
# Display the results to the user.
display_results(fileName, numSum)
return None
# Displays an introduction to the program and describes what it does.
def fluffy_intro():
print('Welcome to the Sum of Numbers program.')
print('This program opens the numbers.dat file and displays')
print('the sum of the integers read from the file.')
return None
# This module accepts the filename and an array by reference as parameters.
# It opens the file, splits the string of integers by the '\n' delimiter,
# converts each string into an integer and stores them in the nums list.
def get_file_contents(fName, nums):
with open(fName,'r') as f:
nums.extend([int(x) for x in f.read().split('\n')[:-1]])
return None
# Displays the summation results to the user.
def display_results(fName, numSum):
sep = '\n\n{}\n\n'.format('-'*79)
print('{0}The sum of all the integers in the {1} file is: {2:>23} {0}'
''.format(sep, fName, numSum))
return None
# Call the main program.
main() | true |
c292b92e7d84623749c1c4c704cbfa33f0b01017 | Roman-Rogers/Wanclouds | /Task - 2.py | 522 | 4.34375 | 4 | names = ['ali Siddiqui', 'hamza Siddiqui', 'hammad ali siDDiqui','ghaffar', 'siddiqui ali', 'Muhammad Siddique ahmed', 'Ahmed Siddiqui']
count = 0
for name in names: # Go through the List
lowercase=name.lower() # Lower Case the string so that it can be used easily
splitname=lowercase.split() # Split the name in first, middle, lastname and so on...
length=len(splitname) # Calculate the length so that we search just lastname
if splitname[length-1] == 'siddiqui': # Condition to count names with last name siddiqui
count=count+1
print (count)
| true |
ff2ae3318ec47aefe5035cf1ee4f7ea92bcc3291 | Jay168/ECS-project | /swap.py | 306 | 4.125 | 4 | #swapping variables without using temporary variables
def swapping(x,y):
x=x+y
y=x-y
x=x-y
return x,y
a=input("input the first number A:\n")
b=input("input the second number B:\n")
a,b=swapping(a,b)
print "The value of A after swapping is:",a
print "The value of B after swapping is:",b
| true |
1a233003afdf53e979e155a2c8122012183de4c5 | anurag3753/courses | /david_course/Lesson-03/file_processing_v2.py | 850 | 4.3125 | 4 | """In this new version, we have used the with statement, as with stmt
automatically takes care of closing the file once we are done with the file.
"""
filename = "StudentsPerformance.csv"
def read_file_at_once(filename):
"""This function reads the complete file in a single go and put it into a
text string
Arguments:
filename {str} -- Name of the file
"""
with open(filename, 'r') as f:
data = f.read()
print (data)
# Way 1
read_file_at_once(filename)
def read_file_line_by_line(filename):
"""This function reads the file line-by-line
Arguments:
filename {str} -- Name of file
"""
with open(filename, 'r') as f:
for line in f:
print(line, end='') # It removes the addition of extra newline while printing
# Way 2
read_file_line_by_line(filename) | true |
ca9f27843c8dd606097931adad722688d36d060a | pankajiitg/EE524 | /Assignment1/KManivas_204102304/Q09.py | 676 | 4.40625 | 4 | ## Program to multiply two matrices
import numpy as np
print("Enter the values of m, n & p for the matrices M1(mxn) and M2(nxp) and click enter after entering each element:")
m = int(input())
n = int(input())
p = int(input())
M1 = np.random.randint(1,5,(m,n))
M2 = np.random.randint(1,5,(n,p))
M = np.zeros((m,p),dtype='int16')
print(M1)
print(M2)
print(M)
for i in range(m):
for j in range(p):
for k in range(n):
M[i,j] = M[i,j] + (M1[i,k]*M2[k,j])
print("The elements of resultant matrix, M, using manual calculations is:")
print(M)
print("The elements of resultant matrix, M, using inbuilt function is:")
print(np.matmul(M1,M2))
| true |
50e26426d5913ff0252d1e05fd3d4a26afd04ed1 | pankajiitg/EE524 | /Assignment1/KManivas_204102304/Q03.py | 294 | 4.46875 | 4 | ##Program to print factorial of a given Number
def factorial(num):
fact = 1
for i in range(1,num+1):
fact = fact * i
return fact
print("Enter a number to calculate factorial:")
num1 = int(input())
print("The factorial of ", num1, "is ", factorial(num1))
| true |
a1e0a66a58a5e0d96ddbd2a07424b9b313912a23 | nova-script/Py-Check-IO | /01_Elementary/08.py | 1,247 | 4.46875 | 4 | """
# Remove All Before
## Not all of the elements are important.
## What you need to do here is to remove from the list all of the elements before the given one.
## For the illustration we have a list [1, 2, 3, 4, 5] and we need to remove all elements
## that go before 3 - which is 1 and 2.
## We have two edge cases here: (1) if a cutting element cannot be found,
## then the list shoudn't be changed. (2) if the list is empty, then it should remain empty.
- Input: List and the border element.
- Output: Iterable (tuple, list, iterator ...).
"""
def remove_all_before(items: list, border: int) -> list:
if border not in items:
return items
else:
return items[items.index(border):]
# These "asserts" are used for self-checking and not for an auto-testing
assert list(remove_all_before([1, 2, 3, 4, 5], 3)) == [3, 4, 5]
assert list(remove_all_before([1, 1, 2, 2, 3, 3], 2)) == [2, 2, 3, 3]
assert list(remove_all_before([1, 1, 2, 4, 2, 3, 4], 2)) == [2, 4, 2, 3, 4]
assert list(remove_all_before([1, 1, 5, 6, 7], 2)) == [1, 1, 5, 6, 7]
assert list(remove_all_before([], 0)) == []
assert list(remove_all_before([7, 7, 7, 7, 7, 7, 7, 7, 7], 7)) == [7, 7, 7, 7, 7, 7, 7, 7, 7] | true |
0f882f1f2a162f6fac61d29a40ae0a44b7c6b771 | Tarunmadhav/Python1 | /GuessingGame.py | 419 | 4.25 | 4 | import random
number=random.randint(1,9)
chances=0
print("Guess A Number Between 1-9")
while chances<5:
guess=int(input("Guess A Number 1-9"))
if(guess==number):
print("Congratulations")
break
elif(guess<number):
print("Guess Higher Number")
else:
print("Guess Lesser Number")
chances+=1
if(chances>5):
print("You Loose and The Number is",number) | true |
3c3182c02d122f69bc1aecb800ceb778ccaa6968 | sr-murthy/inttools | /arithmetic/combinatorics.py | 1,277 | 4.15625 | 4 | from .digits import generalised_product
def factorial(n):
return generalised_product(range(1, n + 1))
def multinomial(n, *ks):
"""
Returns the multinomial coefficient ``(n; k_1, k_2, ... k_m)``, where
``k_1, k_2, ..., k_m`` are non-negative integers such that
::
k_1 + k_2 + ... + k_m = n
This number is the coefficient of the term
::
x_1^(k_1)x_2^(k_2)...x_m^(k_m)
(with the ``k_i`` summing to ``n``) in the polynomial expansion
::
(x_1 + x_2 + ... x_m)^n
The argument ``ks`` can be separate non-negative integers adding up to the
given non-negative integer ``n``, or a list, tuple or set of such
integers prefixed by ``'*'``, e.g. ``*[1, 2, 3]``.
"""
return int(factorial(n) / generalised_product(map(factorial, ks)))
def binomial(n, k):
"""
Returns the familiar binomial cofficient - the number of ways
of choosing a set of ``k`` objects (without replacement) from a set of
``n`` objects.
"""
return multinomial(n, k, n - k)
def binomial2(n, k):
"""
Faster binomial method using a more direct way of calculating factorials.
"""
m = min(k, n - k)
return int(generalised_product(range(n - m + 1, n + 1)) / generalised_product(range(1, m + 1))) | true |
4e39eb65f44e423d9695653291c6c15b95920df2 | rocket7/python | /S8_udemy_Sets.py | 695 | 4.1875 | 4 | ###############
# SETS - UNORDERED AND CONTAINS NO DUPLICATES
###############
# MUST BE IMMUTABLE
# CAN USE UNION AND INTERSECTION OPERATIONS
# CAN BE USED TO CLEAN UP DATA
animals = {"dog", "cat", "lion", "elephant", "tiger", "kangaroo"}
print(animals)
birds = set(["eagle", "falcon", "pigeon", "bluejay", "flamingo"])
print(birds)
for animal in birds:
print(animal)
birds.add("woodpecker")
animals.add("woodpecker")
print(animals)
print(birds)
# In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B.
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
A = set(a)
B = set(b)
print(A.difference(B))
| true |
dcd02ef61c6b2003024857d5132f8f4d8cf72e01 | venkat284eee/DS-with-ML-Ineuron-Assignments | /Python_Assignment2.py | 605 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1:
# Create the below pattern using nested for loop in Python.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
# In[1]:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
# Question 2:
#
# Write a Python program to reverse a word after accepting the input from the user.
# In[3]:
value = input("Enter a string: " )
for i in range(len(value) -1, -1, -1):
print(value[i], end="")
print("\n")
| true |
faffa16c4ee560cb5fdb32013893bbf83e947ba1 | mrparkonline/py_basics | /solutions/basics1/circle.py | 300 | 4.46875 | 4 | # Area of a Circle
import math
# input
radius = float(input('Enter the radius of your circle: '))
# processing
area = math.pi * (radius ** 2)
circumference = 2 * math.pi * radius
# output
print('The circle area is:', area, 'units squared.')
print('The circumference is:', circumference, 'units.') | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.