blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e4bc895b6c639fda81703d162b07034888231d50 | Laurensvaldez/PythonCrashCourse | /CH8: Functions/try_it_yourself_ch8_8_8.py | 986 | 4.375 | 4 | # Start with your program from exercise 8-7. Write a while loop that allows users to enter an album's artist and title.
# Once you have that information, call make_album() with the user's input and print the dictionary that's created.
# Be sure to include a quit value in the while loop.
def make_album(artist, title, tracks=0):
"""Return an artist name and an album title in a dictionary"""
book = {
'name_artist': artist.title(),
'name_album': title.title()}
if tracks:
book['tracks'] = tracks
return book
# prepare the prompts.
title_prompt = "\nWhat album are you thinking of? "
artist_prompt = "Who's the artist? "
# Let the user know how to quit.
print("Enter 'quit' at any time to stop.")
while True:
title = input(title_prompt)
if title == 'quit':
break
artist = input(artist_prompt)
if artist == 'quit':
break
album = make_album(artist, title)
print(album)
print("\nThanks for responding!") | true |
9cb4ce71d22344f24e1d3cc338bb9e83ed1ad3ad | Laurensvaldez/PythonCrashCourse | /CH8: Functions/making_pizzas.py | 1,837 | 4.3125 | 4 | # In this file we will import the function of pizza_import.py
import pizza_import
print("Importing all the functions in the module")
pizza_import.make_pizza(16, 'pepperoni')
pizza_import.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
print("-------------------------------------------")
# To use the import the following syntax is necessary:
# module_name.function_name()
# You can also import a specific function from a module. Here's the general syntax for this approach:
# from module_name import function_name
# You can import as many functions as you want from a module by seperating each function's name with a comma:
# from module_name import function_0, function_1, function_2
# Using 'as' to Give a Function an Alias
# Here we give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The 'as' keyword renames a
# function using the alias you provide.
from pizza_import import make_pizza as mp
print("Importing specific function under an alias")
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
# The general syntax for providing an alias is:
# from module_name import function_name as fn
print("-------------------------------------------")
# You can also provide an alias for a module name.
# Such as:
import pizza_import as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# The general syntax for providing an alias for a module is:
# import module_name as mn
print("-------------------------------------------")
# You can tell Python to import every function in a module by using the asterisk (*) operator
# Example:
from pizza_import import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# The general syntax for providing this import is:
# from module_name import * | true |
146541bd8096d3dada3b6b651f7d74caf3d8fe68 | Laurensvaldez/PythonCrashCourse | /CH9: Classes/9-6_ice_cream_stand.py | 2,095 | 4.5625 | 5 | # Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 or Exercise 9-4
# Either version of the class will work; just pick the one you like better
class Restaurant:
"""A simple restaurant class"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant name and cuisine type"""
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type
# Add an attribute called number_served with a default value of 0
self.number_served = 0
def describe_restaurant(self):
print("The restaurant is called " + self.restaurant_name + ".")
print("And the cuisine type is " + self.cuisine_type + ".")
def open_restaurant(self):
print("The restaurant " + self.restaurant_name.title() + " is open.")
def customers_served(self):
print("The restaurant has served " + str(self.number_served) + " people.")
def set_number_served(self, served_update):
"""Add a method called set_number_served() that lets you set the number of customers that have been served"""
self.number_served = served_update
def increment_number_served(self, increment_served):
"""Method lets you increment the number of customers who's been served."""
self.number_served += increment_served
class IceCreamStand(Restaurant):
"""An Ice Cream Stand, with a class of a restaurant."""
# Add an attribute called flavors that stores a list of ice cream flavors
def __init__(self, name, cuisine_type='ice_cream'):
super().__init__(name, cuisine_type)
self.flavors = []
# Write a method that displays these flavors
def display_flavors(self):
"""Method that displays the flavors available."""
for flavor in self.flavors:
print("- " + flavor.title())
# Create an instance of IceCreamStand, and call this method
big_one = IceCreamStand('The Big One')
big_one.flavors = ['vanilla', 'chocolate', 'black cherry']
big_one.describe_restaurant()
big_one.display_flavors() | true |
f14e51cff185f2277385b1a0d580fd0a077e7195 | Laurensvaldez/PythonCrashCourse | /Ch6: Dictionaries/try_it_yourself_ch6_6_1.py | 514 | 4.3125 | 4 | # Try it yourself challenge 6-1
# Person
# Use a dictionary to store information about a person you know.
# Store their first name, last name, age, and the city in which they live. You should have keys such as
# first_name, last_name, age, and city. Print each piece of information stored in your dictionary.
person = {
'first_name': 'Elba',
'last_name': 'Lopez',
'age': 23,
'city': 'Rotterdam',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city']) | true |
755616213684796cb48d924e5bf927e994e030d1 | Laurensvaldez/PythonCrashCourse | /CH4: working with lists/try_it_yourself_ch4_4_11.py | 500 | 4.21875 | 4 | print ("More Loops")
# all versions of foods.py in this section have avoided using for loops when printing to save space
# Choose a version of foods.py, and write two for loops to print each list of foods
my_foods = ['pizza', 'falafel', 'carrot cake']
print ("My favorite foods are: ")
for food in my_foods:
print (food.title())
print("\n")
friends_foods = ['hamburger', 'kapsalon', 'pica pollo']
print("My friend's favorite foods are: ")
for food in friends_foods:
print(food.title())
| true |
2593aeaf239015183c48861a96af3d1feb21d6d3 | Laurensvaldez/PythonCrashCourse | /CH9: Classes/9-5_login_attempts.py | 2,622 | 4.46875 | 4 | # Add an attribute called login_attempts to your User class from Exercise 9-3
class User:
"""A class to describe a user"""
# Create two attributes called first_name and last_name
# and then create several other attributes that are typically stored in a user profile
def __init__(self, first_name, last_name, age, birthplace, relationship_status):
"""Initialize the first name and last name"""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.age = age
self.birthplace = birthplace.title()
self.relationship_status = relationship_status
self.login_attempts = 0
def describe_user(self):
"""This method prints a summary of the user"""
msg_1 = "The user's first name is " + self.first_name + " and his/her last name is " + \
self.last_name
msg_2 = self.first_name + " " + self.last_name + " age is " + str(self.age) + \
" and lives in " + self.birthplace + "."
msg_3 = self.first_name + " " + self.last_name + " is currently " + self.relationship_status + \
"."
print("\n" + msg_1)
print(msg_2)
print(msg_3)
def greet_user(self):
"""This method provides a personalized greeting to the user."""
# print a personalized greeting to the user
greeting = "Hello " + self.first_name + ", I hope you have a wonderful day!"
print(greeting)
def increment_login_attempts(self):
"""Increment the value of login by 1."""
self.login_attempts += 1
# Write another method called reset_login_attempts() that resets the value of login_attempts to 0
def reset_login_attempts(self):
self.login_attempts = 0
# Make an instance of the User class and call increment_login_attempts() several times, and call reset_login_attempts()
laurens = User("Laurens", "Salcedo Valdez", 29, "Rotterdam", "in a relationship")
laurens.describe_user()
laurens.greet_user()
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.increment_login_attempts()
print("Login attempts are: " + str(laurens.login_attempts))
laurens.reset_login_attempts()
print("Login attempts are reset to: " + str(laurens.login_attempts))
# Print login_attempts again to make sure it was reset to 0
print("Login attempts are reset to: " + str(laurens.login_attempts))
| true |
a4ca9323e0c5bbd2cd4f81cb49151482d2a3d802 | phu-mai/calculate | /calculate.py | 777 | 4.125 | 4 | from datetime import datetime
def string_to_date(input):
return datetime.strptime(input, "%d/%m/%Y")
def check_date(input):
if string_to_date(input) < datetime.strptime("01/01/1900", "%d/%m/%Y") or string_to_date(input) > datetime.strptime("31/12/2999", "%d/%m/%Y"):
return False
else:
return True
def date_between(first_date, second_date):
if check_date(first_date) and check_date(second_date):
return abs(string_to_date(first_date) - string_to_date(second_date)).days - 1
else:
print("The valid date range is between 01/01/1900 and 31/12/2999")
if __name__ == "__main__":
print(date_between("2/6/1983", "22/6/1983"))
print(date_between("4/7/1984", "25/12/1984"))
print(date_between("3/1/1989", "3/8/1983"))
| true |
56490d658082b16ec7ec9140147f0e3e0544c630 | subhendu17620/RUAS-sem-04 | /PP/Java/lab03/a.py | 1,391 | 4.1875 | 4 | # Python3 program to print all Duplicates in array
# A class to represent array of bits using
# array of integers
class BitArray:
# Constructor
def __init__(self, n):
# Divide by 32. To store n bits, we need
# n/32 + 1 integers (Assuming int is stored
# using 32 bits)
self.arr = [0] * ((n >> 5) + 1)
# Get value of a bit at given position
def get(self, pos):
# Divide by 32 to find position of
# integer.
self.index = pos >> 5
# Now find bit number in arr[index]
self.bitNo = pos & 0x1F
# Find value of given bit number in
# arr[index]
return (self.arr[self.index] &
(1 << self.bitNo)) != 0
# Sets a bit at given position
def set(self, pos):
# Find index of bit position
self.index = pos >> 5
# Set bit number in arr[index]
self.bitNo = pos & 0x1F
self.arr[self.index] |= (1 << self.bitNo)
# Main function to print all Duplicates
def checkDuplicates(arr):
# create a bit with 32000 bits
ba = BitArray(320000)
# Traverse array elements
for i in range(len(arr)):
# Index in bit array
num = arr[i]
# If num is already present in bit array
if ba.get(num):
print(num, end = " ")
# Else insert num
else:
ba.set(num)
# Driver Code
if __name__ == "__main__":
arr = [1, 5, 1, 10,10000,2,10000,1,5, 12, 10]
checkDuplicates(arr)
# This code is conributed by
# sanjeev2552
| true |
f600b3970b3c556a9aa03af8d6ef7b1f1dd124f7 | MirjaLagerwaard/MountRUSHmore | /main.py | 1,500 | 4.28125 | 4 | import sys
from algorithm import *
if __name__ == "__main__":
# Error when the user did not give the right amount of arguments
if len(sys.argv) <= 1 or len(sys.argv) > 3:
print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>"
exit()
# update fp to the CSV file the user asked for
if sys.argv[1] == "6_1":
fp = "vehicles_6x6_1.csv"
shape = 6
elif sys.argv[1] == "6_2":
fp = "vehicles_6x6_2.csv"
shape = 6
elif sys.argv[1] == "6_3":
fp = "vehicles_6x6_3.csv"
shape = 6
elif sys.argv[1] == "9_1":
fp = "vehicles_9x9_1.csv"
shape = 9
elif sys.argv[1] == "9_2":
fp = "vehicles_9x9_2.csv"
shape = 9
elif sys.argv[1] == "9_3":
fp = "vehicles_6x6_3.csv"
shape = 9
elif sys.argv[1] == "12":
fp = "vehicles_12x12.csv"
shape = 12
else:
print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>"
exit()
# prepare the CSV file before running an algorithm
board = PrepareFile(fp, shape)
# run the algorithm the user asked for
if sys.argv[2] == "breadth":
BreadthFirstSearch(board)
elif sys.argv[2] == "depth":
Run_ReversedIterativeDeepeningDepthFirstSearch(board)
elif sys.argv[2] == "random":
Random(board)
else:
print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>"
exit()
| true |
90bda58a280724875f5ba10d8171e81e093338ac | prince-singh98/python-codes | /ConditionalStatements/DigitAlphabateOrSpecialCharecter.py | 229 | 4.28125 | 4 | char = input("enter a alphabet")
if((char>='a' and char<='z') or (char>='A' and char<='Z')):
print(char,"is alphabet")
elif(char>='0' and char<='9'):
print(char, "is digit")
else:
print(char, "is special character")
| true |
68e536bf4e5f3b3a7f8a853223e83f6f03511a98 | Chrisgo-75/intro_python | /conditionals/switch_or_case.py | 696 | 4.15625 | 4 | #!/usr/bin/env python3
# Index
# Python does not have a "switch" or "case" control structure which
# allows you to select from multiple choices of a single variable.
# But there are strategies that can simulate it.
#
# 1.
def main():
# 1.
choices = dict(
one = 'first',
two = 'second',
three = 'third',
four = 'fourth',
five = 'fifth'
)
print('Looking for "seven" in dictionary. If it doesn\'t exist then print "other":')
v = 'seven'
print(choices.get(v, 'other'))
print()
print('Looking for a key of "five" and if found print it\'s value:')
v = 'five'
print(choices.get(v, 'other'))
print()
if __name__ == '__main__': main() | true |
85145d7b919824030bb2ce9a1f2132cfadcac9df | Chrisgo-75/intro_python | /general_syntax/strings.py | 1,433 | 4.9375 | 5 | #!/usr/bin/env python3
# Index
# 1. Strings can be created with single or double quotes.
# 2. Can introduce new line into a string.
# 3. Display escape characters (literally). Use "r" per example below.
# - r == "raw string" which is primarily used in regular expressions.
# 4. Format or replace character in string (Python 3 @ 2 way)
# 5. Define a multi-line string using triple single/double quotes
# 6.
def main():
n = 42
# 1. Single or Double quotes
s = 'This is a string using single quotes!'
print(s)
s1b = "This is also a string using double quotes!"
print(s1b)
print()
# 2. New line in string
s2 = "This is a string\nwhich introduces a new line!"
print(s2)
print()
# 3. Show escape characters (literally)
s3 = r"This is a string that literally displays an escape character \n."
print(s3)
print()
# 4. Format or replace character in string (Python 3 @ 2 way)
s4 = "Inserting variable value in this string ... {} ... Python3 uses curly braces and the string's format method".format(n)
print(s4)
s4b = "Inserting varaible value in this string ... %s ... Python2 uses percents." % n
print(s4b)
print()
# 5. Define a multi-line string using triple single/double quotes
print('This example will display a multi-line (3 lines) example:')
s5 = '''\
First line
Second line
Third line
'''
print(s5)
print()
if(__name__ == "__main__"):
main(); | true |
7a16498f5039f500dbb9b916d5f6a87ba3215c4b | datarocksAmy/APL_Python | /ICE/ICE02/ICE2.py | 2,515 | 4.125 | 4 | '''
* Python Programming for Data Scientists and Engineers
* ICE #2
* Q1 : Frequencies of characters in the string.
* Q2 : Max word length in the string.
* Q3 : Count numbers of digits and characters in the string.
* #11 Chia-Hui Amy Lin
'''
# Prompt user for a sentence
user_input_sentence = input("Please type a sentence you have in mind : ")
# ===================================================================================
# Q1 : Calculate character frequency in a string
characters = list(user_input_sentence)
characters = list(map(lambda x: x.strip(',.'), characters))
characters = " ".join(characters).split()
frequency = {}
for idx in range(len(characters)):
try:
frequency[characters[idx]] += 1
except KeyError:
frequency[characters[idx]] = 1
# Header
print("\n" + "[ Frequency Count ]")
print("------------------------------------------------------")
# Output frequency count for each character in the user input
for key, val in frequency.items():
print("Word " + key + " : " + str(val) + " times")
# ===================================================================================
# Q2 : Take a list of words and return the length of the longest one
wordList = user_input_sentence.split()
wordLenCount = {}
for word in range(len(wordList)):
wordLenCount[wordList[word]] = len(wordList[word])
sort = dict(sorted(wordLenCount.items(), key=lambda x: (-x[1], x[0])))
# Header
print("\n" + "[ Max Word Length ]")
print("------------------------------------------------------")
# Output the max lenght
print("Max word length of this sentence :", list(sort.values())[0])
maxWords = []
for w_key, w_val in sort.items():
if w_val == list(sort.values())[0]:
maxWords.append(w_key)
# Output word(s) with the max length
print("Word(s) with max length :")
for selection in range(len(maxWords)):
print("\t" + maxWords[selection])
# ===================================================================================
# Q3 : Obtain a string and calculate the number of digits and letters
# Header
print("\n" + "[ # of Digits & Letters ]")
print("------------------------------------------------------")
# Filter out the digits in the string
numberList = list(filter(str.isdigit, user_input_sentence))
letterCount = ''.join([letter for letter in user_input_sentence if not letter.isdigit()])
# Output the count for digits and letters in the string
print("Total # of numbers(digits):", len(numberList))
print("Total # of letters:", len(letterCount))
| true |
9094b07c5ef5da96a89870a898db9b9c010dbc45 | datarocksAmy/APL_Python | /Lab Assignment/Lab04/Lab04_b_MashDictionaries.py | 1,293 | 4.125 | 4 | # ------------------------------------------------------------
# * Python Programming for Data Scientists and Engineers
# * LAB #4-b Mash Dictionaries
# * #11 Chia-Hui Amy Lin
# ------------------------------------------------------------
# Dictionary
from statistics import mean
# Function
def mash(input_dict):
''' Function for mashing keys with integer values into one and update the current dictionary in the list. '''
for idx in range(len(input_dict)):
intList = []
popList = []
mash = {}
keyMash = ""
for key, val in inputList[idx].items():
if type(val) is int:
intList.append(val)
popList.append(key)
keyMash += (key + ",")
mash[keyMash] = mean(intList)
input_dict[idx].update(mash)
for num in range(len(popList)):
input_dict[idx].pop(popList[num])
return input_dict
# Input value
inputList = [{"course": "coffee", "Crows": 3, "Starbucks": 7},
{"course": "coffee", "Crows": 4, "Starbucks": 8},
{"course": "coffee", "Crows": 3, "Starbucks": 5}]
print("< #4-b Mash Dictionaries >")
# Call function to mash/update the original list
inputList = mash(inputList)
# Output the result
print("Updated Input :", inputList)
| true |
5db43d9103f910dfeb21e7196142c38fc112af38 | datarocksAmy/APL_Python | /ICE/ICE03/ICE3-2 New List.py | 1,845 | 4.1875 | 4 | '''
* Python Programming for Data Scientists and Engineers
* ICE #3-2 Make new list
* Take in a list of numbers.
* Make a new list for only the first and last elements.
* #11 Chia-Hui Amy Lin
'''
# Function for prompting user for numbers, append and return the list
def user_enter_num(count_prompt, user_num_list):
# Prompt user for a number(integer).
# If it's an invalid input, prompt user again.
flag = False
while True:
user_prompt = input("Please enter 5 numbers : ")
try:
user_prompt = int(user_prompt)
except ValueError or TypeError:
print("Invalid input. Please enter an INTEGER." + "\n")
flag = True
count_prompt -= 1
else:
break
user_num_list.append(user_prompt)
return user_num_list
# Pre-set number list
numbers = [4, 5, 6, 7, 8]
# Variables for customized number list
user_number = []
count = 0
# Continue to call function user_enter_num until the user entered 5 numbers
while count < 5:
user_enter_num(count, user_number)
count += 1
# Output the first and last number of new list from the original one that the user prompted
print("===================================================================")
print("<< User Prompt Number List >>")
print("The Original User Prompt List : ", user_number)
firstLastNumList = user_number[0::len(user_number)-1]
print("New list containing only first and last element(user prompt) : ", firstLastNumList)
# Output the first and last number of new list from the pre-set number list
print("===================================================================")
print("<< Pre-set Number List >>")
print("Original Number List : ", numbers)
presetNumList = numbers[0::len(numbers)-1]
print("New list containing only first and last element(preset) : ", presetNumList)
| true |
dbc3dfae249a74877e71007e05cd933c92d13459 | lelong03/python_algorithm | /array/median_sorted_arrays.py | 2,041 | 4.125 | 4 | # Find median of two sorted arrays of same size
# Objective: Given two sorted arrays of size n.
# Write an algorithm to find the median of combined array (merger of both the given arrays, size = 2n).
# What is Median?
# If n is odd then Median (M) = value of ((n + 1)/2)th item term.
# If n is even then Median (M) = value of [(n/2)th item term + (n/2 + 1)th item term]/2
# Binary Approach: Compare the medians of both arrays?
# - Say arrays are array1[] and array2[].
# - Calculate the median of both the arrays, say m1 and m2 for array1[] and array2[].
# - If m1 == m2 then return m1 or m2 as final result.
# - If m1 > m2 then median will be present in either of the sub arrays.
# - If m2 > m1 then median will be present in either of the sub arrays.
# - Repeat the steps from 1 to 5 recursively until 2 elements are left in both the arrays.
# - Then apply the formula to get the median
# - Median = (max(array1[0],array2[0]) + min(array1[1],array2[1]))/2
def get_median_and_index(l, start, end):
size = end - start + 1
if size % 2 != 0:
index = start+(size+1)/2-1
return index, l[index]
else:
index = start+size/2
return index, (l[index] + l[index+1]) / 2
def find(a, a_start, a_end, b, b_start, b_end):
if (a_end - a_start + 1) == 2 and (b_end - b_start + 1) == 2:
return (max(a[a_start], b[b_start]) + min(a[a_end], b[b_end])) / 2.0
mid_index_a, median_a = get_median_and_index(a, a_start, a_end)
mid_index_b, median_b = get_median_and_index(b, b_start, b_end)
if median_a == median_b:
return median_a * 1.0
if median_a > median_b:
return find(a, a_start, mid_index_a, b, mid_index_b, b_end)
else:
return find(a, mid_index_a, a_end, b, b_start, mid_index_b)
def get_median_of_two_sorted_arrays(array_1, array_2):
return find(array_1, 0, len(array_1)-1, array_2, 0, len(array_2)-1)
if __name__ == '__main__':
arr_1 = [2,6,9,10,11]
arr_2 = [1,5,7,12,15]
print(get_median_of_two_sorted_arrays(arr_1, arr_2))
| true |
0847e2a138d297ceb53d34e5c15004424227907e | lelong03/python_algorithm | /array/next_permutation.py | 1,358 | 4.125 | 4 | # Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
# The replacement must be in-place, do not allocate extra memory.
# Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
def reverse(arr, begin, end):
while begin < end:
arr[begin], arr[end] = arr[end], arr[begin]
begin += 1
end -= 1
def next_permutation(arr, begin, end):
partion_index = end-1
while partion_index > -1 and arr[partion_index] >= arr[partion_index+1]:
partion_index -= 1
if partion_index == -1:
return reverse(arr, begin, end)
change_index = end
while change_index > -1 and arr[change_index] <= arr[partion_index]:
change_index -= 1
arr[change_index], arr[partion_index] = arr[partion_index], arr[change_index]
return reverse(arr, partion_index+1, end)
a = [1,3,4,2]
next_permutation(a, 0, len(a)-1)
print a
a = [1,4,2,3]
next_permutation(a, 0, len(a)-1)
print a
a = [1,2,3,4]
next_permutation(a, 0, len(a)-1)
print a
a = [4,3,2,1]
next_permutation(a, 0, len(a)-1)
print a
a = [5,1,1]
next_permutation(a, 0, len(a)-1)
print a
| true |
429a91d928bbf33f9ddf0c5daea25a8777d65084 | anutha13/Python | /demo.py | 1,058 | 4.21875 | 4 | from time import sleep
from threading import Thread
class Hello(Thread):
def run(self):
for i in range(5):
print("hello")
sleep(1)
class Hi(Thread):
def run(self):
for i in range(5):
print("Hi")
t1=Hello()
t2=Hi()
t1.start() #this is a different thread t1
sleep(0.2)
t2.start() #this is another thread t2
t1.join()
t2.join()
#main thread will not execute until both t1 and t2 will join
print("bye")
#this whole program is using a main thread
#but to run on different core or different threads not in Main thread
#we need Thread as a parent of the Hi and Hello class
# multi-threading
# threading is light-weight process and that process is divided into small parts
# that part is called thread
# can i execute 2 function on different cores at the same time
#zip() zips two list with each other
list=['anu','thakur','king]
num=['ab','cd','ef']
zipped=zip(list,num)
for (a,b) in zipped:
print(a,b)
| true |
5a0140339b66c37c3d1f7056f8a2b8520630d39c | JasleenUT/Encryption | /ElGamal/ElGamal_Alice.py | 1,669 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 20:07:58 2018
@author: jasleenarora
"""
# Read the values from intermediate file
with open('intermediate.txt','r') as f:
content = f.readlines()
p = int(content[0])
g = int(content[1])
a = int(content[2])
c1 = int(content[3])
c2 = int(content[4])
###fast powered
def fastPower(g, A, N):
a=g
b=1
while A>0:
if A%2==1:
b=(b*a)%N
a=(a*a)%N
A=A//2
return b
# This script converts an integer to binary
def int2bin(integer):
if integer == 0:
return('00000000')
binString = ''
while integer:
if integer % 2 == 1:
binString = '1' + binString
else:
binString = '0' + binString
integer //=2
while len(binString)%8 != 0:
binString = '0' + binString
return binString
# Converts binary to integer
def bin2int(binary):
return int(binary,2) # this tells the function that the input 'binary' is in base 2 and it converts it to base 10
# This will convert integer to character
def int2msg(integer):
return bin2msg2(int2bin(integer))
# Write the conversion from binary to character in one line
def bin2msg2(binary):
return ''.join(chr(int(binary[i*8:i*8+8],2)) for i in range(len(binary)//8))
def ElGamal(p,g,a,c1,c2):
# Step1: calculate ((c1)^a)^p-2
temp = fastPower(c1,a,p)
s1 = fastPower(temp,p-2,p)
# Step2: Multiply this by c2
s2 = (s1*c2)%p
# Step3: Convert this to character
msg = int2msg(s2)
print("The decoded message is: ",msg)
ElGamal(p,g,a,c1,c2) | true |
31437cfb86cb0bdd9ce378ba6aacd44a48c1a3dd | opember44/Engineering_4_Notebook | /Python/calculator.py | 1,426 | 4.34375 | 4 | # Python Program 1 - Calculator
# Written by Olivia Pemberton
def doMath (num1, num2, operation):
# defines do math function
# program will need yo to enter 2 numbers to do operation
if operation == 1:
x = round((num1 + num2), 2)
return str(x)
if operation == 2:
x = round((num1 - num2), 2)
return str(x)
if operation == 3:
x = round((num1 * num2), 2)
return str(x)
if operation == 4:
x = round((num1 / num2), 2)
return str(x)
if operation == 5:
x = round((num1 % num2), 2)
return str(x)
# this makes the operation add, subtract, multiply, divide, and find
# the remainder of the two numbers entered
go = "y"
# this sets the variable for the whileloop
print("After calculations is complete, press Enter to go again")
print("Press x then Enter to quit program")
# prints the instructions the user needs to work the calculator
while go == "y":
# starts the calculator
a = float(input("Enter 1st Number: "))
b = float(input("Enter 2nd Number: "))
# the user is told to put in the two numbers
print("Sum:\t\t" + doMath(a,b,1))
print("Difference:\t" + doMath(a,b,2))
print("Product:\t" + doMath(a,b,3))
print("Quotient:\t" + doMath(a,b,4))
print("Modulo:\t\t" + doMath(a,b,5))
# the program run and finds all the answers to the math functions
key = input(" ")
# the program can be run again if the user puts in more numbers
if key == "x":
# the user can end the program by pressing x then enter
break
| true |
d95b1bfa19fa52013079f7d63f7794d1c6736d84 | hectorzaragoza/python | /functions.py | 1,985 | 4.1875 | 4 | #functions allow us to put something into it, does something to it, and gives a different output.
#We start with def to define the function, then we name it, VarName()
#def function(input1, input2, input3,...):
# code
# more code
# return value
#result = functionName(In1, In2, In3,...)
#result = value
def addOne(x): #this line of code simply gives your function a name and inside the parenthesis, the inputs
y = x + 1 #this line of code determines the actual function/manipulation/calculation that you are trying to do.
#Line 12 cont. i.e. what you want to do to your inputs and assign that to a new variable which will then be returned
return y #this line of code returns the output of your function
def addTogether(in1, testin2):
inter = in1 + testin2
return inter
testValue = 2 #this is going to be the variable we put into our addOne function, whose result is assigned in result
result = addOne(testValue) #y = testValue + 1 -> 2+1 -> 3
print(result)
secondTwo = addTogether(testValue, result) #secondTwo is a variable that will store the result of inputting testValue
#and result into the addTogether function defined in line 16.
print(secondTwo)
print(addTogether("Hello"," World!"))
print(addTogether("Hello",str(1)))
#exercise
#Write a function that takes two inputs and returns their sum
def SumFunction(VarOne, Vartwo):
varthree = VarOne + Vartwo
return varthree
open = 1
close = 2
EndProduct = SumFunction(open, close)
print(EndProduct)
#Write a function that takes an input and checks how many times the input is divisible by 3 and by 5. It then returns
#those two values
def aFunction(InputA):
DivByThree = int(InputA/3) #You can have multiple things done to an input within a single function and return
#multiple results for tall those things as in this example.
DivByFive = int(InputA/5)
return DivByThree, DivByFive
Divisible = aFunction(489)
print(Divisible)
print(163*3, 97*5) #testing result
| true |
ef58048b8b05de8a3239b61c320f601d02da1daa | manjushachava1/PythonEndeavors | /ListLessThanTen.py | 498 | 4.21875 | 4 | # Program 3
# Take a list and print out the numbers less than 5
# Extras:
# 1. Write program in one line of code
# 2. Ask the user for a number and return a list that contains elements that are smaller than that user number.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
c = []
# Extra 1
for element in a:
if element < 5:
b.append(element)
print(b)
# Extra 2
num = int(input("Enter a random number: "))
for element in a:
if element < num:
c.append(element)
print(c) | true |
7f66d0d287df330aaad8d58a3d74308a85171942 | JavaScriptBach/Project-Euler | /004.py | 518 | 4.125 | 4 | #coding=utf-8
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(num):
string = str(num)
for i in range(0, len(string) / 2):
if string[i] != string[len(string) - 1 - i]:
return False
return True
num = 0
for i in range(100, 1000):
for j in range(100, 1000):
if is_palindrome(i * j) and i * j > num:
num = i * j
print num | true |
592e65372e0cbbbbaaaa50e61b16a4546e6301a5 | pgiardiniere/notes-WhirlwindTourOfPython | /06-scalarTypes.py | 2,782 | 4.53125 | 5 | ### Simple Types in Python ::
# --- Python Scalar Types ---
# ----------------------------------------------
# Type Example Description
# ``````````````````````````````````````````````
# int x = 1 integers
# float x = 1.0 floating point nums
# complex x = 1 + 2j complex nums
# bool x = True True/False
# str x = 'abc' String: chars//text
# NoneType x = None Null values
#
# ----------------------------------------------
### Integers (ints)
x = 1; print ( type(x) )
# unlike most languages, ints do NOT overflow
# they are variable-precision.
print ( 2 ** 200 )
# Python ints up-cast to floats when divided
print ( 5 / 2 )
# PYTHON 2 ONLY -- difference between 'int' and 'long'
### Floating-Point numbers
# can be defined in decimal notation OR exponential
x = 0.000005
y = 5e-6
print ( x == y )
x = 1400000.00
y = 1.4e6
print ( x == y )
# as expected, cast to float as follows:
float(1)
# as usual, floating point comparison is wonky
print ( 0.1 + 0.2 == 0.3 ) # yields False
# caused by binary > decimal (base-2 > base-10) approximation
print( "0.1 = {0:.17f}".format(0.1) )
print( "0.2 = {0:.17f}".format(0.2) )
print( "0.3 = {0:.17f}".format(0.3) )
# specifically, representing a 1/10 digit num requires infinite digits in base-2
# much like 1/3 requires infinite digits in base-10
### Complex Numbers
print ( complex(1, 2) ) # j used instead of i
c = 3 + 4j # j is 'keyword' - denotes imag
print ( c.real )
print ( c.imag )
print ( c.conjugate() ) # 3 - 4j
print ( abs(c) ) # 3^2 + (4j)^2 absolute magnitude
### String Type
# String created with EITHER 'single' "double" quotes
message = "foobar"
response = "doi"
# example (useful) string funcs/methods.
print ( len(message) ) # 3
print ( message.upper() ) # make all-caps
print ( message.lower() ) # all-lowercase
print ( message.capitalize() ) # first-cap
print ( message + response ) # string concat (NO auto-spacing)
print ( message[0] ) # char indexing
print ( 5 * response ) # * to mult. concat.
### None Type
print ( type(None) ) # None keyword denotes NoneType
# commonly used like "void" returns in other langs
return_value = print('abc')
print ( return_value )
### Boolean Type
result = (4 < 5)
print ( result )
print ( type(result) )
print(True, False) # Boolean vals CASE SENSITIVE
# construct using bool()
print ( bool(42) ) # numeric nonzero is True
print ( bool(0) ) # numeric zero is False
print ( bool(None) ) # NoneType is False
print ( bool("text") ) # norm. string is True
print ( bool("") ) # empty string is False
print ( bool([1,2]) ) # norm. list is True
print ( bool([]) ) # empty list is False | true |
6b43604d2d995874639262c7995a22dde3bd5b41 | eshulok/2.-Variables | /main.py | 604 | 4.53125 | 5 | #Variables are like nicknames for values
#You can assign a value to a variable
temperature = 75
#And then use the variable name in your code
print(temperature)
#You can change the value of the variable
temperature = 100
print(temperature)
#You can use variables for operations
temp_today = 85
temp_yesterday = 79
#How much warmer is it today than yesterday?
print(temp_today - temp_yesterday)
#Tomorrow will be 10 degrees warmer than today
print(temp_today + 10)
#Or if you want to save the value for tomorrow's temperature, create a new variable
temp_tomorrow = temp_today + 10
print(temp_tomorrow) | true |
37499520285d5a5b5b8746d02a4fc06854627f13 | riyaasenthilkumar/riya19 | /factorial.py | 270 | 4.125 | 4 | num=7
num=int(input("Enter a number:"))
factorial=1
if num<0:
print("factorial does not exist for negative number")
elif num==0:
print("the factorial of0 is 1")
else:
for i in range (1,num+1):
factorial=factorial*i
print("the factorial of",num,"is",factorial)
| true |
ccf67c2b2625e3ae6d1acc1e7cca475f8b3e5f67 | Xtreme-89/Python-projects | /main.py | 1,424 | 4.1875 | 4 | <<<<<<< HEAD
is_male = True
is_tall = False
if is_male and is_tall:
print("You are a tall male")
elif is_male and not is_tall:
print("You are a short male")
elif not is_male and is_tall:
print("You are a tall female")
else:
print("You are a short female")
#comparisons
def max_num(num1, num2, num3):
if num1 >= num2 and num2 >= num3:
return num1
if num2 >= num1 and num2 >= num3:
return num2
if num3 >= num1 and num3 >= num2:
return num3
else:
print("WTF u siked my programme")
num1 = int(input("Type your first number "))
num2 = int(input("Type your second number "))
num3 = int(input("Type your third number "))
print(str(max_num(num1, num2, num3)) + " is the highest number")
#Guessing Game
secret_word = "Giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Guess the secret word: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses - you have no access")
else:
print("Well done, you now have full access to the high order of variables.")
#For loops
friends = ["Jim", "Karen", "Emma", "Alexandria", "Liz", "Ellie"]
for friend in friends:
print (friend)
=======
print(3 +4.5)
>>>>>>> ab1d0e7820f4a8f97b5b83024948417c6bbadd0b
| true |
3b6c35f55899dbc8819e048fdbdebb065cd01db1 | brunomatt/ProjectEulerNum4 | /ProjectEulerNum4.py | 734 | 4.28125 | 4 | #A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
products = []
palindromes = []
three_digit_nums = range(100,1000)
for k in three_digit_nums:
for j in three_digit_nums:
products.append(k*j)
def check_palindrome(stringcheck): #only works for 6 digit numbers which is all we need for this exercise
if str(stringcheck)[0] == str(stringcheck)[-1] and str(stringcheck)[1] == str(stringcheck)[-2] and str(stringcheck)[2] == str(stringcheck)[-3]:
palindromes.append(stringcheck)
for num in products:
check_palindrome(num)
print(max(palindromes)) | true |
18187aef39ed5cdb6edad56d8599bc80586d93f8 | TokarAndrii/PythonStuff | /pythonTasks/data_structures/moreOnList.py | 1,760 | 4.71875 | 5 | # https: // docs.python.org/3.0/tutorial/datastructures.html
# list.append(x)
# Add an item to the end of the list
# equivalent to a[len(a):] = [x].
# list.extend(L)
# Extend the list by appending all the items in the given list
# equivalent to a[len(a):] = L.
# list.insert(i, x)
# Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
# list.remove(x)
# Remove the first item from the list whose value is x. It is an error if there is no such item.
# list.pop([i])
# Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
# list.index(x)
# Return the index in the list of the first item whose value is x. It is an error if there is no such item.
# list.count(x)
# Return the number of times x appears in the list.
# list.sort()
# Sort the items of the list, in place.
# list.reverse()
# Reverse the elements of the list, in place.
a = [66.25, 333, 333, 1, 1234.5]
a.append(237)
print(a)
# [66.25, 333, 333, 1, 1234.5, 237]
a.insert(1, 999)
print(a)
# [66.25, 999, 333, 333, 1, 1234.5, 237]
a.remove(333)
print(a)
# [66.25, 999, 333, 1, 1234.5, 237]
a.pop(1)
print(a)
# [66.25, 333, 1, 1234.5, 237]
find = a.index(237)
print(find)
# 4
print(a.count(333))
# 1
a.sort()
print(a)
# [1, 66.25, 237, 333, 1234.5]
a.reverse()
print(a)
# [1234.5, 333, 237, 66.25, 1]
| true |
1f3aaa0e48d787f2b1ec361d800cbc8d4606c7af | wicarte/492 | /a3.py | 845 | 4.125 | 4 | #Assignment 3 (W3D4) - William Carter
#What I think will happen before running the code:
#I think the code prompts the user to enter a number, casts
#the number as an int, counts up by 1 on the interval (2, user
#provided number), and prints whenever the outer loop iterator (i)
#is not cleanly divisible by the inner loop iterator (k).
n = input("Please enter a number as an upper limit: ")
n = int(n)
for i in range(2, n):
check_var = True
for k in xrange(2, i):
if (i%k) == 0:
check_var = False
if check_var:
print(i)
#After running the code:
#A number is printed out and another number is printed out as many times
#as the first number's value. For example, if 5 is printed out and 7
#is the next number to be printed, 7 will print 5 different times.
#This pattern continues until the upper bound provided by the user
#is reached.
| true |
1a948637866f58b51f76d1b69c070d67a6a615c8 | nbenkler/CS110_Intro_CS | /HW #5/untitled folder/convertFunctions.py | 955 | 4.15625 | 4 | # Program to read file HW5_Input.txt and convert characters in the file to their unicode, hexadecimal, and binary representations.
#Noam Benkler
#2/12/18
def fileIngest(fileName):
inFile = open(fileName, "r")
return inFile
inFile.close()
def conversionOutput(file):
for line in file:
full = (line)
character = (full[0])
unicode = uniConversion(character)
hexadecimal = hexConversion(unicode)
binary = binConversion(unicode)
output = str("The Character "+str(character)+" is encoded as "+str(unicode)+" in Unicode, which is "+str(hexadecimal)+" in hexadecimal and "+str(binary)+" in binary.")
print (output)
def uniConversion(alphanum):
uni = ord(alphanum)
return uni
def hexConversion(alphanum):
hexa = hex(alphanum) [2:]
return hexa
def binConversion(alphanum):
bina = bin(alphanum) [2:]
return bina
def main():
fileName = "HW5_input.txt"
conversionFile = fileIngest(fileName)
conversionOutput(conversionFile)
main() | true |
590d5ad63a0fcf7f0f27a6352051093acfc9923c | nbenkler/CS110_Intro_CS | /Lab 3/functions.py | 1,026 | 4.4375 | 4 | '''function.py
Blake Howald 9/19/17, modified for Python 3 from original by Jeff Ondich, 25 September 2009
A very brief example of how functions interact with
their callers via parameters and return values.
Before you run this program, try to predict exactly
what output will appear, and in what order. You are
trying to trace the movement of data throughout the
program, and make sure you understand what happens
when. This simple program is very important for you
to understand. If you have figured it out, the rest
of the term will be a lot easier than if you haven't.
'''
def f(n):
print(n)
result = 3 * n + 4
return result
def g(n):
print(n)
result = 2 * n - 3
return result
number = 5
print('number = ', number)
print()
print('Experiment #1')
answer = f(number)
print('f(number) =', answer)
print()
print('Experiment #2')
answer = g(number)
print('g(number) =', answer)
print()
print('Experiment #3')
answer = f(g(number))
print('f(g(number)) =', answer)
print()
| true |
78ef5fc28e3f4ae7efc5ed523eeffe246496c403 | alexmkubiak/MIT_IntroCS | /week1/pset1_2.py | 413 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 18:00:03 2018
This code determines how many times the string 'bob' occurs in a string s.
@author: Alex
"""
s = 'azcbobobegghakl'
count = 0
index = 0
for index in s:
if s[index] == 'b':
if s[index + 1] == 'o':
if s[index+2] == 'b':
count += 1
print("Number of times bob occurs is: " + str(count))
| true |
9ecd69b1dc1bd808055cea00eabc82428dc12056 | TheChuey/DevCamp | /range_slices_in_pythonList.py | 982 | 4.3125 | 4 | tags = [
'python',
'development',
'tutorials',
'code',
'programing',
'computer science'
]
#tags_range = tags[:-1:2]
tags_range = tags[::-1] # reverses the oder of the list
# slicing function
print(tags_range)
"""
# Advanced Techniques for Implementing Ranges and Slices in Python Lists
tag_range = tags[1:-1:2] # we want every other tag here (place in an interval) -inside the bracket you can pass in the third elemnt(interval(every other tag) the 2 takes every other element)
tag_range = tags[::-1] #slicing -flip the entire order of the list- in bracket-reverse index values-remove second perameter
#above-you would use this
print(tag_range)
#------------------------------------------------------------------------------
tags.sort(reverse=True) #sorting function looks at the alphabetical value-instead of the above example that pulls the index
print(tags)
////////////////////////////////////////////////////////////
""" | true |
09a4ae07c0b9e3c8d1604bfaea0ce58078d52936 | asim09/Algorithm | /data-types/List/sort-list-of-string.py | 256 | 4.1875 | 4 | # Python Program to sort a list according to the length of the elements
a = ['Apple', 'Ball', 'Cat', 'Ox']
for i in range(len(a)):
for j in range(len(a) - i - 1):
if len(a[j]) > len(a[j+1]):
a[j], a[j+1] = a[j+1], a[j]
print(a[-1])
| true |
234a8bc6f168afac7ab18c566b0a783e5e9080fd | prabalbhandari04/python_ | /labexercise2.py | 312 | 4.28125 | 4 | #Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. Every number is given on a separate line.#
length_of_base = int(input("Enter the lenght of base:"))
height = int(input("Enter the height:"))
area = (1/2)*(length_of_base*height)
print(area) | true |
06fe1661b93a940e28adb9c5fab488df85e19eb8 | ankush-phulia/Lift-MDP-Model | /simulator/Elevator.py | 2,956 | 4.25 | 4 | class Elevator(object):
"""
- state representation of the elevator
"""
def __init__(self, N, K):
self.N = N # number of floors
self.K = K # number of elevators
# initial positions of all elevators
self.pos = [0]*K
# button up on each floor (always 0 for top floor)
self.BU = [0]*N
# button down on each floor (always 0 for first floor)
self.BD = [0]*N
# floor buttons pressed inside elevator, for each elevator
self.BF = [[0]*N for i in range(K)]
# light up indicator for each lift for its current floor (always 0 for top floor)
self.LU = [0]*K
# light down indicator for each lift for its current floor (always 0 for first floor)
self.LD = [0]*K
def __str__(self):
"""
- returns a string expression of the current state of the elevator
"""
state = ''
state += ' '.join([str(x) for x in self.pos]) + ' '
state += ''.join([str(x) + ' ' + str(y) + ' ' for x,
y in zip(self.BU, self.BD)])
for e in self.BF:
state += ' '.join([str(x) for x in e])
state += ' '
state += ' '.join([str(x) for x in self.LU]) + ' '
state += ' '.join([str(x) for x in self.LD]) + ' '
return state
# state modifiers
def modify_pos(self, k, delta):
"""
- change position of kth lift by delta (+/- 1)
- validity checks in Simulator
"""
self.pos[k] += delta
def modify_floor_button(self, n, direction, status):
"""
- n : floor number
- direction : 'U' for up button and 'D' for down button
- status : 0 to clear and 1 to press
- returns if status was toggled
"""
toggled = True
if direction == 'U':
if self.BU[n] == status:
toggled = False
self.BU[n] = status
if direction == 'D':
if self.BD[n] == status:
toggled = False
self.BD[n] = status
return toggled
def modify_elevator_button(self, k, n, status):
"""
- k : elevator number
- n : floor number
- status : 0 to clear and 1 to press
- returns if status was toggled
"""
toggled = True
if self.BF[k][n] == status:
toggled = False
self.BF[k][n] = status
return toggled
def reset_lights(self):
self.LU = [0] * self.K
self.LD = [0] * self.K
def modify_lights(self, k, direction, status):
"""
- k : lift number
- direction : 'U' for up button and 'D' for down button
- status : 0 to clear and 1 to press
"""
if direction == 'U':
self.LU[k] = status
if direction == 'D':
self.LD[k] = status
| true |
1d8df8f0fd6996602088725eaef8fb63429cdf99 | mileshill/HackerRank | /AI/Bot_Building/Bot_Saves_Princess/princess.py | 2,127 | 4.125 | 4 | #!/usr/bin/env python2
"""
Bot Saves Princess:
Mario is located at the center of the grid. Princess Peach is located at one of the four corners. Peach is denoted by 'p' and Mario by 'm'. The goal is to make the proper moves to reach the princess
Input:
First line contains an ODD integer (3<=N<=99) denoting the size of the grid. The is followed by an NxN grid.
Output:
Print out the steps required to reach the princess. Each move will have the format "MOVE\n"
Valid Moves:
LEFT, RIGHT, UP, DOWN
"""
from sys import stdin, stdout
r = stdin.readline
def find_princess_position( grid_size ):
""" Read the array to find princess """
assert type( grid_size ) is int
for i in range( grid_size ):
line = list(r().strip())
if 'p' in line:
j = line.index('p')
location = (j,i)
return location
def get_directions( x_peach, y_peach, x_mario, y_mario):
""" Determine L/R U/D directions mario will travel """
horizontal_dir =''
vertical_dir = ''
# horizontal direction
if x_peach > x_mario:
horizontal_dir = "RIGHT"
else:
horizontal_dir = "LEFT"
# vertical direction
if y_peach > y_mario:
vertical_dir = "DOWN"
else:
vertical_dir = "UP"
return (horizontal_dir, vertical_dir)
def generate_marios_path( grid_size, location_of_princess ):
""" Generate the steps to move to the princess """
grid_center = (grid_size -1)/2 + 1
distance_to_wall = grid_center -1
xp, yp = location_of_princess
x_dir, y_dir = get_directions( xp, yp, xm, ym )
horizontal = [ x_dir for x in range(distance_to_wall)]
vertical = [ y_dir for y in range(distance_to_wall) ]
return horizontal + vertical
def main():
grid_size = int( r().strip() )
location_of_princess = find_princess_position( grid_size )
marios_path = generate_marios_path( grid_size, location_of_princess )
assert type( marios_path ) is list
for move in marios_path:
stdout.write( move + '\n' )
if __name__ == '__main__':
main()
| true |
f1d0eed5c88aff33508a9b32e9aaec1a3f962de3 | rahulkumar1m/exercism-python-track | /isogram/isogram.py | 528 | 4.3125 | 4 | def is_isogram(string) -> bool:
# Tokenizing the characters in the string
string = [char for char in string.lower()]
# initializing an empty list of characters present in the string
characters = []
# if a character from string is already present in our list of characters, we return False
for char in string:
if (char == " ") or (char == "-"):
continue
elif char in characters:
return False
else:
characters.append(char)
return True
| true |
122a3f71dd406d2cea9d838e3fe1260cd0e3adcf | hardlyHacking/cs1 | /static/solutions/labs/gravity/solution/system.py | 2,283 | 4.21875 | 4 | # system.py
# Solution for CS 1 Lab Assignment 3.
# Definition of the System class for gravity simulation.
# A System represents several Body objects.
# Based on code written by Aaron Watanabe and Devin Balkcom.
UNIVERSAL_GRAVITATIONAL_CONSTANT = 6.67384e-11
from math import sqrt
from body import Body
class System:
# To initialize a System, just save the body list.
def __init__(self, body_list):
self.body_list = body_list
# Draw a System by drawing each body in the body list.
def draw(self, cx, cy, pixels_per_meter):
for body in self.body_list:
body.draw(cx, cy, pixels_per_meter)
# Compute the distance between bodies n1 and n2.
def dist(self, n1, n2):
dx = self.body_list[n2].get_x() - self.body_list[n1].get_x()
dy = self.body_list[n2].get_y() - self.body_list[n1].get_y()
return sqrt(dx * dx + dy * dy)
# Compute the acceleration of all other bodies on body n.
def compute_acceleration(self, n):
total_ax = 0
total_ay = 0
n_x = self.body_list[n].get_x()
n_y = self.body_list[n].get_y()
for i in range(len(self.body_list)):
if i != n: # don't compute the acceleration of body n on itself!
r = self.dist(i, n)
a = UNIVERSAL_GRAVITATIONAL_CONSTANT * self.body_list[i].get_mass() / (r * r)
# a is the magnitude of the acceleration.
# Break it into its x and y components ax and ay,
# and add them into the running sums total_ax and total_ay.
dx = self.body_list[i].get_x() - n_x
ax = a * dx / r
total_ax += ax
dy = self.body_list[i].get_y() - n_y
ay = a * dy / r
total_ay += ay
# To return two values, use a tuple.
return (total_ax, total_ay)
# Compute the acceleration on each body, and use the acceleration
# to update the velocity and then the position of each body.
def update(self, timestep):
for n in range(len(self.body_list)):
(ax, ay) = self.compute_acceleration(n)
self.body_list[n].update_velocity(ax, ay, timestep)
self.body_list[n].update_position(timestep)
| true |
490389021ee556bb98c72ae687389445ebb6dcb7 | Andras00P/Python_Exercise_solutions | /31 - Guess_Game.py | 855 | 4.46875 | 4 | ''' Build a simple guessing game where it will continuously ask the user to enter a number between 1 and 10.
If the user's guesses matched, the user will score 10 points, and display the score.
If the user's guess doesn't match, display the generated number.
Also, if the user enters "q" stop the game. '''
import random
print("Welcome to the Guessing Game! \n\n")
print("Enter the letter q, to quit.\n")
score = 0
while True:
npc = random.randint(0, 10)
print("Guess a number between 0 and 10.")
n = input("What's your guess? \n")
if n == "q":
print("\nGame Over!")
break
num = int(n)
if num is npc:
score += 10
print("Your guess was correct!\n")
print(f"You currently have {score} points\n")
else:
print(f"The number was {npc}\n")
| true |
3607e93c5431e03789f3f980fd2220c4a8dc9b10 | Andras00P/Python_Exercise_solutions | /24 - Reverse_String.py | 443 | 4.375 | 4 | """ Reverse a string.
If the input is: Hello World.
The output should be: .dlroW olleH """
def reverse_string(text):
result = ""
for char in text:
result = char + result
return result
# Shortcut
def reverse_string2(text):
return text[::-1]
usr_text = input("Write the text, you want to reverse: \n")
print("Reversed: \n", reverse_string(usr_text) + "\n", reverse_string2(usr_text))
| true |
a5fd62036f3dd8a6ec226ffae14b48c6c5ab06ca | Andras00P/Python_Exercise_solutions | /21 - Check_Prime.py | 357 | 4.21875 | 4 | ''' For a given number, check whether the number is a prime number or not '''
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
usr_num = int(input("Enter number: \n"))
if is_prime(usr_num):
print("The number is a Prime")
else:
print("The number is not a Prime")
| true |
06afe217a85fc98b1689ac6e6119a118fe91f9b5 | garciacastano09/pycourse | /intermediate/exercises/mod_05_iterators_generators_coroutines/exercise.py | 2,627 | 4.125 | 4 | #-*- coding: utf-8 -*-
u'''
MOD 05: Iterators, generators and coroutines
'''
def repeat_items(sequence, num_times=2):
'''Iterate the sequence returning each element repeated several times
>>> list(repeat_items([1, 2, 3]))
[1, 1, 2, 2, 3, 3]
>>> list(repeat_items([1, 2, 3], 3))
[1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> list(repeat_items([1, 2, 3], 0))
[]
>>> list(repeat_items([1, 2, 3], 1))
[1, 2, 3]
:param sequence: sequence or iterable to iterate over
:param num_times: number of times to repeat each item
:returns: generator with each element of the sequence repeated
'''
for i in sequence:
rep=num_times
while rep>0:
yield i
rep-=1
continue
def izip(*sequences):
'''Return tuples with one element of each sequence
It returns as many pairs as the shortest sequence
The same than std lib zip function
>>> list(izip([1, 2, 3], ['a', 'b', 'c']))
[[1, 'a'], [2, 'b'], [3, 'c']]
>>> list(izip([1, 2, 3], ['a', 'b', 'c', 'd']))
[[1, 'a'], [2, 'b'], [3, 'c']]
:param sequences: two or more sequences to loop over
:returns: generator returning tuples with the n-th item of input sequences
'''
if len(sequences) > 0:
tuples_len = min(int(i) for i in map(lambda x: len(x), sequences))
else:
yield []
return
for index in range(0, tuples_len):
result_element = []
for sequence in sequences:
result_element.append(sequence[index])
yield result_element
def merge(*sequences):
'''Iterate over all sequences returning each time one item of one of them
Always loop sequences in the same order
>>> list(merge([None, True, False], ['a', 'e', 'i', 'o', 'u']))
[None, 'a', True, 'e', False, 'i', 'o', 'u']
>>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False]))
['a', None, 'e', True, 'i', False, 'o', 'u']
>>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
['a', None, 0, 'e', True, 1, 'i', False, 2, 'o', 3, 'u', 4, 5, 6, 7, 8, 9]
:param sequences: two or more sequences to loop over
:returns: generator returning one item of each
'''
iterators = map(iter, sequences)
while sequences:
yield map(iter)
def flatten(L):
'''flatten the input list of lists to a flattened list
>>>list(flatten([1, 2, [3]])
[1, 2, 3]
>>>list(flatten([1, 2, [3, 4], [[5]])
[1, 2, ,3 ,4 ,5]
:param L: list of lists
:returns: generator with flattened list
'''
yield None
| true |
014e36604daf04ec73c663fe223cd445fcd01ca5 | garciacastano09/pycourse | /advanced/exercises/mod_05_functools/exercise_mod_05.py | 585 | 4.25 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
u"""
Created on Oct 5, 2013
@author: pablito56
@license: MIT
@contact: pablito56@gmail.com
Module 05 functools exercise
>>> it = power_of(2)
>>> it.next()
1
>>> it.next()
2
>>> it.next()
4
>>> it.next()
8
>>> it.next()
16
>>> it = power_of(3)
>>> it.next()
1
>>> it.next()
3
>>> it.next()
9
"""
from itertools import imap, count
def power_of(x):
"""Generator returning powers of the provided number
"""
# Try to use imap and count (from itertools module)
# You MUST use pow function in this exercise
return count(1)
| true |
c3d462c1e5cd9bb28a67ee54f8f80c03ec14f06a | ACEinfinity7/Determinant2x2 | /deter_lib.py | 792 | 4.125 | 4 | def deter2x2(matrix):
"""
function to calculate the determinant of
the 2x2 matrix.
The determinant of a matrix is defined as
the upper-left element times the lower right element
minus
the upper-right element times the lower left element
"""
result = (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0])
# TODO: calculate the determinant of the 2x2 matrix
return result
def deter3x3(matrix):
a = matrix[0][0]
b = matrix[0][1]
c = matrix[0][2]
d = matrix[1][0]
e = matrix[1][1]
f = matrix[1][2]
g = matrix[2][0]
h = matrix[2][1]
i = matrix[2][2]
result = (a*e*i) - (a*f*h) - (b*d*i) + (b*f*g) + (c*d*h) - (c*e*g)
return result
matrix_test = [[4,1,3],[5,3,1],[8,4,2]]
print(deter3x3(matrix_test))
| true |
e354f576673621e8dc851bda02d495a5196f9f7d | mitchellflax/lpsr-samples | /3-6ATkinterExample/remoteControl.py | 464 | 4.28125 | 4 | import turtle
from Tkinter import *
# create the root Tkinter window and a Frame to go in it
root = Tk()
frame = Frame(root, height=100, width=100)
# create our turtle
shawn = turtle.Turtle()
# make some simple buttons
fwd = Button(frame, text='fwd', fg='red', command=lambda: shawn.forward(50))
left = Button(frame, text='left', command=lambda: shawn.left(90))
# put it all together
fwd.pack(side=LEFT)
left.pack(side=LEFT)
frame.pack()
turtle.exitonclick()
| true |
ed15cbf4fd067d8b9c8194d22b795cb55005797f | mitchellflax/lpsr-samples | /ProblemSets/PS5/teamManager.py | 1,525 | 4.3125 | 4 | # a Player on a team has a name, an age, and a number of goals so far this season
class Player(object):
def __init__(self, name, age, goals):
self.name = name
self.age = age
self.goals = goals
def printStats(self):
print("Name: " + self.name)
print("Age: " + str(self.age))
print("Goals: " + str(self.goals))
# default doesn't matter, we'll set it again
user_choice = 1
my_players = []
while user_choice != 0:
print("What do you want to do? Enter the # of your choice and press Enter.")
print("(1) Add a player")
print("(2) Print all players")
print("(3) Print average number of goals for all players")
print("(0) Leave the program and delete all players")
user_choice = int(raw_input())
# if the user wants to add a player, collect their data and make a Player object
if user_choice == 1:
print("Enter name:")
player_name = raw_input()
print("Enter age:")
player_age = int(raw_input())
print("Enter number of goals scored this season:")
player_goals = int(raw_input())
my_players.append(Player(player_name, player_age, player_goals))
print("Ok, player entered.")
# if the user wants to print the players, call printStats for each Player
if user_choice == 2:
print("Here are all the players...")
for player in my_players:
player.printStats()
if user_choice == 3:
# average = sum of all goals divided by count of players
sum = 0
count = 0
for player in my_players:
sum += player.goals
count += 1
avg = sum / count
print("Average goals: " + str(avg))
| true |
505b7944e773905bd8b1c5c8be4ce6d9a3b58730 | mitchellflax/lpsr-samples | /4-2WritingFiles/haikuGenerator2.py | 1,548 | 4.3125 | 4 | # haikuGenerator.py
import random
# Ask the user for the lines of the haiku
print('Welcome to the Haiku generator!')
print('Would you like to write your haiku from scratch or get a randomized first line?')
print('(1) I\'ll write it from scratch')
print('(2) Start me with a random line')
user_choice = int(raw_input())
# if the user wants to write from scratch, keep it simple
if user_choice == 1:
print('Provide the first line of your haiku:')
haiku_ln1 = raw_input()
# if the user is into getting a random starter, we have some work to do
else:
# open the rando file and bring in the random lines
starters_file = open('haikuStarters.txt', 'r')
starters_list = []
# get the starter lines and add them to a list
line = starters_file.readline()
while line:
starters_list.append(line)
line = starters_file.readline()
# spit the line back to the user
print('All right, here\'s your first line:')
haiku_ln1 = starters_list[random.randint(0,len(starters_list))]
print(haiku_ln1)
print('Provide the second line of your haiku:')
haiku_ln2 = raw_input()
print('Provide the third line of your haiku:')
haiku_ln3 = raw_input()
# Ask the user for the filename
print('What file would you like to write your haiku to?')
filename = raw_input()
# Write the haiku to a file
my_file = open(filename, 'w')
my_file.write(haiku_ln1 + '\n')
my_file.write(haiku_ln2 + '\n')
my_file.write(haiku_ln3 + '\n')
# Success! Close the file.
my_file.close()
print("Done! To view your haiku, type 'cat' and the name of your file at the command line.")
| true |
7e13745a73f6d77bbebcc267c0d4481ba6a86d3a | mitchellflax/lpsr-samples | /3-4FunctionsInTurtle/samplePatternTemplate.py | 495 | 4.25 | 4 | # samplePattern.py
import turtle
# myTurtle is a Turtle object
# side is the length of a side in points
def makeTriangle(myTurtle, side):
pass
# make our turtle
kipp = turtle.Turtle()
kipp.forward(150)
kipp.right(180)
# kipp makes triangles centered at a point that shifts
# and decreases in size with each loop
length = 100
while length > 0:
makeTriangle(kipp, length)
kipp.forward(3)
# make the sides shorter
length = length - 1
# wait to exit until I've clicked
turtle.exitonclick()
| true |
f9f2cbd0408139865c1cb412a80c1d60b5cc038c | Brian-Musembi/ICS3U-Unit6-04-Python | /array_average.py | 1,839 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by Brian Musembi
# Created on June 2021
# This program prints a 2D array and finds the average of all the numbers
import random
def average_2D(list_2D):
# This function finds the average
total = 0
rows = len(list_2D)
columns = len(list_2D[0])
for row_value in list_2D:
for value in row_value:
total += value
average = total / (rows * columns)
return average
def main():
# This function handles input and prints a 2D array
print("This program prints a 2D array and finds the average "
"of all numbers.")
print("")
list_2D = []
# input
while True:
try:
rows_input = input("Input the number of rows you want: ")
rows = int(rows_input)
columns_input = input("Input the number of columns you want: ")
columns = int(columns_input)
print("")
# check for negative numbers
if rows > 0 and columns > 0:
for loop_counter_rows in range(0, rows):
temp_column = []
for loop_counter_columns in range(0, columns):
random_num = random.randint(0, 50)
temp_column.append(random_num)
print("{0} ".format(random_num), end="")
list_2D.append(temp_column)
print("")
average_of_array = average_2D(list_2D)
average_rounded = '{0:.5g}'.format(average_of_array)
print("")
print("The average of all the numbers is: {0}"
.format(average_rounded))
break
except Exception:
# output
print("Enter a number for both values, try again.")
if __name__ == "__main__":
main()
| true |
c054b2383fd5b7d7a042d69673d2708aef9be0b1 | coreman14/Python-From-java | /CPRG251/Assignment 6/Movie.py | 2,090 | 4.40625 | 4 | class Movie():
def __init__(self, mins:int, name:str, year:int):
"""Creates an object and assign the respective args
Args:
mins (int): Length of the movie
name (str): Name of the movie
year (int): Year the movie was released
"""
self.mins = mins
self.year = year
self.name = name
def getYear(self):
"""Returns the year of the movie
Returns:
int: The year of the movie
"""
return self.year;
def setYear(self, year):
"""Sets the year of the movie
Args:
year (int): The year of the movie
"""
self.year = year;
def getMins(self):
"""Returns the length of the movie in minutes
Returns:
int: The length of the movie
"""
return self.mins;
def setMins(self,mins):
"""Sets the length of the movie in minutes
Args:
mins (int): The length of the movie
"""
self.mins = mins;
def getName(self):
"""Returns the name of the movie
Returns:
str: The name of the movie
"""
return self.name;
def setName(self, name):
"""Sets the name of the movie
Args:
name (str): The name of the movie
"""
self.name = name;
def __str__(self):
"""Returns a formatted string for output
Returns in order of (Mins,Year,Name)
Returns:
str: A string for output in a list (Mins,Year,Name)
"""
return f"{self.getMins():<15}{self.getYear():<6}{self.getName()}"
def formatForFile(self):
"""Returns the movie in a csv format
Returns in order of (Mins,Name,Year)
Returns:
str: The movie in a CSV format (Mins,Name,Year)
"""
return f"{self.getMins()},{self.getName()},{self.getYear()}\n"
| true |
34d705727c44475ce5c1411558760a01969ef75b | Syvacus/python_programming_project | /Session number 2.py | 2,246 | 4.1875 | 4 | # Question 1
# Problem: '15151515' is printed because the chairs variable is text instead of a number
# Solution: Convert the chairs variable from text to number
chairs = '15' # <- this is a string (text) rather than an int (number)
nails = 4
total_nails = int(chairs) * nails # <- convert string to int by wrapping it in the int() function
message = 'I need to buy {} nails'.format(total_nails)
print(message)
#my solution
nails = 4
chairs = 15
total_nails = nails * chairs
message = "I _need _to _buy" + str (total_nails) +"nails"
print(message)
# Question 2
# Problem: When the code is run, we get a error: 'NameError: name 'Penelope' is not defined'
# this is because Python is interpreting Penelope as a variable, rather than a string
# Solution: To store text, it needs to be enclosed in either '{text}' or "{text}"
my_name = 'Penelope' # <- store the name as text by enclosing in single or double quotes
my_age = 29
message = 'My name is {} and I am {} years old'.format(my_name, my_age)
print(message)
#my solution
my_name = "Penelope"
my_age = 29
message = (my_name, my_age)
print(message)
# Question 3
# Task: I have a lot of boxes of eggs in my fridge and I want to calculate how many omelettes I can make.
# Write a program to calculate this.
# Assume that a box of eggs contains six eggs and I need four eggs for each omelette, but I should be
# able to easily change these values if I want. The output should say something like "You can make 9
# omelettes with 6 boxes of eggs".
boxes = 7
eggs_per_box = 6
eggs_per_omelette = 4
total_number_of_eggs = boxes * eggs_per_box
# Calculate whole number of omelettes
number_of_whole_omelettes = total_number_of_eggs // eggs_per_omelette
left_over_eggs = total_number_of_eggs % eggs_per_omelette
message = 'Using {} boxes of eggs, you can make {} whole omelettes, with {} eggs left over.'
print(message.format(boxes, number_of_whole_omelettes, left_over_eggs))
# Calculate number of omelettes (as a decimal)
number_of_decimal_omelettes = total_number_of_eggs / eggs_per_omelette
message = 'Using {} boxes of eggs, you can make {} omelettes.'
print(message.format(boxes, number_of_decimal_omelettes))
| true |
95d7dd2afe45d705d1bbb3884245e1258651f0c0 | DHANI4/NUMBER-GUESSING-GAME | /NumberGuessing.py | 443 | 4.28125 | 4 | import random
print("Number Guessing Game")
rand=random.randint(1,20)
print("Guess a Number between 1-20")
chances=0
while(chances<5):
chances=chances+1
guess=int(input("Enter Your Guess"))
if(guess==rand):
print("Congratulations You Won!!")
break
elif(guess<rand):
print("Guess a number higher")
else:
print("Guess a number lesser")
if not chances<5:
print("You Loose") | true |
949b939ef934fb793119900d36b377d7069c1916 | vivianlorenaortiz/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 345 | 4.3125 | 4 | #!/usr/bin/python3
"""
Funtion that prints a square with the character #.
"""
def print_square(size):
"""
Function print square.
"""
if type(size) is not int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
for i in range(size):
print(size * "#")
| true |
809e7e3a4be9be995241c67909ae61fc5796d98d | drummerevans/Vector_Multiply | /cross_input.py | 564 | 4.125 | 4 | import numpy as np
items = []
max = 3
while len(items) < max:
item = input("Add an element to the list: ")
items.append(int(item))
print("The length of the list is now increased to {:d}." .format(len(items)))
print(items)
things = []
values = 3
for i in range(0, values):
thing = input("Add an element to the second list: ")
things.append(int(thing))
print("The length of the second list is now increased to {:d}. " .format(len(things)))
print(things)
z = np.cross(items, things)
print("The cross product of the two lists are: ", z)
| true |
44a4dda12809ebd8ba6e3c6c52c96e130a0fa7e1 | PrateekMinhas/Python | /assignment14.py | 1,555 | 4.4375 | 4 | Q.1- Write a python program to print the cube of each value of a list using list comprehension.
lst=[1,2,3,4,5]
lstc=[i**3 for i in lst]
print(lstc)
#Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension.
lst_pr= [ i for i in range(2,int(input("Enter the end input of the range for the prime numbers"))) if all(i%j!=0 for j in range(2,i)) ] #all returns true if all items in a seq are true
print(lst_pr)
#Q.3- Write the main differences between List Comprehension and Generator Expression.
"""generator expression uses () while list comprehension uses []
list comprehension returns a list that we can iterate and access via index but same is not the case in generator expression"""
#LAMBDA & MAP
#Q.1- Celsius = [39.2, 36.5, 37.3, 37.8] Convert this python list to Fahrenheit using map and lambda expression.
Celsius = [39.2, 36.5, 37.3, 37.8]
far=list(map(lambda i:(i * (9/5)) + 32,Celsius))
print(far)
#Q.2- Apply an anonymous function to square all the elements of a list using map and lambda.
lst1=[10,20,30,40,50]
lstsq=list(map(lambda i:i**2,lst1))
print(lstsq)
#FILTER & REDUCE
#Q.1- Filter out all the primes from a list.
lis3 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for m in range(2, 18):
lis3 = list(filter(lambda x: x == m or x % m and x > 1, lis3))
print(lis3)
#Q.2- Write a python program to multiply all the elements of a list using reduce.
from functools import reduce
lis4 = [1,2,3,4,5,6,7,8,9,10]
mul = reduce(lambda x, y: x*y,lis4)
print(mul)
| true |
cc1aa3c2ec38ffc869b942af0491d3c44baf9ba1 | PrateekMinhas/Python | /assignment3.py | 2,048 | 4.25 | 4 |
#Q.1- Create a list with user defined inputs.
ls=[]
x=int(input("enter the number of elements"))
for i in range (x):
m=input()
ls.append(m)
print (ls)
#Q.2- Add the following list to above created list:
#[‘google’,’apple’,’facebook’,’microsoft’,’tesla’]
ls1=['google','apple','facebook','microsoft','tesla']
ls.extend(ls1)
print(ls)
#Q.3 - Count the number of time an object occurs in a list.
ls2=[1,2,3,3,'rabbit',',','$','$',4,7]
x = input("enter an element from the string to know its occurence in it")
print (ls2.count(x))
#Q.4 - create a list with numbers and sort it in ascending order.
ls3=[1,2,45,6,8,4,3,6,8,9,0,8,67,-4]
ls3.sort()
print (ls3)
#Q.5 - Given are two one-dimensional arrays A and B which are sorted in ascending order.
#Write a program to merge them into a single sorted array C that contains every item from
#arrays A and B, in ascending order. [List]
A=[1,3,4,6,7,-8,-98]
B=[1,4,5,3,6,56,33,23]
C=[12,34,5]
A.sort() #sorts A
B.sort() #sorts B
C.sort() #sorts C
A.extend(B) #adds b to A
C.extend(A) #adds new A to C
C.sort() #sorts the new C
print(C)#prints C
#Q.6 - Count even and odd numbers in that list.
odd=[]
even=[]
for y in C:
if y%2==0:
even.append(y)
else:
odd.append(y)
print ("even numbers are ",len(even))
print ("odd numbers are ",len(odd))
#TUPLE
#Q.1-Print a tuple in reverse order.
tup=('apple','mango','banana')
rev=reversed(tup)
print(tuple(rev))
#Q.2-Find largest and smallest elements of a tuples.
tup1=(1,2,4,5,6,78,-90)
print(max(tup1))
print(min(tup1))
#STRINGS
#Q.1- Convert a string to uppercase.
string='im so sister shook ryt now !!'
print (string.upper())
#Q.2- Print true if the string contains all numeric characters.
string2=str(input("enter a string"))
print (string2.isdigit())
#Q.3- Replace the word "World" with your name in the string "Hello World".
string3='Hello World'
print(string3.replace('World','Prateek Minhas'))
| true |
cef5dd3e9ca6fe8f9ce33b6e4f8aca9e35f368f4 | 0xch25/Data-Structures | /2.Arrays/Problems/Running sum of 1D Array.py | 497 | 4.21875 | 4 | '''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]'''
def runningSum(nums):
sum =0
for i in range(len(nums)):
temp=nums[i]
nums[i] =nums[i] +sum
sum+=temp
return nums
nums=[1,1,1,1,1]
nums2=[1,2,3,4]
print(runningSum(nums))
print(runningSum(nums2)) | true |
7816262c0cda16be8c7d255780fba2c1203905a8 | 0xch25/Data-Structures | /3.Stacks/Palindrome using Stacks.py | 544 | 4.15625 | 4 | '''Program to check weather the given string is palindrome or not'''
class Stack:
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
s = Stack()
str= input("enter the string:")
for char in str:
s.push(char)
str2=""
while not s.is_empty():
str2 = str2 + s.pop()
if str == str2:
print('The string is a palindrome')
else:
print('The string is not a palindrome') | true |
e70a83469f49d7f0dcb0ce94f8621e1b8b032836 | 0xch25/Data-Structures | /10.Strings/Problems/Shuffle String.py | 776 | 4.1875 | 4 | '''
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.
Example 2:
Input: s = "abc", indices = [0,1,2]
Output: "abc"
Explanation: After shuffling, each character remains in its position.
Example 3:
Input: s = "aiohn", indices = [3,1,4,2,0]
Output: "nihao"
'''
def restoreString(s,indices):
res = [" "] * len(s)
for i in range(len(s)):
res[indices[i]] = s[i]
return "".join(res)
s = "aiohn"
indices = [3,1,4,2,0]
print(restoreString(s,indices)) | true |
355a3568f845a02c8c3af90bf627ea2a207d7b84 | ndri/challenges | /old/33.py | 1,139 | 4.125 | 4 | #!/usr/bin/env python
# 33 - Area Calculator
import sys
try:
shape, args = sys.argv[1], ' '.join(sys.argv[2:])
except:
sys.exit('Error. Use -h for help.')
if shape == '-h':
print 'Challenge 33 - Area Calculator'
print '-h\t\t\tDisplay this help'
print '-r width height\t\tArea for a rectangle'
print '-c radius\t\tArea for a circle'
print '-t base height\t\tArea for a triangle'
elif shape == '-r':
try:
width, height = args.split()[:2]
area = float(width) * float(height)
print 'The area of this rectangle is {0:.4}'.format(area)
except:
print 'Usage: -r width height'
elif shape == '-c':
try:
radius = float(args.split()[0])
area = 3.14159265358 * radius**2
print 'The area of this circle is {0:.4}'.format(area)
except:
print 'Usage: -c radius'
elif shape == '-t':
try:
base, height = args.split()[:2]
area = 0.5 * float(base) * float(height)
print 'The area of this triangle is {0:.4}'.format(area)
except:
print 'Usage: -t base height'
else:
print 'Error. Use -h for help.'
| true |
42096d931802f6a0edcfa5702f2a91d0bbba2cd5 | LaloGarcia91/CrackingTheCodingInterview | /Chapter_1/CheckPermutation.py | 775 | 4.125 | 4 | class CheckPermutation:
def __init__(self, str1, str2):
self.checkIfIsPermutation(str1, str2)
def checkIfIsPermutation(self, str1, str2):
str1_len = len(str1)
str2_len = len(str2)
if str1_len == str2_len:
counterIfEqualLetters = 0
for str1_letter in str1:
if str1_letter in str2:
counterIfEqualLetters += 1
else:
print("It is NOT a permutation")
return False
if counterIfEqualLetters == str1_len:
print("It IS a permutation")
return True
else:
print("Words are not even the same length")
# run exercise
CheckPermutation("HELLO", "HLLEO")
| true |
13550a3bd2b683327b96a2676f5d006b69353b73 | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Smooth Sailing/isLucky.py | 614 | 4.21875 | 4 | """
Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.
Example
For n = 1230, the output should be
isLucky(n) = true;
For n = 239017, the output should be
isLucky(n) = false.
"""
def isLucky(n):
n_list = [int(i) for i in str(n)]
half = int((len(n_list)/2))
list1 = n_list[:half]
list2 = n_list[half:]
if sum(list1) == sum(list2):
return True
else:
return False | true |
27f090cb703d12372205b7308efe17f5e0a73980 | AndreiBratkovski/CodeFights-Solutions | /Arcade/Intro/Smooth Sailing/commonCharacterCount.py | 718 | 4.34375 | 4 | """
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
"""
def commonCharacterCount(s1, s2):
global_count = 0
char_count1 = 0
char_count2 = 0
s1_set = set(s1)
for i in s1_set:
if i in s2:
char_count1 = s1.count(i)
char_count2 = s2.count(i)
if char_count1 <= char_count2:
global_count += char_count1
elif char_count2 <= char_count1:
global_count += char_count2
return global_count | true |
b7315bf9114c641c1b3493ffef65109da2dc9046 | Surenu1248/Python3 | /eighth.py | 434 | 4.15625 | 4 | # Repeat program 7 with Tuples (Take example from Tutorial)
tpl1 = (10,20,30,40,50,60,70,80,90,100,110)
tpl2 = (11,22,33,44,55,66,77,88,99)
# Printing all Elements.....
print("List Elements are: ", tpl1)
# Slicing Operations.....
print("Slicing Operation: ", tpl1[3:6])
# Repetition.....
print("Repetition of list for 5 times: ", (tpl1,) * 5)
# Concatenation of lst and lst2
print("Combination of lst and lst2: ", tpl1 + tpl2)
| true |
251b26428c895b27abb3e0db7ff0316e5bc8a7e1 | Filjo0/PythonProjects | /Ch3.py | 2,197 | 4.25 | 4 | """
Chapter 3.
11. In the game of Lucky Sevens, the player rolls a pair of dice. If the dots add up to 7,
the player wins $4; otherwise, the player loses $1. Suppose that, to entice the gullible,
a casino tells players that there are lots of ways to win: (1, 6), (2, 5), and so
on. A little mathematical analysis reveals that there are not enough ways to win
to make the game worthwhile; however, because many people’s eyes glaze over
at the first mention of mathematics, your challenge is to write a program that
demonstrates the futility of playing the game. Your program should take as input
the amount of money that the player wants to put into the pot, and play the game
until the pot is e mpty. At that point, the program should print the number of
rolls it took to break the player, as well as maximum amount of money in the pot.
"""
import random
from time import sleep
pot = 0
print("Hello. Lets play \"The Lucky Sevens game\"!",
"\nRules: You roll a pair of dice. If the dots add up to 7, you WIN $4"
"\nOtherwise, you lose $1"
"\nThere are lots of ways to WIN: (1, 6), (2, 5), (3, 4)")
while True:
try:
pot = int(input("How much money would you like to deposit into the pot: $"))
print("Press ENTER to roll a pair of dice")
input()
except ValueError:
print("Please print the number: ")
while pot > 0:
print("Rolling...")
sleep(2)
dice_roll = random.randint(1, 6), random.randint(1, 6)
print("You rolled number:", dice_roll[0], "and", dice_roll[1])
my_roll = (dice_roll[0] + dice_roll[1])
if my_roll == 7:
pot += 4
print("Congratulations! The dots add up to 7! You've won $4 "
"\nYour balance is: $" + str(pot),
"\nPress ENTER to try again")
else:
pot -= 1
print("Unlucky! The dots add up to:", my_roll, "You've lost $1"
"\nYour balance is: $" + str(pot),
"\nPress ENTER to try again")
input()
print("You need to deposit money into your pot")
| true |
3cd6ff12af16a6a3d672cad425a9df0d398cedb1 | lslewis1/Python-Labs | /Week 5 Py Labs/Seconds converter.py | 747 | 4.21875 | 4 | #10/1/14
#This program will take a user input of a number of seconds.
#The program will then display how many full minutes, hours, days, and leftover seconds there are
#ts is the input of seconds
#s1 is the leftover seconds for the minutes
#s2 is the seconds for hours
#s3 is the seconds for days
#m is the number of minutes
#h is the number of hours
#d is the number of days
ts=int(input("Enter the number of seconds :"))
if ts>=60:
m=ts//60
s1=(ts%60)
if ts>=3600:
h=ts//3600
s2=(ts%3600)
if ts>=86400:
d=ts//86400
s3=(ts%86400)
print(ts,"Seconds are equal to :")
print(m,"full minute(s) and",s1,"seconds.")
print(h,"full hour(s) and",s2,"seconds.")
print(d,"full day(s) and",s3,"seconds.")
| true |
c46d80d326ba0b65ca97c0679faa2e50aa384371 | lslewis1/Python-Labs | /Week 5 Py Labs/BMI.py | 530 | 4.34375 | 4 | #10/1/14
#This program will determine a person's BMI
#Then it will display wheter the person in optimal weight, over, or under
#bmi is the body mass indicator
#w is the weight
#h is the height
w=float(input("Enter your weight in pounds :"))
h=float(input("Enter your height in inches :"))
bmi=(w*703)/(h*h)
print("Your body mass indicator is", \
format(bmi, '.2f'))
if bmi>25:
print("You are overweight.")
elif bmi>=18.5:
print("Your weight is optimal.")
else:
print("You are underweight.")
| true |
f22d1886a08da98b613d9ed89432a39d47679830 | lslewis1/Python-Labs | /Week 6 Py Labs/calories burned.py | 327 | 4.125 | 4 | #10/6/14
#This program will use a loop to display the number of calories burned after time.
#The times are: 10,15,20,25, and 30 minutes
#i controls the while loop
#cb is calories burned
#m is minutes
i=10
while i<=30:
m=i
cb=m*3.9
i=i+5
print(cb,"Calories burned for running for", m,"minutes.")
| true |
29260166c31c491e47c68e1674e384bc56c6a2d5 | lslewis1/Python-Labs | /Week 8 Py Labs/Temperature converter.py | 919 | 4.4375 | 4 | #10/20/14
#This program will utilize a for loop to convert a given temperature.
#The conversion will be between celsius and fahrenheit based on user input.
ch=int(input("Enter a 1 for celsuis to fahrenheit, or a 2 for fahrenheit to celsius: "))
if ch==1:
start=int(input("Please enter your start value: "))
end=int(input("Please enter your end value: "))
step=int(input("Please enter what you want to count by: "))
for temp in range(start,end+1,step):
F=(9/5*temp)+32
print(temp,"degrees Celsius =",format(F,'.2f'),"degrees Fahrenheit.")
elif ch==2:
start=int(input("Please enter your start value: "))
end=int(input("Please enter your end value: "))
step=int(input("Please enter what you want to count by: "))
for temp in range(start,end+1,step):
F=(temp-32)*(5/9)
print(temp,"degrees Fahrenheit =",format(F,'.2f'),"degrees Celsius.")
| true |
d31c472acb56ddda5e696e10c957d3d85cf88220 | lslewis1/Python-Labs | /Week 4 Py Labs/Letter grade graded lab.py | 536 | 4.375 | 4 | #9/26/14
#This program will display a student's grade.
#The prgram will print a letter grade after receiving the numerical grade
#Grade is the numerical grade
#Letter is the letter grade
Grade=float(input("Please enter your numerical grade :"))
if Grade>=90:
print("Your letter grade is an A.")
elif Grade>=80:
print("Your letter grade is a B.")
elif Grade>=70:
print("Your letter grade is a C.")
elif Grade>=60:
print("Your letter grade is a D.")
else:
print("Your letter grade is an F.")
| true |
6b6bee3144bce48f71c9eb02c574d7540f0f42da | aaqibgouher/python | /numpy_random/generate_rn.py | 815 | 4.34375 | 4 | from numpy import random
# 1. for random integer till 100. also second parameter is size means how much you wanna generate
# num_1 = random.randint(100) #should give the last value
# print(num_1)
# 2. for random int array :
# num = random.randint(100,size=10)
# print(num)
# 3. for random float ;
# num_2 = random.rand() # last value is not required but if will give n digit then it will show a list containing n elements
# print(num_2)
# 4. for 2d random int array :
# num = random.randint(100,size=(3,5))
# print(num)
# 5. for 2d random float array :
# num = random.rand(3,5)
# print(num)
# 6. random value from an array :
# num = random.choice([1,2,3,4,5])
# print(num)
# 7. from random value in the array generate a 2d array :
# num = random.choice([1,2,3,4,5],size=(2,2))
# print(num) | true |
962557880d2b679913ac49c86658aa8e5bb1205d | aaqibgouher/python | /numpy_eg/vector/summation.py | 995 | 4.21875 | 4 | import numpy as np
# 1. simple add element wise
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# print(np.add(arr_1,arr_2))
# 2. summation - first it will sum the arr_1,arr_2 and arr_3 individually and then sum it at once and will give the output. also axis means it will sum and give the output in one axis
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# arr_3 = np.array([2,4,6,8,10])
# new_arr = np.sum([arr_1,arr_2,arr_3],axis=1)
# print(new_arr)
# 3. cummulative sum
# arr_1 = np.array([1,2,3,4,5])
# print(np.cumsum(arr_1))
# 4. product
# arr_1 = np.array([1,2,3,4,5])
# print(np.prod(arr_1))
# 5. product of more than 2 arrays
# arr_1 = np.array([1,2,3,4,5])
# arr_2 = np.array([1,2,3,4,5])
# print(np.prod([arr_1,arr_2],axis=1)) #if will not give that axis,then it will give prod of both 2 arrays but after giving axis = 1, it will give individual product
# 6. cummulative product
# arr_1 = np.array([1,2,3,4,5])
# print(np.cumprod(arr_1)) | true |
07923c14b2d3cc7e14a49c0eaff1e20d8769b7cb | Jonaugustin/MyContactsAssignment | /main.py | 2,408 | 4.34375 | 4 | contacts = [["John", 311, "noemail@email.com"], ["Robert", 966, "uisemali@email.com"], ["Edward", 346, "nonumber@email.ca"]]
menu = """
Main Menu
1. Display All Contacts Names
2. Search Contacts
3. Edit Contact
4. New Contact
5. Remove Contact
6. Exit
"""
def displayContact():
if contacts:
print("Contact Names are: ")
for i in range(len(contacts)):
print(contacts[i][0])
else:
print("Sorry, as of right now there are no contacts.")
callInput()
def searchContact():
txt = """
Name: {}
Phone Number: {}
Email: {}
"""
cherch = str(input("Please enter name of individual you would wish to search: "))
for i in range(len(contacts)):
for x in contacts[i]:
if cherch == x:
print(txt.format(contacts[i][0], contacts[i][1], contacts[i][2]))
callInput()
def editContact():
cherch = str(input("Please enter name of individual you would wish to search: "))
for i in range(len(contacts)):
for x in contacts[i]:
if cherch == x:
contacts[i][0] = str(input("Please enter in a new name for this contact: "))
contacts[i][1] = int(input("Please enter in a new number for this contact: "))
contacts[i][2] = str(input("Please enter in a new email for this contact: "))
callInput()
def newContact():
name = str(input("Please enter in a name for this contact: "))
phone = int(input("Please enter in a number for this contact: "))
email = str(input("Please enter in an email for this contact: "))
contacts.append([name, phone, email])
callInput()
def removeContact():
cherch = str(input("Please enter name of individual you would wish to remove: "))
for i in range(len(contacts)):
if cherch == contacts[i][0]:
del contacts[i]
break
callInput()
def callInput():
print(menu)
option = int(input("Please select a number from 1 to 6: "))
if option == 1:
displayContact()
elif option == 2:
searchContact()
elif option == 3:
editContact()
elif option == 4:
newContact()
elif option == 5:
removeContact()
elif option == 6:
exit()
else:
option = int(input("Please select a number again from 1 to 6: "))
callInput()
| true |
57d9d25fe134eff49886a76ba6d8ea91f9498073 | nikhilpatil29/AlgoProgram | /algo/MenuDriven.py | 2,442 | 4.125 | 4 | '''
Purpose: Program to perform all sorting operation like
insertion,bubble etc
@author Nikhil Patil
'''
from utility import *
class MenuDriven:
x = utility()
choice = 0
while 1:
print "Menu : "
print "1. binarySearch method for integer"
print "2. binarySearch method for String"
print "3. insertionSort method for integer"
print "4. insertionSort method for String"
print "5. bubbleSort method for integer"
print "6. bubbleSort method for String"
print "7.Exit"
choice = int(input("\nenter your choice\n"))
if choice == 1:
numList = [1,3,6,9,11,32,54,59,61]
print numList
ele = input("enter the element to search")
pos = x.binarySearchInteger(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 2:
numList = ['a','b','c','d','e','f','g']
print numList
ele = raw_input("enter the element to search")
pos = x.binarySearchString(ele,numList)
if (pos != -1):
print ele ," is found at " ,(pos + 1)," position"
else:
print("element not found")
elif choice == 3:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print numList
array1 = x.insertionSortInteger(numList)
print"Sorted Insertion Sort Array : ",array1
elif choice == 4:
array = ["nikhil", "kunal", "zeeshan", "amar"]
print array
array1 = x.insertionSortString(array)
print"Sorted Insertion Sort Array : ",array1
elif choice == 5:
numList = [10, 15, 14, 13, 19, 8, 4, 33]
print "list before sort"
print numList, "\n"
print "list after sort"
print(x.bubbleSort(numList))
elif choice == 6:
array = ["nikhil","kunal","zeeshan","amar"]
print("Sorted Bubble Sort Array : ")
print array
print("Sorted Bubble Sort Array : ")
x.bubbleSortString(array)
else:
exit(0)
#
#
#
# insertionSortString(str1, size)
# print("Sorted Insertion Sort Array : ")
# printStringArray(str1, size)
# break
| true |
cbfa94e5ab45819bb1dd9ee3834ec98d1b826911 | webfarer/python_by_example | /Chapter2/016.py | 317 | 4.125 | 4 | user_rainy = str.lower(input("Tell me pls - is a rainy: "))
if user_rainy == 'yes':
user_umbrella = str.lower(input("It is too windy for an umbrella?: "))
if user_umbrella == 'yes':
print("It is too windy for an umbrella")
else:
print("Take an umbrella")
else:
print("Enjoy your day") | true |
126ba2113fe13cb7a8008b772793718001df3c94 | KacperKubara/USAIS_Workshops | /Clustering/k-means.py | 1,734 | 4.1875 | 4 | # K-NN classification with k-fold cross validation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Read Data
dataset = pd.read_csv("Mall_Customers.csv")
# Choose which features to use
x = dataset.iloc[:, 3:5].values # Features - Age, annual income (k$)
"""
K-Means clustering is unsupervised ML algorithm. It means that
it will figure the classes on its own (contrary to ML classification algorithms)
The purpose of clustering is to find out if a certain group of data points have
similar charactertics, i.e. if they create a cluster
Therefore, we won't need train-test split. Feature scaling might also be unnecessary
as the 2 features have v.similar values
"""
inertia = []
cluster_count = []
from sklearn.cluster import KMeans
for i in range(1,15):
cluster = KMeans(n_clusters = i, random_state = 42)
cluster.fit(x)
inertia.append(cluster.inertia_)
cluster_count.append(i)
fig0, ax0 = plt.subplots()
ax0.plot(cluster_count, inertia)
ax0.set_title("Elbow Method")
ax0.set_xlabel("No. clusters")
ax0.set_ylabel("WCSS")
# By looking on the elbow method plot,
# let's choose n_clusters = 5
# Cluster the data and assign labels ('classes')
cluster = KMeans(n_clusters = 5, random_state = 42)
y_pred = cluster.fit_predict(x)
# Visualise Results
from matplotlib import colors
my_colors = list(colors.BASE_COLORS.keys())
fig1, ax1 = plt.subplots()
ax1.set_title("Clusters")
ax1.set_xlabel("Annual Income")
ax1.set_ylabel("Spending Score")
# Plotting cluster
for i, label in enumerate(cluster.labels_):
ax1.scatter(x[i, 0], x[i, 1], c = my_colors[label])
ax1.scatter(cluster.cluster_centers_[:, 0], cluster.cluster_centers_[:, 1],
s = 300, c = 'yellow', label = 'Centroids')
| true |
f0749405938e25a640b1955262887d8e5924397a | betty29/code-1 | /recipes/Python/52316_Dialect_for_sort_by_then_by/recipe-52316.py | 1,587 | 4.15625 | 4 | import string
star_list = ['Elizabeth Taylor',
'Bette Davis',
'Hugh Grant',
'C. Grant']
star_list.sort(lambda x,y: (
cmp(string.split(x)[-1], string.split(y)[-1]) or # Sort by last name ...
cmp(x, y))) # ... then by first name
print "Sorted list of stars:"
for name in star_list:
print name
#
# "cmp(X, Y)" return 'false' (0) when X and Y compare equal,
# so "or" makes the next "cmp()" to be evaluated.
# To reverse the sorting order, simply swap X and Y in cmp().
#
# This can also be used if we have some other sorting criteria associated with
# the elements of the list. We simply build an auxiliary list of tuples
# to pack the sorting criteria together with the main elements, then sort and
# unpack the result.
#
def sorting_criterium_1(data):
return string.split(data)[-1] # This is again the last name.
def sorting_criterium_2(data):
return len(data) # This is some fancy sorting criterium.
# Pack the auxiliary list:
aux_list = map(lambda x: (x,
sorting_criterium_1(x),
sorting_criterium_2(x)),
star_list)
# Sort:
aux_list.sort(lambda x,y: (
cmp(x[1], y[1]) or # Sort by criteria 1 (last name)...
cmp(y[2], x[2]) or # ... then by criteria 2 (in reverse order) ...
cmp(x, y))) # ... then by the value in the main list.
# Unpack the resulting list:
star_list = map(lambda x: x[0], aux_list)
print "Another sorted list of stars:"
for name in star_list:
print name
| true |
da7d9b543243c19783719c409b67347ce4b126a3 | betty29/code-1 | /recipes/Python/304440_Sorting_dictionaries_value/recipe-304440.py | 843 | 4.21875 | 4 | # Example from PEP 265 - Sorting Dictionaries By Value
# Counting occurences of letters
d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
# operator.itemgetter is new in Python 2.4
# `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter
# Items sorted by key
# The new builtin `sorted()` will return a sorted copy of the input iterable.
print sorted(d.items())
# Items sorted by key, in reverse order
# The keyword argument `reverse` operates as one might expect
print sorted(d.items(), reverse=True)
# Items sorted by value
# The keyword argument `key` allows easy selection of sorting criteria
print sorted(d.items(), key=itemgetter(1))
# In-place sort still works, and also has the same new features as sorted
items = d.items()
items.sort(key = itemgetter(1), reverse=True)
print items
| true |
809a2e466bf5784e776a0249cf43460147cb14e0 | betty29/code-1 | /recipes/Python/578935_Garden_Requirements_Calculator/recipe-578935.py | 2,723 | 4.21875 | 4 | '''
9-16-2014
Ethan D. Hann
Garden Requirements Calculator
'''
import math
#This program will take input from the user to determine the amount of gardening materials needed
print("Garden Requirements Calculator")
print("ALL UNITS ENTERED ARE ASSUMED TO BE IN FEET")
print("_____________________________________________________")
print("")
#Gather all necessary input from user
side_length = input("Enter the length of one side of garden: ")
spacing = input("Enter the spacing between plants: ")
depth_garden = input("Enter the depth of the garden soil: ")
depth_fill = input("Enter the depth of the fill: ")
#Convert input to floats so that we can do math with them
side_length = float(side_length)
spacing = float(spacing)
depth_garden = float(depth_garden)
depth_fill = float(depth_fill)
#Calculate radius of each circle and semi-circle
r = side_length / 4
#1 - Number of plants for all semi-circles
area = (math.pi * (r**2)) / 2
number_plants_semi = math.trunc(area / (spacing**2))
#2 - Number of plants for the circle garden
area = math.pi * (r**2)
number_plants_circle = math.trunc(area / (spacing**2))
#3 - Total number of plants for garden
total_number_plants = number_plants_circle + (number_plants_semi*4)
#4 - Soil for each semi-circle garden in cubic yards
volume = (math.pi * (r**2) * depth_garden) / 2
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_semi = round(cubic_volume, 1)
#5 - Soil for circle garden in cubic yards
volume = math.pi * (r**2) * depth_garden
#Convert to cubic yards
cubic_volume = volume / 27
cubic_volume_rounded_circle = round(cubic_volume, 1)
#6 - Total amount of soil for the garden
total_soil = (cubic_volume_rounded_semi * 4) + cubic_volume_rounded_circle
total_soil_rounded = round(total_soil, 1)
#7 - Total fill for the garden
volume_whole = (side_length**2) * depth_fill
all_volume_circle = (math.pi * (r**2) * depth_garden) * 3
total_volume_fill = volume_whole - all_volume_circle
cubic_total_volume_fill = total_volume_fill / 27
cubic_total_volume_fill_rounded = round(cubic_total_volume_fill, 1)
#Print out the results
print("")
print("You will need the following...")
print("Number of plants for each semi-circle garden:", number_plants_semi)
print("Number of plants for the circle garden:", number_plants_circle)
print("Total number of plants for the garden:", total_number_plants)
print("Amount of soil for each semi-circle garden:", cubic_volume_rounded_semi, "cubic yards")
print("Amount of soil for the circle garden:", cubic_volume_rounded_circle, "cubic yards")
print("Total amount of soil for the garden:", total_soil_rounded, "cubic yards")
print("Total amount of fill for the garden:", cubic_total_volume_fill_rounded, "cubic yards")
| true |
e2f6af7d70e34e1fd89e1239bcbac0709810dc25 | betty29/code-1 | /recipes/Python/577344_Maclaurinsseriescos2x/recipe-577344.py | 1,458 | 4.15625 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/008/10
#version :2.6
"""
maclaurin_cos_2x is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos(2x) = 1- 2^2*x^2/2! + 2^4*x^4/4! - 2^6*x^6/6! ...........
"""
from math import *
def maclaurin_cos_2x(value,k):
"""
Compute maclaurin's series approximation for cos(2x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos(2x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**item)*(value*pi/180)**item/factorial(item)
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos_2x_1 = maclaurin_cos_2x(60,100)
print maclaurin_cos_2x_1
maclaurin_cos_2x_2 = maclaurin_cos_2x(45,100)
print maclaurin_cos_2x_2
maclaurin_cos_2x_3 = maclaurin_cos_2x(30,100)
print maclaurin_cos_2x_3
######################################################################FT python "C:\
#urine series\M
#-0.5
#0.0
#0.5
| true |
a752a877f7aa023a64622cb406d86f9655133808 | betty29/code-1 | /recipes/Python/577345_Maclaurinsseriescos_x/recipe-577345.py | 1,429 | 4.21875 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/08/10
#version :2.6
"""
maclaurin_cos_pow2 is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos²(x) = 1- x^2 + 2^3*x^4/4! - 2^5*x^6/6! ...........
"""
from math import *
def maclaurin_cos_pow2(value,k):
"""
Compute maclaurin's series approximation for cos^2(x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos^2(x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**(item-1))*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**(item-1))*((value*pi/180)**item/factorial(item))
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos1 = maclaurin_cos_pow2(135,100)
print maclaurin_cos1
maclaurin_cos2 = maclaurin_cos_pow2(45,100)
print maclaurin_cos2
maclaurin_cos3 = maclaurin_cos_pow2(30,100)
print maclaurin_cos3
#############################################################
#FT python "C:
#0.5
#0.5
#0.75
| true |
a5431bb48049aa784132d0a08a866223d580d2d4 | betty29/code-1 | /recipes/Python/577574_PythInfinite_Rotations/recipe-577574.py | 2,497 | 4.28125 | 4 | from itertools import *
from collections import deque
# First a naive approach. At each generation we pop the first element and append
# it to the back. This is highly memmory deficient.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = list(it)
for i in range(len(l)):
yield iter(l)
l = l[1:]+[l[0]]
# A much better approach would seam to be using a deque, which rotates in O(1),
# However this does have the negative effect, that generating the next rotation
# before the current has been iterated through, will result in a RuntimeError
# because the deque has mutated during iteration.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = deque(it)
for i in range(len(l)):
yield iter(l)
l.rotate()
# The trick is to use subsets of infinite lists. First we define the function tails,
# which is standard in many functal languages.
# Because of the way tee is implemented in itertools, the below implementation will
# use memory only propertional to the offset difference between the generated
# iterators.
def tails(it):
""" tails([1,2,3,4,5]) --> [[1,2,3,4,5], [2,3,4,5], [3,4,5], [4,5], [5], []] """
while True:
tail, it = tee(it)
yield tail
next(it)
# We can now define two new rotations functions.
# The first one is very similar to the above, but since we never keep all list
# elements, we need an extra length parameter.
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return (islice(rot,N) for rot in islice(tails(cycle(it)),N))
# The above works fine for things like:
# >>> for rot in rotations(range(4), 4):
# ... print (list(rot))
# ...
# [0, 1, 2, 3]
# [1, 2, 3, 0]
# [2, 3, 0, 1]
# [3, 0, 1, 2]
#
# But that is not really where it shines, since the lists are iterated one after
# another, and so the tails memory usage becomes linear.
#
# In many cases tails and infinite lists lets us get away with an even simpler
# rotaions function:
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return islice(tails(cycle(it)),N)
# This one works great for instances where we are topcut anyway:
# >>> for rot in rotations(range(4), 4):
# ... print (list(zip(range(4), rot)))
# ...
# [(0, 0), (1, 1), (2, 2), (3, 3)]
# [(0, 1), (1, 2), (2, 3), (3, 0)]
# [(0, 2), (1, 3), (2, 0), (3, 1)]
# [(0, 3), (1, 0), (2, 1), (3, 2)]
| true |
d821b07149089dba24a238c3ad83d5c8b6642fd6 | betty29/code-1 | /recipes/Python/577965_Sieve_Eratosthenes_Prime/recipe-577965.py | 986 | 4.34375 | 4 | def primeSieve(x):
'''
Generates a list of odd integers from 3 until input, and crosses
out all multiples of each number in the list.
Usage:
primeSieve(number) -- Finds all prime numbers up until number.
Returns: list of prime integers (obviously).
Time: around 1.5 seconds when number = 1000000.
'''
numlist = range(3, x+1, 2)
counter = 0 # Keeps count of index in while loop
backup = 0 # Used to reset count after each iteration and keep count outside of while loop
for num in numlist:
counter = backup
if num != 0:
counter += num
while counter <= len(numlist)-1: # Sifts through multiples of num, setting them all to 0
numlist[counter] = 0
counter += num
else: # If number is 0 already, skip
pass
backup += 1 # Increment backup to move on to next index
return [2] + [x for x in numlist if x]
| true |
849e48eba0db9689f82e2c23ec9d9ae777c78a54 | betty29/code-1 | /recipes/Python/466321_recursive_sorting/recipe-466321.py | 443 | 4.25 | 4 | """
recursive sort
"""
def rec_sort(iterable):
# if iterable is a mutable sequence type
# sort it
try:
iterable.sort()
# if it isn't return item
except:
return iterable
# loop inside sequence items
for pos,item in enumerate(iterable):
iterable[pos] = rec_sort(item)
return iterable
if __name__ == '__main__':
struct = [[1,2,3,[6,4,5]],[2,1,5],[4,3,2]]
print rec_sort(struct)
| true |
25fc1d2d9fe540cc5e2994ac04c875cb40df2f8c | betty29/code-1 | /recipes/Python/334695_PivotCrosstabDenormalizatiNormalized/recipe-334695.py | 2,599 | 4.40625 | 4 | def pivot(table, left, top, value):
"""
Creates a cross-tab or pivot table from a normalised input table. Use this
function to 'denormalize' a table of normalized records.
* The table argument can be a list of dictionaries or a Table object.
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621)
* The left argument is a tuple of headings which are displayed down the
left side of the new table.
* The top argument is a tuple of headings which are displayed across the
top of the new table.
Tuples are used so that multiple element headings and columns can be used.
Eg. To transform the list (listOfDicts):
Name, Year, Value
-----------------------
'Simon', 2004, 32
'Russel', 2004, 64
'Simon', 2005, 128
'Russel', 2005, 32
into the new list:
'Name', 2004, 2005
------------------------
'Simon', 32, 128
'Russel', 64, 32
you would call pivot with the arguments:
newList = pivot(listOfDicts, ('Name',), ('Year',), 'Value')
"""
rs = {}
ysort = []
xsort = []
for row in table:
yaxis = tuple([row[c] for c in left])
if yaxis not in ysort: ysort.append(yaxis)
xaxis = tuple([row[c] for c in top])
if xaxis not in xsort: xsort.append(xaxis)
try:
rs[yaxis]
except KeyError:
rs[yaxis] = {}
if xaxis not in rs[yaxis]:
rs[yaxis][xaxis] = 0
rs[yaxis][xaxis] += row[value]
headings = list(left)
headings.extend(xsort)
t = []
#If you want a list of dictionaries returned, use a cheaper alternative,
#the Table class at:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621
#and replace the above line with this code:
#t = Table(*headings)
for left in ysort:
row = list(left)
row.extend([rs[left][x] for x in rs[left]])
t.append(dict(zip(headings,row)))
return t
if __name__ == "__main__":
import random
#Build a list of dictionaries
c = "Employee","Year","Month","Value"
d = []
for y in xrange(2003,2005):
for m in xrange(1,13):
for e in xrange(1,6):
d.append(dict(zip(c,(e,y,m,random.randint(10,90)))))
#pivot the list contents using the 'Employee' field for the left column,
#and the 'Year' field for the top heading and the 'Value' field for each
#cell in the new table.
t = pivot(d,["Employee"],["Year"],"Value")
for row in t:
print row
| true |
a2e8e4bc7ec3c702eca1668891cfe72ea1a70113 | betty29/code-1 | /recipes/Python/502260_Parseline_break_text_line_informatted/recipe-502260.py | 1,089 | 4.1875 | 4 | def parseline(line,format):
"""\
Given a line (a string actually) and a short string telling
how to format it, return a list of python objects that result.
The format string maps words (as split by line.split()) into
python code:
x -> Nothing; skip this word
s -> Return this word as a string
i -> Return this word as an int
d -> Return this word as an int
f -> Return this word as a float
Basic parsing of strings:
>>> parseline('Hello, World','ss')
['Hello,', 'World']
You can use 'x' to skip a record; you also don't have to parse
every record:
>>> parseline('1 2 3 4','xdd')
[2, 3]
>>> parseline('C1 0.0 0.0 0.0','sfff')
['C1', 0.0, 0.0, 0.0]
"""
xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
result = []
words = line.split()
for i in range(len(format)):
f = format[i]
trans = xlat.get(f)
if trans: result.append(trans(words[i]))
if len(result) == 0: return None
if len(result) == 1: return result[0]
return result
| true |
486e319264ee6470f902c3dd3240f614d06dff83 | betty29/code-1 | /recipes/Python/498090_Finding_value_passed_particular_parameter/recipe-498090.py | 1,180 | 4.125 | 4 | import inspect
def get_arg_value(func, argname, args, kwargs):
"""
This function is meant to be used inside decorators, when you want
to find what value will be available inside a wrapped function for
a particular argument name. It handles positional and keyword
arguments and takes into account default values. For example:
>>> def foo(x, y): pass
...
>>> get_arg_value(foo, 'y', [1, 2], {})
2
>>> get_arg_value(foo, 'y', [1], {'y' : 2})
2
>>> def foo(x, y, z=300): pass
...
>>> get_arg_value(foo, 'z', [1], {'y' : 2})
300
>>> get_arg_value(foo, 'z', [1], {'y' : 2, 'z' : 5})
5
"""
# first check kwargs
if argname in kwargs:
return kwargs[argname]
# OK. could it be a positional argument?
regargs, varargs, varkwargs, defaults=inspect.getargspec(func)
if argname in regargs:
regdict=dict(zip(regargs, args))
if argname in regdict:
return regdict[argname]
defaultdict=dict(zip(reversed(regargs), defaults))
if argname in defaultdict:
return defaultdict[argname]
raise ValueError("no such argument: %s" % argname)
| true |
f15d9fdb5bd40bfa44342919598f3df07340b086 | J-Cook-jr/python-dictionaries | /hotel.py | 334 | 4.125 | 4 | # This program creates a dictionary of hotel rooms and it's occupants.
# Create a dictionary that lists the room number and it's occupants.
earlton_hotel ={
"Room 101" : "Harley Cook",
"Room 102" : "Mildred Tatum",
"Room 103" : "Jewel Cook",
"Room 104" : "Tiffany Waters",
"Room 105" : "Dejon Waters"
}
print(earlton_hotel) | true |
f74e3aaff1778023fc4d7180c9c3e7a96cd871ee | MatthewGerges/CS50-Programming-Projects | /MatthewGerges-cs50-problems-2021-x-sentimental-readability/readability.py | 2,780 | 4.125 | 4 | from cs50 import get_string
# import the get_string function from cs50's library
def main():
# prompt the user to enter a piece of text (a paragraph/ excerpt)
paragraph1 = get_string("Text: ")
letters = count_letters(paragraph1)
# the return value of count_letters (how many letters there are in a paragraph) is assigned to the variable letters
words = count_words(paragraph1)
# the variable words is assigned the return value of the count_words function (tells you how many words are in a paragraph)
sentences = count_sentences(paragraph1)
# the variable sentences is assigned the return value of the count_sentences function(tells you how many sentences are in a paragraph)
# letters100 is automatically converted to a double in python
letters100 = (letters * 100) / words
# calculate the average number of letters and sentences per 100 words in the text
sentences100 = (sentences * 100) / words
formula = (0.0588 * letters100) - (0.296 * sentences100) - 15.8
# The above is Coleman-Liau formula, whose rounded value tells you the grade-reading level of a particular text
grade = round(formula)
# if formula gives you a number between 1 and 16, print that number as the grade reading level
if (grade >= 1 and grade < 16):
print(f"Grade {grade}")
# if the formula gives you a number that it is not in that range, specify if it is too low or too high of a reading level
elif (grade < 1):
print("Before Grade 1")
elif (grade >= 16):
print("Grade 16+")
# count the letters in the paragraph by checking the if the letters are alphabetical
def count_letters(paragraph):
letters = 0
for char in paragraph:
if char.isalpha():
# char.isalpha() returns true if a character is a letter and false otherwise
letters += 1
return letters
# count the words in the paragraph by adding 1 to the number of spaces
def count_words(paragraph):
words = 1
for i in range(len(paragraph)):
if (" " == paragraph[i]):
words += 1
return words
# count the number of sentences by counting the number of punctuation marks in the paragraph (compare strings and add to a counting variable)
def count_sentences(paragraph):
sentences = 0
for i in range(len(paragraph)):
# check for periods, exclamations, and question marks
if (paragraph[i] == "." or paragraph[i] == "!" or paragraph[i] == "?"):
sentences += 1
return sentences
main()
'''
# This is how to iterate through each character in a string and check if it is a letter
s = 'a123b'
for char in s:
print(char, char.isalpha())
''' | true |
ae6a511723cc0f54dc39d56b2c9ed70ed3bb9305 | lnbe10/Math-Thinking-for-Comp-Sci | /combinatory_analysis/dice-game.py | 2,755 | 4.1875 | 4 | # dice game:
# a shady person has various dices in a table
# the dices can have arbitrary values in their
# sides, like:
# [1,1,3,3,6,6]
# [1,2,3,4,5,6]
# [9,9,9,9,9,1]
# The shady person lets you see the dices
# and tell if you want to choose yor dice before
# or after him
# after both of you choose,
# them roll your dices, and see
# who wins (the one with bigger number showing up)
# to maximize the chances of winning, you have to
# do some tasks:
# 1- check if there's a dice better than all others
# 1.1 - if it exists, you choose first and select it
# 1.2 - if it doesn't exist, you let the shady person
# choose a dice and you choose one wich is better
# than his one .-.
def count_wins(dice1, dice2):
assert len(dice1) == 6 and len(dice2) == 6
dice1_wins, dice2_wins = 0, 0
for i in dice1:
for j in dice2:
if i>j:
dice1_wins+=1;
if j>i:
dice2_wins+=1;
return (dice1_wins, dice2_wins)
dice1 = [1, 2, 3, 4, 5, 6];
dice2 = [1, 2, 3, 4, 5, 6];
count_wins(dice1,dice2);
dice3 = [1, 1, 6, 6, 8, 8];
dice4 = [2, 2, 4, 4, 9, 9];
count_wins(dice3,dice4);
def find_the_best_dice(dices):
assert all(len(dice) == 6 for dice in dices)
wins = [0 for i in range(len(dices))];
for i in range(len(dices)):
for j in range(i+1, len(dices)):
versus = count_wins(dices[i], dices[j]);
if versus[0]>versus[1]:
wins[i]+=1;
if versus[1]>versus[0]:
wins[j]+=1;
if max(wins) == len(dices)-1:
#print('best dice is', wins.index(max(wins)));
return wins.index(max(wins));
#print('no best dice');
return -1
find_the_best_dice([[1, 1, 6, 6, 8, 8], [2, 2, 4, 4, 9, 9], [3, 3, 5, 5, 7, 7]]);
find_the_best_dice([[3, 3, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [4, 4, 4, 4, 0, 0], [5, 5, 5, 1, 1, 1]]);
find_the_best_dice([[1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7], [1, 2, 3, 4, 5, 6]]);
def compute_strategy(dices):
assert all(len(dice) == 6 for dice in dices)
strategy = dict()
strategy["choose_first"] = True
strategy["first_dice"] = 0
for i in range(len(dices)):
strategy[i] = (i + 1) % len(dices)
if find_the_best_dice(dices) != -1:
strategy["choose_first"] = True;
strategy["first_dice"] = find_the_best_dice(dices);
else:
strategy["choose_first"] = False;
for i in range(len(dices)):
for j in range(i+1, len(dices)):
versus = count_wins(dices[i], dices[j]);
if versus[0]>versus[1]:
strategy[j]=i;
if versus[1]>versus[0]:
strategy[i]=j;
print(strategy);
return strategy;
dices = [[4, 4, 4, 4, 0, 0], [7, 7, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [5, 5, 5, 1, 1, 1]];
compute_strategy(dices);
dices2 = [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]];
#compute_strategy(dices2);
| true |
a60df60f1bd19896da30e8d46be5fee3a020413c | battyone/Practical-Computational-Thinking-with-Python | /ch4_orOperator.py | 220 | 4.125 | 4 | A = True
B = False
C = A and B
D = A or B
if C == True:
print("A and B is True.")
else:
print("A and B is False.")
if D == True:
print("A or B is True.")
else:
print("A or B is False.")
| true |
255c09b29bc9cd76e730a64a0722d24b003297c8 | ugneokmanaite/api_json | /json_exchange_rates.py | 1,068 | 4.3125 | 4 | import json
# create a class Exchange Rates
class ExchangeRates:
# with required attributes
def __init__(self):
pass
# method to return the exchange rates
def fetch_ExchangeRates(self):
with open("exchange_rates.json", "r") as jsonfile:
dataset = json.load(jsonfile)
# For loop to get all exchange rates
for e in dataset:
if e == "rates":
print(dataset(["rates"]))
currency = input("What currency would you like the exchange rate of, please see list.\n")
# display exchange rates with specific currencies
print(dataset["rates"][currency])
e = ExchangeRates
e.__init__(ExchangeRates)
# fetch the data from exchange_rates.json
# method to return the exchange rates
# creating an object of class
# rate_display = ExchangeRates ("exchange_rates.json")
# print(rate_display.rates)
# display the data
# display the type of data
# method to return the exchange rates
# display exchange rates with specific currencies
| true |
9445b358d4c35b1caec4c3bc2620b47ef514d331 | MathewsPeter/PythonProjects | /biodata_validater.py | 1,124 | 4.5625 | 5 | '''Example: What is your name? If the user enters * you prompt them that the input is wrong, and ask them to enter a valid name.
At the end you print a summary that looks like this:
- Name: John Doe
- Date of birth: Jan 1, 1954
- Address: 24 fifth Ave, NY
- Personal goals: To be the best programmer there ever was.
'''
while(1):
name = input("Enter name: ")
if name.replace(" ", "").isalpha():
break
print("Name shall have only alphabets and space. Please try again.\n")
while(1):
dob = input("Enter DOB as DDMMYYY: ")
dd = (int)(dob[0:2])
mm = (int)(dob[2:4])
yyyy = (int)(dob[4:8])
if(dd>0 and dd<=31):
if(mm>0 and mm<=12):
if(yyyy>1900 and yyyy<=2021):
break;
else:
print("Year should be between 1900 and 2021. Please try again.\n")
else:
print("Month should be between 1 and 12. Please try again.\n")
else:
print("Date should be between 1 and 31. Please try again.\n")
print("Name is ", name)
print("DOB is ", dd,"-",mm,"-",yyyy)
| true |
f105606ceb0d3a72e2d35e88a78952fed10f38a7 | MathewsPeter/PythonProjects | /bitCountPosnSet.py | 408 | 4.15625 | 4 | '''
input a 8bit Number
count the number of 1s in it's binary representation
consider that as a number, swap the bit at that position
'''
n = (int)(input("enter a number between [0,127] both inclusive"))
if n<0 or n>127:
print("enter properly")
else:
n_1= n
c = 0
while n:
if n&0b1:
c+=1
n = n>>1
print(c)
n_2 = n_1 ^ (1<<c)
print(n_2)
| true |
3966d55212271c1a681156beaee25f6820a076fc | zsamantha/coding_challenge | /calc.py | 1,217 | 4.125 | 4 | import math
print("Welcome to the Calculator App")
print("The following operations are available: + - / *")
print("Please separate entries with a space. Ex: Use 1 + 2 instead of 1+2")
print("Type \"Q\" to quit the program.")
result = None
op = None
while(True):
calc = input().strip().split()
if calc[0].lower() == "q":
break
for item in calc:
if item.isnumeric():
if result is None:
result = int(item)
else:
num = int(item)
if op == "+":
result += num
elif op == "-":
result -= num
elif op == "*":
result *= num
elif op == "/":
result /= num
else:
print("Bad Input.")
result = None
break
elif item.isalpha():
print("Bad Input")
result = None
break
else:
op = item
if result is not None:
if result % 1 == 0:
print("= ", math.trunc(result))
else:
print("= {0:.2f}".format(result))
print("Goodbye :)") | true |
31d0b19e04fce106e14c19aec9d7d6f463f0d852 | panchaly75/MyCaptain_AI | /AI_MyCaptainApp_03(1).py | 863 | 4.3125 | 4 | #Write a Python Program for Fibonacci numbers.
def fibo(input_number):
fibonacci_ls=[]
for count_term in range(input_number):
if count_term==0:
fibonacci_ls.append(0)
elif count_term==1:
fibonacci_ls.append(1)
else:
fibonacci_ls.append(fibonacci_ls[count_term-2]+fibonacci_ls[count_term-1])
return fibonacci_ls
number = int(input("Enter how much terms you want?\t:\t"))
ls = fibo(number)
print(ls)
'''
#if you want to print without list type, so in place of print(ls), you can use below lines of code
for item in ls:
print(item, end=' ')
#in place of define fuction you may also use only for loop
https://github.com/panchaly75/MyCaptainPythonProjects/blob/main/project03.py
in this above github link has same code with for loop
'''
#https://colab.research.google.com/drive/1gK-J2dPT7Cn5HP0EFNJrf0S-6x0pyWki?usp=sharing
| true |
ebb169123be03b88cdd6dcfab33657bd4a60f573 | Devlin1834/Games | /collatz.py | 1,792 | 4.15625 | 4 | ## Collatz Sequence
## Idea from Al Sweigart's 'Automate the Boring Stuff'
def collatz():
global over
over = False
print("Lets Explore the Collatz Sequence")
print("Often called the simplest impossible math problem,")
print("the premise is simple, but the results are confusing!")
print("Lets start and see if you can catch on...")
c = ''
while c == '':
try:
c = int(input("Type in any integer: "))
except ValueError:
print("Thats very funny but its NOT an integer")
while c != 1:
if c % 2 == 0:
c = c // 2
print(c)
elif c % 2 == 1:
c = (3 * c) + 1
print(c)
if c == 1:
print("Do you get it?")
print("For ANY real integer, you can reduce it down to 1 using the Collatz Sequence")
print("If the number is even, take n/2")
print("If the number is odd, take 3n+1")
print("Follow that sequence with your answers until you reach 1")
print()
print("Lets keep going")
print("Type 0 at any point to return to the Games screen")
while over == False:
newc = ''
while newc != 0:
try:
print("-" * 65)
newc = int(input("Type in any number: "))
except ValueError:
print("Thats very funny but its NOT a number")
if newc == 0:
over = True
break
while newc != 1:
if newc % 2 == 0:
newc = newc // 2
print(newc)
elif newc % 2 == 1:
newc = (3 * newc) + 1
print(newc)
| true |
26a77eaf507d1b0107e311ee09706bc352e70ced | ScottG489/Task-Organizer | /src/task/task.py | 2,528 | 4.125 | 4 | """Create task objects
Public classes:
Task
TaskCreator
Provides ways to instantiate a Task instance.
"""
from textwrap import dedent
# TODO: Should this be private if TaskCreator is to be the only
# correct way to make a Task instance?
class Task():
"""Instantiate a Task object.
Provides attributes for tasks and methods to compare Task instances.
"""
def __init__(self, **kwargs):
try:
self.key = kwargs['key']
except KeyError:
self.key = None
try:
self.title = kwargs['title']
except KeyError:
self.title = None
try:
self.notes = kwargs['notes']
except KeyError:
self.notes = None
# self.priority = priority
# self.tags = tags
def __str__(self):
return dedent('''\
ID: %(key)s
Title: %(title)s
Notes: %(notes)s''') % {
'key': self.key,
'title': self.title,
'notes': self.notes
}
def __eq__(self, other):
if not isinstance(other, Task):
return False
if self.key == other.key\
and self.title == other.title\
and self.notes == other.notes:
return True
return False
def __ne__(self, other):
if not isinstance(other, Task):
return True
if self.key != other.key\
or self.title != other.title\
or self.notes != other.notes:
return True
return False
class TaskCreator():
"""Create a Task instance automatically.
Public methods:
build(arg_dict)
Create a Task instance in a automatic and safer manner."""
def __init__(self):
pass
@staticmethod
def build(arg_dict):
"""Creates a Task instance given a dictionary.
Args:
arg_dict (dict): dictionary formatted to create a Task
The given dictionary must have a correct naming scheme. However, it
can be missing any field.
"""
task_item = Task()
try:
task_item.key = arg_dict['key']
except KeyError:
task_item.key = None
try:
task_item.title = arg_dict['title']
except KeyError:
task_item.title = None
try:
task_item.notes = arg_dict['notes']
except KeyError:
task_item.notes = None
return task_item
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.