blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
26c7ace59a7074f0584cd63e7f21eedc2159579e | ephreal/CS | /searching/python/binary_search.py | 549 | 4.21875 | 4 | def binary_search(search_list, target):
""""
An implementation of a binary search in python.
Returns the index in the list if the item is found. Returns None
if not.
"""
first = 0
last = len(search_list) - 1
while first <= last:
midpoint = (first + last) // 2
if search_list[midpoint] == target:
return midpoint
elif search_list[midpoint] < target:
first = midpoint + 1
elif search_list[midpoint] > target:
last = midpoint - 1
return None
| true |
7f8ca8e54858853fb057e7076eed9b9c634b82b6 | PacktPublishing/The-Complete-Python-Course | /1_intro/lectures/15_dictionaries/code.py | 921 | 4.625 | 5 | friend_ages = {"Rolf": 24, "Adam": 30, "Anne": 27}
print(friend_ages["Rolf"]) # 24
# friend_ages["Bob"] ERROR
# -- Adding a new key to the dictionary --
friend_ages["Bob"] = 20
print(friend_ages) # {'Rolf': 24, 'Adam': 30, 'Anne': 27, 'Bob': 20}
# -- Modifying existing keys --
friend_ages["Rolf"] = 25
print(friend_ages) # {'Rolf': 25, 'Adam': 30, 'Anne': 27, 'Bob': 20}
# -- Lists of dictionaries --
# Imagine you have a program that stores information about your friends.
# This is the perfect place to use a list of dictionaries.
# That way you can store multiple pieces of data about each friend, all in a single variable.
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27},
]
# You can turn a list of lists or tuples into a dictionary:
friends = [("Rolf", 24), ("Adam", 30), ("Anne", 27)]
friend_ages = dict(friends)
print(friend_ages)
| true |
8c8020d86d108df7264b3448c4f6cbfa6c6fc7a3 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/05_argument_unpacking/code.py | 2,507 | 4.90625 | 5 | """
* What is argument unpacking?
* Unpacking positional arguments
* Unpacking named arguments
* Example (below)
Given a function, like the one we just looked at to add a balance to an account:
"""
accounts = {
'checking': 1958.00,
'savings': 3695.50
}
def add_balance(amount: float, name: str) -> float:
"""Function to update the balance of an account and return the new balance."""
accounts[name] += amount
return accounts[name]
"""
Imagine we’ve got a list of transactions that we’ve downloaded from our bank page; and they look somewhat like this:
"""
transactions = [
(-180.67, 'checking'),
(-220.00, 'checking'),
(220.00, 'savings'),
(-15.70, 'checking'),
(-23.90, 'checking'),
(-13.00, 'checking'),
(1579.50, 'checking'),
(-600.50, 'checking'),
(600.50, 'savings'),
]
"""
If we now wanted to add them all to our accounts, we’d do something like this:
"""
for t in transactions:
add_balance(t[0], t[1])
"""
What we’re doing here something very specific: *passing all elements of an iterable as arguments, one by one*.
Whenever you need to do this, there’s a shorthand in Python that we can use:
"""
for t in transactions:
add_balance(*t) # passes each element of t as an argument in order
"""
In section 9 we looked at this code when we were studying `map()`:
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
@classmethod
def from_dict(cls, data):
return cls(data['username'], data['password'])
# imagine these users are coming from a database...
users = [
{ 'username': 'rolf', 'password': '123' },
{ 'username': 'tecladoisawesome', 'password': 'youaretoo' }
]
user_objects = map(User.from_dict, users)
"""
The option of using a list comprehension is slightly uglier, I feel:
"""
user_objects = [User.from_dict(u) for u in users]
"""
Instead of having a `from_dict` method in there, we could do this, using named argument unpacking:
"""
class User:
def __init__(self, username, password):
self.username = username
self.password = password
users = [
{ 'username': 'rolf', 'password': '123' },
{ 'username': 'tecladoisawesome', 'password': 'youaretoo' }
]
user_objects = [User(**data) for data in users]
"""
If our data was not in dictionary format, we could do:
"""
users = [
('rolf', '123'),
('tecladoisawesome', 'youaretoo')
]
user_objects = [User(*data) for data in users]
| true |
85748dc41cd9db69df420983540035e866d89a7e | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/7_else_with_loops/code.py | 591 | 4.34375 | 4 | # On loops, you can add an `else` clause. This only runs if the loop does not encounter a `break` or an error.
# That means, if the loop completes successfully, the `else` part will run.
cars = ["ok", "ok", "ok", "faulty", "ok", "ok"]
for status in cars:
if status == "faulty":
print("Stopping the production line!")
break
print(f"This car is {status}.")
else:
print("All cars built successfully. No faulty cars!")
# Remove the "faulty" and you'll see the `else` part starts running.
# Link: https://blog.tecladocode.com/python-snippet-1-more-uses-for-else/
| true |
533360c4d458f8e2fc579b60af0441f5ec49ec17 | PacktPublishing/The-Complete-Python-Course | /6_files/files_project/friends.py | 735 | 4.3125 | 4 | # Ask the user for a list of 3 friends
# For each friend, we'll tell the user whether they are nearby
# For each nearby friend, we'll save their name to `nearby_friends.txt`
friends = input('Enter three friend names, separated by commas (no spaces, please): ').split(',')
people = open('people.txt', 'r')
people_nearby = [line.strip() for line in people.readlines()]
people.close()
friends_set = set(friends)
people_nearby_set = set(people_nearby)
friends_nearby_set = friends_set.intersection(people_nearby_set)
nearby_friends_file = open('nearby_friends.txt', 'w')
for friend in friends_nearby_set:
print(f'{friend} is nearby! Meet up with them.')
nearby_friends_file.write(f'{friend}\n')
nearby_friends_file.close()
| true |
c712a62a9b104cbb2345f00b18dfdee6712d5c0c | PacktPublishing/The-Complete-Python-Course | /2_intro_to_python/lectures/15_functions/code.py | 894 | 4.3125 | 4 | # So far we've been using functions such as `print`, `len`, and `zip`.
# But we haven't learned how to create our own functions, or even how they really work.
# Let's create our own function. The building blocks are:
# def
# the name
# brackets
# colon
# any code you want, but it must be indented if you want it to run as part of the function.
def greet():
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Running this does nothing, because although we have defined a function, we haven't executed it.
# We must execute the function in order for its contents to run.
greet()
# You can put as much or as little code as you want inside a function, but prefer shorter functions over longer ones.
# You'll usually be putting code that you want to reuse inside functions.
# Any variables declared inside the function are not accessible outside it.
print(name) # ERROR!
| true |
fab51111c8d19f063d67d289cfeef4c9a71bb801 | PacktPublishing/The-Complete-Python-Course | /7_second_milestone_project/milestone_2_files/app.py | 1,197 | 4.1875 | 4 | from utils import database
USER_CHOICE = """
Enter:
- 'a' to add a new book
- 'l' to list all books
- 'r' to mark a book as read
- 'd' to delete a book
- 'q' to quit
Your choice: """
def menu():
database.create_book_table()
user_input = input(USER_CHOICE)
while user_input != 'q':
if user_input == 'a':
prompt_add_book()
elif user_input == 'l':
list_books()
elif user_input == 'r':
prompt_read_book()
elif user_input == 'd':
prompt_delete_book()
user_input = input(USER_CHOICE)
def prompt_add_book():
name = input('Enter the new book name: ')
author = input('Enter the new book author: ')
database.add_book(name, author)
def list_books():
for book in database.get_all_books():
read = 'YES' if book['read'] else 'NO'
print(f"{book['name']} by {book['author']} — Read: {read}")
def prompt_read_book():
name = input('Enter the name of the book you just finished reading: ')
database.mark_book_as_read(name)
def prompt_delete_book():
name = input('Enter the name of the book you wish to delete: ')
database.delete_book(name)
menu()
| true |
42677deb29fcb61c5aeff5b093742d97952c9e27 | PacktPublishing/The-Complete-Python-Course | /10_advanced_python/lectures/10_timing_your_code/code.py | 1,661 | 4.5 | 4 | """
As well as the `datetime` module, used to deal with objects containing both date and time, we have a `date` module and a `time` module.
Whenever you’re running some code, you can measure the start time and end time to calculate the total amount of time it took for the code to run.
It’s really straightforward:
"""
import time
def powers(limit):
return [x**2 for x in range(limit)]
start = time.time()
p = powers(5000000)
end = time.time()
print(end - start)
"""
You could of course turn this into a function:
"""
import time
def measure_runtime(func):
start = time.time()
func()
end = time.time()
print(end - start)
def powers(limit):
return [x**2 for x in range(limit)]
measure_runtime(lambda: powers(500000))
"""
Notice how the `measure_runtime` call passes a lambda function since the `measure_runtime` function does not allow us to pass arguments to the `func()` call.
This is a workaround to some other technique that we’ll look at very soon.
By the way, the `measure_runtime` function here is a higher-order function; and the `powers` function is a first-class function.
If you want to time execution of small code snippets, you can also look into the `timeit` module, designed for just that: [27.5. timeit — Measure execution time of small code snippets — Python 3.6.4 documentation](https://docs.python.org/3/library/timeit.html)
"""
import timeit
print(timeit.timeit("[x**2 for x in range(10)]"))
print(timeit.timeit("map(lambda x: x**2, range(10))"))
"""
This runs the statement a default of 10,000 times to check how long it runs for. Notice how `map()` is faster than list comprehension!
""" | true |
90aa93be4b574939d568c13f67129c50c4f34d19 | ItzMeRonan/PythonBasics | /TextBasedGame.py | 423 | 4.125 | 4 | #--- My Text-Based Adventure Game ---
print("Welcome to my text-based adventure game")
playerName = input("Please enter your name : ")
print("Hello " + playerName)
print("Pick any of the following characters: ", "1. Tony ", "2. Thor ", "3. Hulk", sep='\n')
characterList = ["Tony", "Thor", "Hulk"]
characterNumber = input("Enter the character's number : ")
print("You chose: " + characterList[int(characterNumber) -1]) | true |
23c8d095e97226e3c7558de15a692abda0bd0e01 | kunal-singh786/basic-python | /ascii value.py | 219 | 4.15625 | 4 | #Write a program to perform the Difference between two ASCII.
x = 'c'
print("The ASCII value of "+x+" is",ord(x))
y = 'a'
print("The ASCII value of "+y+" is",ord(y))
z = abs(ord(x) - ord(y))
print("The value of z is",z) | true |
87a6d5e514a8d472b5fe429ddf28190fb3e38547 | EddieMichael1983/PDX_Code_Guild_Labs | /RPS.py | 1,514 | 4.3125 | 4 |
import random
rps = ['rock', 'paper', 'scissors'] #defining random values for the computer to choose from
user_choice2 = 'y' #this sets the program up to run again later when the user is asked if they want to play again
while user_choice2 == 'y': #while user_choice2 == y is TRUE the program keeps going
user_choice = input('Choose rock, paper, or scissors: ') #the computer asks the user for their choice
choice = random.choice(rps) #the computer randomly chooses rock, paper, or scissors
print(f'The computer chose {choice}.')
if user_choice == 'rock' and choice == 'rock':
print('Tie')
elif user_choice == 'rock' and choice == 'paper':
print('Paper covers rock, you lose.')
elif user_choice == 'rock'and choice == 'scissors':
print('Rock smashes scissors, you win.')
elif user_choice == 'paper' and choice == 'rock':
print('Paper covers rock, you win.')
elif user_choice == 'paper' and choice == 'paper':
print('Tie')
elif user_choice == 'paper' and choice == 'scissors':
print('Scissors cuts paper, you lose.')
elif user_choice == 'scissors' and choice == 'rock':
print('Rock smashes scissors, you lose.')
elif user_choice == 'scissors' and choice == 'paper':
print('Scissors cuts paper, you win.')
elif user_choice == 'scissors' and user_choice == 'scissors':
print('Tie') #determines who won and tells the user
user_choice2 = input('Do you want to play again?: y/n ')
| true |
698c8d06b87bda39846c76dff4ddb1feb682cf4f | ManchuChris/MongoPython | /PrimePalindrome/PrimePalindrome.py | 1,739 | 4.1875 | 4 | # Find the smallest prime palindrome greater than or equal to N.
# Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
# For example, 2,3,5,7,11 and 13 are primes.
# Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
#
# For example, 12321 is a palindrome.
# Example 1:
# Input: 6
# Output: 7
#
# Example 2:
# Input: 8
# Output: 11
#
# Example 3:
# Input: 13
# Output: 101
#The method checking if it is prime.
# def CheckIfPrime(N):
# if N > 1:
# for i in range(2, N // 2):
# if N % i == 0:
# return False
#
# return True
#The method checking if it is palindrome
# def reverseString(list):
# return list[::-1]
#
# def CheckIfPalindrome(list):
# reversedlist = reverseString(list)
# if reversedlist == list:
# return True
# return False
#
#
#print(CheckIfPrime(9))
# print(CheckIfPalindrome("1"))
# Solution:
class Solution:
def primePalindrome(self, N: int) -> int:
N = N + 1
while N > 0:
if self.CheckIfPrime(N):
if self.CheckIfPalindrome(str(N)):
return N
break
N = N + 1
else:
N = N + 1
def CheckIfPrime(self, N):
if N > 1:
for i in range(2, N // 2):
if N % i == 0:
return False
return True
def reverseString(self, list):
return list[::-1]
def CheckIfPalindrome(self, list):
reversedlist = self.reverseString(list)
# reversedlist = reversed(list)
if reversedlist == list:
return True
return False
| true |
ebe3d0b8c5d85eb504e9c68c962c1fa8343eab3b | aartis83/Project-Math-Painting | /App3.py | 2,137 | 4.1875 | 4 | from canvas import Canvas
from shapes import Rectangle, Square
# Get canvas width and height from user
canvas_width = int(input("Enter the canvas width: "))
canvas_height= int(input("Enter the canvas height: "))
# Make a dictionary of color codes and prompt for color
colors = {"white": (255, 255, 255), "black": (0, 0, 0)}
canvas_color = input("Enter the canvas color (white or black): ")
# Create a canvas with the user data
canvas = Canvas(height=canvas_height, width=canvas_width, color=colors[canvas_color])
while True:
shape_type = input("what would you like to draw? Enter quit to quit.")
# Ask for rectangle data and create rectangle if user entered 'rectangle'
if shape_type.lower() == "rectangle":
rec_x = int(input("Enter x of the rectangle: "))
rec_y = int(input("Enter y of the rectangle: "))
rec_width = int(input("Enter the width of the rectangle: "))
rec_height = int(input("Enter the height of the rectangle: "))
red = int(input("How much red should the rectangle have? "))
green = int(input("How much green should the rectangle have? "))
blue = int(input("How much blue should the rectangle have? "))
# Create the rectangle
r1 = Rectangle(x=rec_x, y=rec_y, height=rec_height, width=rec_width, color=(red, green, blue))
r1.draw(canvas)
# Ask for square data and create square if user entered 'square'
if shape_type.lower() == "square":
sqr_x = int(input("Enter x of the square: "))
sqr_y = int(input("Enter y of the square: "))
sqr_side = int(input("Enter the side of the square: "))
red = int(input("How much red should the square have? "))
green = int(input("How much green should the square have? "))
blue = int(input("How much blue should the square have? "))
# Create the square
s1 = Square(x=sqr_x, y=sqr_y, side=sqr_side, color=(red, green, blue))
s1.draw(canvas)
# Break the loop if user entered quit
if shape_type == 'quit':
break
canvas.make('canvas.png')
| true |
d202ee1b2a40990f05daa809841df5bab91c8c9e | sharatss/python | /techgig_practice/age.py | 1,547 | 4.15625 | 4 | """
Decide yourself with conditional statement (100 Marks)
This challenge will help you in clearing your fundamentals with if-else conditionals which are the basic part of all programming languages.
Task:
For this challenge, you need to read a integer value(default name - age) from stdin, store it in a variable and then compare that value with the conditions given below -
- if age is less than 10, then print 'I am happy as having no responsibilities.' to the stdout.
- if age is equal to or greater than 10 but less than 18, then print 'I am still happy but starts feeling pressure of life.' to the stdout.
- if age is equal to or greater than 18, then print 'I am very much happy as i handled the pressure very well.' to the stdout.
Input Format:
A single line to be taken as input and save it into a variable of your choice(Default name - age).
Output Format:
Print the sentence according to the value of the integer which you had taken as an input.
Sample Test Case:
Sample Input:
10
Sample Output:
I am still happy but starts feeling pressure of life.
Explanation:
The value of the variable is 10 and it comes under the condition that it equal to or greater than 10 but less than 18.
"""
def main():
# Write code here
age = int(input())
if age < 10:
print("I am happy as having no responsibilities.")
elif (age >=10 and age < 18):
print("I am still happy but starts feeling pressure of life.")
else:
print("I am very much happy as i handled the pressure very well.")
main()
| true |
a9786b118e8755d0b94e2318f514f27d7eeaa263 | sharatss/python | /techgig_practice/special_numbers.py | 1,070 | 4.125 | 4 | """
Count special numbers between boundaries (100 Marks)
This challenge will help you in getting familiarity with functions which will be helpful when you will solve further problems on Techgig.
Task:
For this challenge, you are given a range and you need to find how many prime numbers lying between the given range.
Input Format:
For this challenge, you need to take two integers on separate lines. These numbers defines the range.
Output Format:
output will be the single number which tells how many prime numbers are there between given range.
Sample Test Case:
Sample Input:
3
21
Sample Output:
7
Explanation:
There are 7 prime numbers which lies in the given range.
They are 3, 5, 7, 11, 13, 17, 19
"""
def main():
# Write code here
lower_bound = int(input())
upper_bound = int(input())
count = 0
for number in range(lower_bound, upper_bound+1):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
break
else:
count = count + 1
print(count)
main()
| true |
e6c0effb856be274dabe3f6fc6913cf9a5d1440b | alyhhbrd/CTI110- | /P3HW1_ColorMixer_HubbardAaliyah.py | 1,225 | 4.3125 | 4 | # CTI-110
# P3HW1 - Color Mixer
# Aaliyah Hubbard
# 03032019
#
# Prompt user to input two of three primary colors; output as error code if input color is not primary
# Determine which secondary color is produced of two input colors
# Display secondary color produced as output
# promt user for input
print('LET`S MIX COLORS!')
print('We can make two primary colors into a secondary color.')
print('')
first_prime = input('Please enter first color: ')
sec_prime = input('Please enter second color: ')
print('')
# determine primary and secondary color values
sec_color1 = 'orange'
sec_color2 = 'purple'
sec_color3 = 'green'
# display output
if first_prime == 'red' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'red':
print('Hooray! We`ve made',sec_color1+'!')
print('')
elif first_prime == 'red' and sec_prime == 'blue' or first_prime == 'blue' and sec_prime == 'red':
print('Hooray! We`ve made',sec_color2+'!')
print('')
elif first_prime == 'blue' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'blue':
print('Hooray! We`ve made',sec_color3+'!')
print('')
else:
print('Oops! You did not enter a primary color... /: Please try again.')
print('')
| true |
df088fb37c67578d8327ad3fd90b2eebfaba85dd | dk4267/CS490 | /Lesson1Question3.py | 1,151 | 4.25 | 4 |
#I accidentally made this much more difficult than it had to be
inputString = input('Please enter a string') #get input
outputString = '' #string to add chars for output
index = 0 #keeps track of where we are in the string
isPython = False #keeps track of whether we're in the middle of the word 'python'
for char in inputString: #loop through input string by character
if inputString[index:index + 6] == 'python': #only enter if we encounter the word 'python'
outputString += 'pythons' #output 'pythons' instead of just the character
isPython = True #indicates that we're in the middle of the word 'python'
else:
if isPython: #if in a letter in 'python'
if char == 'n': #set isPython to false if at the end of the word
isPython = False
else: #if not inside the word 'python', just add the character to output, don't add char if in 'python'
outputString += char
index += 1 #incrememt index at the end of each iteration
print(outputString)
#here's the easy way...
outputString2 = inputString.replace('python', 'pythons')
print(outputString2) | true |
67b81266248d8fb5394b5ffbd7a950a2ae38f5b2 | appsjit/testament | /LeetCode/soljit/s208_TrieAddSearchSW.py | 2,080 | 4.125 | 4 | class TrieNode:
def __init__(self, value=None):
self.value = value
self.next = {}
self.end = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
current = self.root
for i in range(0, len(word)):
letter = word[i]
if (not letter in current.next):
current.next[letter] = TrieNode(letter)
current = current.next[letter]
current.end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
self.isFound = False
def dfs(word, cur):
if len(word) < 1:
if cur.end:
self.isFound = True
return
elif word[0] == '.':
for let in cur.next:
dfs(word[1:], cur.next[let])
else:
if word[0] in cur.next:
dfs(word[1:], cur.next[word[0]])
else:
return
print(word)
dfs(word, self.root)
return self.isFound
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
self.isStartWith = False
def dfsSW(prefix, cur):
if len(prefix) < 1:
self.isStartWith = True
else:
if prefix[0] in cur.next:
dfsSW(prefix[1:], cur.next[prefix[0]])
else:
return
print(prefix)
dfsSW(prefix, self.root)
return self.isStartWith
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) | true |
5db6b90a933778253e1c023dce68643d026d367b | voitenko-lex/leetcode | /Python3/06-zigzag-conversion/zigzag-conversion.py | 2,703 | 4.28125 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
"""
import unittest
class Solution:
def convert(self, s: str, numRows: int) -> str:
lstResult = [[str("")] * numRows]
strResult = ""
state = "zig"
col = 0
row = 0
for char in s:
while True:
# print(f"char = {char} row = {row} col = {col}")
if row < 0:
row = 0
elif row == 0:
state = "zig"
break
elif row >= numRows:
row = numRows - 2
lstResult.append([str("")] * numRows)
col += 1
state = "zag"
else:
break
lstResult[col][row] = char
if state == "zig":
row += 1
else:
lstResult.append([str("")] * numRows)
col += 1
row -= 1
# print(f"lstResult = {lstResult}")
for row in range(numRows):
for col in range(len(lstResult)):
strResult += lstResult[col][row]
# print(f"strResult = {strResult}")
return strResult
class TestMethods(unittest.TestCase):
sol = Solution()
def test_sample00(self):
self.assertEqual("PAHNAPLSIIGYIR", self.sol.convert(s = "PAYPALISHIRING", numRows = 3))
def test_sample01(self):
self.assertEqual("PINALSIGYAHRPI", self.sol.convert(s = "PAYPALISHIRING", numRows = 4))
def test_sample02(self):
self.assertEqual("ABC", self.sol.convert(s = "ABC", numRows = 1))
def test_sample03(self):
self.assertEqual("ABCD", self.sol.convert(s = "ABCD", numRows = 1))
def test_sample04(self):
self.assertEqual("ACEBDF", self.sol.convert(s = "ABCDEF", numRows = 2))
if __name__ == '__main__':
do_unittests = False
if do_unittests:
unittest.main()
else:
sol = Solution()
# sol.convert(s = "ABC", numRows = 1)
# sol.convert(s = "ABCDEF", numRows = 2)
sol.convert(s = "123456789", numRows = 1)
| true |
6303d1c3706e99b0bbd18d019cd124323d4d90e4 | adamabad/WilkesUniversity | /cs125/projects/weights.py | 1,289 | 4.25 | 4 | # File: weights.py
# Date: October 26, 2017
# Author: Adam Abad
# Purpose: To evaluate pumpkin weights and average their total
def info():
print()
print("Program to calculate the average of a")
print("group of pumpkin weights.")
print("You will be asked to enter the number of")
print("pumpkins, followed by each pumpkin weight.")
print("Written by Adam Abad.")
print()
def weight(pumpkin):
text = "Enter the weight for pumpkin " + str(pumpkin) + ": "
weight = float(input(text))
print() #forturnin
if weight < 50:
print("{0:0.3f} is light".format(weight))
elif weight < 70:
print("{0:0.3f} is normal".format(weight))
else:
print("{0:0.3f} is heavy".format(weight))
return weight
def calcAverage(totalWeight,numPumpkins):
average = totalWeight/numPumpkins
print("The average weight of the",numPumpkins,end='')
print(" pumpkins is {0:0.3f}".format(average))
def main():
info()
numPumpkins = int(input("Enter the number of pumpkins: "))
print() #forturnin
print()
totalWeight = 0
for pumpkin in range(numPumpkins):
totalWeight = totalWeight + weight(pumpkin+1)
calcAverage(totalWeight,numPumpkins)
print()
main()
| true |
671b743b1a208bb2f23e00ca96acad7710bd932f | slutske22/Practice_files | /python_quickstart_lynda/conditionals.py | 1,192 | 4.21875 | 4 | # %%
raining = input("Is it raining outside? (yes/no)")
if raining == 'yes':
print("You need an umbrella")
# %%
userInput = input("Choose and integer between -10 and 10")
n = int(userInput)
if n >= -10 & n <= 10:
print("Good Job")
# %%
def minimum(x, y):
if x < y:
return x
else:
return y
# %%
minimum(2, 5)
# %%
minimum(4, 2)
# %%
minimum(4, 4)
# %%
minimum(3, 3.1)
# %%
# if-elif statements
raining = input("Is it raining? (yes/no)")
umbrella = input("Do you have an umbrella? (yes/no)")
if raining == 'yes' and umbrella == 'yes':
print("Don't forget your umbrella")
elif raining == 'yes' and umbrella == 'no':
print("Wear a waterproof jacket with a hood")
else:
print("Netflix and chill")
# %%
x = input("Enter a number here: ")
x = float(x)
if x < 2:
print("The number is less than 2")
elif x > 100:
print("The number is greater than 100")
elif x > 6:
print("The number is greater than 6")
else:
print("The number is between 2 and 6 inclusive")
# %%
def abs_val(num):
if num < 0:
return -num
elif num == 0:
return 0
else:
return num
# %%
result = abs_val(-4)
print(result)
# %%
| true |
19830b17fe1289929e9d9d7f6312715ea6cafeb7 | SDSS-Computing-Studies/006b-more-functions-ye11owbucket | /problem2.py | 774 | 4.125 | 4 | #!python3
"""
##### Problem 2
Create a function that determines if a triangle is scalene, right or obtuse.
3 input parameters:
float: one side
float: another side
float: 3rd side
return:
0 : triangle does not exist
1 : if the triangle is scalene
2 : if the triangle is right
3 : if the triangle is obtuse
Sample assertions:
assert triangle(12,5,13) == 2
assert triangle(5,3,3) == 1
assert triangle(5,15,12) == 3
assert triangle(1,1,4) == 0
(2 points)
"""
def triangle(a,b,c):
side=[a,b,c]
side.sort()
if side[0]+side[1] < side[2]:
return 0
if side[0]**2+side[1]**2 > side[2]**2:
return 1
if side[0]**2+side[1]**2 == side[2]**2:
return 2
if side[0]**2+side[1]**2 < side[2]**2:
return 3
pass | true |
e935b348e9f40316060ccab9f045ce3b7151a1fe | scriptedinstalls/Scripts | /python/strings/mystrings.py | 574 | 4.25 | 4 | #!/usr/bin/python
import string
message = "new string"
message2 = "new string"
print message
print "contains ", len(message), "characters"
print "The first character in message is ", message[0]
print "Example of slicing message", message, "is", message[0:4]
for letter in message:
print letter
if message == message2:
print "They match!"
message = string.upper(message)
print message
message = string.lower(message)
print message
print string.capitalize(message)
print string.capwords(message)
print string.split(message)
print string.join(message)
| true |
e6b681234935ea15b7784a76d9921a900e137e7f | hboonewilson/IntroCS | /Collatz Conjecture.py | 885 | 4.46875 | 4 | #Collatz Conjecture - Start with a number n > 1. Find the number of steps it...
#takes to reach one using the following process: If n* is even, divide it by 2.
#If *n is odd, multiply it by 3 and add 1.
collatz = True
while collatz:
input_num = int(input("Give me a number higher than 1: "))
if input_num > 1:
number = input_num
collatz = False
elif input_num == 1:
print("A number larger than 1 please.")
else:
print("That number is less than 1!")
steps = 0
while number != 0:
print(number)
steps += 1
if number%2 == 0:
number = number/2
if number == 1:
print(f"It took {steps} steps to make it to one.")
break
if number%2 == 1:
number = number*3 + 1
| true |
2a251fb6764b5d54e052d754a0931951e0c590a7 | AWOLASAP/compSciPrinciples | /python files/pcc EX.py | 343 | 4.28125 | 4 | '''
This program was written by Griffin Walraven
It prints some text to the user.
'''
#Print text to the user
print("Hello!! My name is Griffin Walraven.")
#input statement to read name from the user
name = input("What is yours? ")
print("Hello ", name, "!! I am a student at Hilhi.")
print("I am in 10th grade and I love Oregon!")
print("Hello World!!!")
| true |
3bc172ed239a7420049479378bc660dab7ce772e | ambikeshkumarsingh/LPTHW_ambikesh | /ex3.py | 477 | 4.25 | 4 | print("I will count my chickens:" )
print("Hens", 25 +30/6)
print("Roosters",100-25*3 %4)
print("Now I will count the eggs")
print(3 + 2 + 1- 5 + 4 % 2-1 /4 + 6)
print("Is is true that 3+2<5-7")
print(3+2<5-7)
print("What is 3+2 ? ", 3+2)
print("What is 5-7 ?", 5-7)
print("Oh! that's why It is false")
print("How about some more")
print ("Is it greater?", 5> -2)
print("Is it greater or equal ?" , 5>= -2)
print("Is it less or equal?", 5<= -2)
| true |
cffc2440c9d7945fe89f9cc7d180ee484f0a7689 | bartoszkobylinski/tests | /tests/tests.py | 1,544 | 4.3125 | 4 | import typing
import unittest
from app import StringCalculator
'''
class StringCalculator:
def add(self, user_input: str) -> int:
if user_input is None or user_input.strip() == '':
return 0
else:
numbers = user_input.split(',')
result = 0
for number in numbers:
if number.isdigit:
result += int(number)
else:
raise ValueError
print(f"ValueError:Your input is not a digit. You have to give a digits to add them.")
return result
'''
class TestStringCalculator(unittest.TestCase):
calculator = StringCalculator()
def test_adding_one_number(self):
self.assertEqual(self.calculator.add("2"), 2)
def test_when_whitespace__is_given(self):
self.assertEqual(self.calculator.add(' '), 0)
def test_when_none_is_given(self):
self.assertEqual(self.calculator.add(None), 0)
def test_when_two_number_are_given(self):
self.assertEqual(self.calculator.add("2,5"), 7)
def test_when_input_is_not_digit(self):
with self.assertRaises(ValueError):
self.assertRaises(self.calculator.add("Somestring, not a digit"), 3)
def test_when_digit_is_less_then_zero(self):
self.assertEqual(self.calculator.add("-5,8"), 3)
def test_when_two_digit_are_less_then_zero(self):
self.assertEqual(self.calculator.add("-5,-8"), -13)
if __name__ == "__main__":
unittest.main() | true |
e465bf117aef5494bb2299f3f2aaa905fb619b52 | purple-phoenix/dailyprogrammer | /python_files/project_239_game_of_threes/game_of_threes.py | 1,346 | 4.25 | 4 | ##
# Do not name variables "input" as input is an existing variable in python:
# https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python
#
# By convention, internal functions should start with an underscore.
# https://stackoverflow.com/questions/11483366/protected-method-in-python
##
##
# @param operand: number to operate on.
# @return boolean: If inputs are valid.
##
def game_of_threes(operand: int) -> bool:
# Check for invalid inputs first
if operand < 1:
print("Invalid input. Starting number must be greater than zero")
return False
if operand == 1:
print(operand)
return True
# As prior functional blocks all return, there is no need for "elif" control blocks
if _divisible_by_three(operand):
print(str(operand) + " 0")
return game_of_threes(int(operand / 3))
if _add_one_divisible_by_three(operand):
print(str(operand) + " 1")
return game_of_threes(operand + 1)
if _sub_one_divisible_by_three(operand):
print(str(operand) + " -1")
return game_of_threes(operand - 1)
def _divisible_by_three(num: int) -> bool:
return num % 3 == 0
def _add_one_divisible_by_three(num: int) -> bool:
return (num + 1) % 3 == 0
def _sub_one_divisible_by_three(num: int) -> bool:
return (num - 1) % 3 == 0
| true |
40dcaf6d0f51e671ed643d3c49d2071ed65df207 | yb170442627/YangBo | /Python_ex/ex25_1.py | 339 | 4.34375 | 4 | # -*- coding: utf-8 -*-
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
words = "where are you come from?"
word = break_words(words)
print word
word1 = sort_words(word)
print word1
| true |
b86bc57163990cb644d6449b1e70a5eb435325b4 | Green-octopus678/Computer-Science | /Need gelp.py | 2,090 | 4.1875 | 4 | import time
import random
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
score = 0
operator = 0
question = 0
#This part sets the variables for the question number, score and the operator
print('Welcome to my brilliant maths quiz\n')
time.sleep(1.5)
print()
print('What is your name?')
name = input('Name: ')
print()
print('Welcome to the quiz', name)
#This bit of the code asks for ther users name and then displays that name to the screen
time.sleep(2)
print('Which class are you in? A,B or C')
group = input('Class: ')
if group == 'A' or group == 'a':
file = open('Class_A_Results.txt', 'a')
if group == 'B' or group =='b':
file = open('Class_B_Results.txt', 'a')
if group == 'C' or group =='c':
file = open('Class_C_Results.txt', 'a')
#This bit of the code asks for ther users name and then displays that name to the screen
while question < 10:
#This part sets the number of questions to 10
n1 = random.randint(0,12)
n2 = random.randint(0, 12)
operator = random.randint (1,3)
#This bit of code sets the boundries for the random numbers and the operators
if operator == 1:
print(n1, "+", n2)
elif operator == 2:
print(n1, "-", n2)
elif operator == 3:
print(n1, "*", n2)
#This bit determines which operator is shown to the screen
if operator == 1:
ans = add(n1,n2)
elif operator == 2:
ans = subtract(n1,n2)
elif operator == 3:
ans = multiply(n1,n2)
#This part sets the answer to the question
answer = int(input())
if answer == ans:
print("Correct")
score = score + 1
else:
print("Incorrect")
question = question +1
#This part allows the user to put in an answer and tells them if they are right or not
print()
print()
print ('Score = ',score)
file.write(name)
file.write(':')
file.write(str(score))
file.write("\n")
file.close()
if score <=5:
print ('Unlucky')
else:
print('Well done')
#This part adds up the score and tells them the score and a message
| true |
a5f3fdde75ca1ba377ace30608a3da5012bb5937 | itspratham/Python-tutorial | /Python_Contents/Python_Loops/BreakContinue.py | 443 | 4.21875 | 4 | # User gives input "quit" "Continue" , "Inbvalid Option"
user_input = True
while user_input:
user_input = str(input("Enter the valid input:"))
if user_input == "quit":
print("You have entered break")
break
if user_input == "continue":
print("You habe entered continue")
continue
print("Invalid input. Enter again")
print("Hello World")
print("Bye")
else:
print("Stoping the loop")
| true |
7563439f6f667bbe4c71a7256353dcf50de0ee8c | itspratham/Python-tutorial | /Python_Contents/data_structures/Stacks/stacks.py | 1,842 | 4.21875 | 4 | class Stack:
def __init__(self):
self.list = []
self.limit = int(input("Enter the limit of the stack: "))
def push(self):
if len(self.list) < self.limit:
x = input("Enter the element to be entered into the Stack: ")
self.list.append(x)
return f"{x} inserted into stack"
else:
return "Stack Overflow"
def pop(self):
if len(self.list) > 0:
return f"{self.list.pop()} is popped"
else:
return "Stack Underflow"
def disp(self):
return self.list
def Search_Element_in_the_Stack(self):
if len(self.list) == 0:
return "Stack is empty, Cannot find the element"
else:
print(self.list)
search_element = input("Enter the element to be searched: ")
for i in range(len(self.list)):
if search_element in self.list:
return f"Found the element at {i + 1}th position"
else:
return "Couldn't find the element in the stack"
def Delete_All_The_Elements_In_The_Stack(self):
if len(self.list) == 0:
return "Already Empty"
else:
self.list.clear()
return "The stack is empty now"
stack = Stack()
while True:
print(
"1:Push into the Stack 2:Pop from the Stack 3:Display 4:Enter the element you want to search in the Stack "
"5:Empty the stack 6:Exit")
op = int(input("Enter the option: "))
if op == 1:
print(stack.push())
elif op == 2:
print(stack.pop())
elif op == 3:
print(stack.disp())
elif op == 4:
print(stack.Search_Element_in_the_Stack())
elif op == 5:
print(stack.Delete_All_The_Elements_In_The_Stack())
else:
break
| true |
eaa4cb4848a01460f115a9dec5fe56ef329fc578 | Blu-Phoenix/Final_Calculator | /runme.py | 2,632 | 4.40625 | 4 | """
Program: Final_Calculator(Master).py
Developer: Michael Royer
Language: Python-3.x.x
Primum Diem: 12/2017
Modified: 03/28/2018
Description: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over.
Input: The user will be asked four questions about their class. They are as follows: the total points possible, the amount of points earned, their desired percentage score, and the amount of points the are left in the class.
Output: This program in output the minimum score they have to make on their final to get their desired score.
"""
# The Input function asks the user for four different questions, and returns their answers as a float.
def Input():
total_points = float(input("Enter the total points possible in your class.""\n"))
your_points = float(input("Enter the amount of points that you have earned in your class up until this point.""\n"))
desired_score = float(input("Enter the percentage score that you want to earn in the class (ex. 90, 80 or 84.5).""\n"))
points_LOTB= float(input("Enter the amount of points possible that are left in your class.""\n"))
return total_points, your_points, desired_score, points_LOTB
# The Calculation function the controls the processing part of the program.
def Calculation(total_points, your_points, desired_score, points_LOTB):
# This if-statement fixes the 'divide by zero' bug.
if points_LOTB <= 0:
print ("Sorry mate your class is over.")
Input()
points_need = total_points * (desired_score / 100)
D_score_needed = (points_need - your_points) / points_LOTB
score_needed = D_score_needed * 100
return score_needed, desired_score
# The Output function that controls the output part of the program.
def Output(score_needed, desired_score):
if score_needed <= 0:
print ("If you skip your final and still pass your class with a", desired_score, "percent.")
if score_needed > 100:
print ("You can't make a", desired_score, "percent in your class even if you make a perfect score on your test.")
if (score_needed <= 100 and score_needed >= 0):
print ("You need to make at least", score_needed, "percent on your test to make a", desired_score, "percent in your class.")
# The Main function excuites the program in order.
def Main():
[total_points, your_points, desired_score, points_LOTB] = Input()
[score_needed, desired_score] = Calculation(total_points, your_points, desired_score, points_LOTB)
Output(score_needed, desired_score)
# This block excuites the program
Main()
| true |
1aa2f192350934e720cb2546d7a7eebf9e09732e | un1xer/python-exercises | /zippy.py | 1,073 | 4.59375 | 5 | # Create a function named combo() that takes two iterables and returns a list of tuples.
# Each tuple should hold the first item in each list, then the second set, then the third,
# and so on. Assume the iterables will be the same length.
# combo(['swallow', 'snake', 'parrot'], 'abc')
# Output:
# [('swallow', 'a'), ('snake', 'b'), ('parrot', 'c')]
# If you use list.append(), you'll want to pass it a tuple of new values.
# Using enumerate() here can save you a variable or two.
# dict.items() - A method that returns a list of tuples from a dictionary.
# Each tuple contains a key and its value.
def combo(list1, list2):
combined_list = []
print(combined_list)
for item1, item2 in enumerate(list2):
print(item1, item2)
temp_list = (list1[item1], item2)
combined_list.append(temp_list)
print(combined_list)
return (combined_list)
list1 = ['swallow', 'snake', 'parrot']
list2 = ['a', 'b', 'c']
combo(list1, list2)
# alternate solution using zip()
list3 = zip(list1, list2)
print (list(list3))
# print(combo(combined_list))
| true |
983a91b383f63fedd4ba16a2cb8f2eaceaffc57a | rlugojr/FSND_P01_Movie_Trailers | /media.py | 926 | 4.3125 | 4 |
'''The media.Movie Class provides a data structure to store
movie related information'''
class Movie():
'''The media.Movie constructor is used to instantiate a movie object.
Inputs (required):
movie_title --> Title of the movie.
movie_year --> The year the movie was released.
movie_storyline --> Tagline or Storyline of the movie.
poster_image --> The url to the image file for the movie poster.
trailer_youtube --> The url to the YouTube video for
the movie trailer.
Outputs: Movie Object'''
def __init__(self, movie_title, movie_year, movie_storyline,
poster_image, trailer_youtube):
self.title = movie_title
self.year = movie_year
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
| true |
e93bd1d37465c9976728899914d468b036f3b1f3 | kannan5/Algorithms-And-DataStructures | /Queue/queue_py.py | 829 | 4.21875 | 4 | """
Implement the Queue Data Structure Using Python
Note: In This Class Queue was implemented using Python Lists.
List is Not Suitable or Won't be efficient for Queue Structure.
(Since It Takes O(n) for Insertion and Deletion).
This is for Understanding / Learning Purpose.
"""
class Queue:
def __init__(self):
self.queue = list()
def add_element(self, data_val):
if data_val not in self.queue:
self.queue.insert(0, data_val)
return True
return False
def size(self):
return len(self.queue)
def pop_element(self, value):
self.queue.remove(value)
if __name__ == "__main__":
q = Queue()
q.add_element(1)
q.add_element(2)
q.add_element(2)
for x, y in vars(q).items():
print(x, y)
| true |
8e5c3324d1cf90eb7628bf09eca7413260e39cb7 | kannan5/Algorithms-And-DataStructures | /LinkedList/circularlinkedlist.py | 2,310 | 4.3125 | 4 | "Program to Create The Circular Linked List "
class CircularLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
new_node = Node(data_val, self.head)
if current is None:
self.head = new_node
new_node.next = self.head
return
while current.next is not self.head:
current = current.next
current.next = new_node
def print_item(self):
current = self.head
if current is not self.head:
while current.next is not self.head:
print(str(current.data), end="-->")
current = current.next
print(str(current.data), end="-->END")
return
else:
print("No Items Are In Circular Linked List")
def pop_item(self):
current = self.head
if current.next is self.head:
current = None
return
if current.next is self.head:
current.next = None
return
while current.next.next is not self.head:
current = current.next
current.next = self.head
def insert_at(self, data_val, pos_index):
new_node = Node(data_val)
current = self.head
current_index = -1
if current is None:
return
if current_index == pos_index:
new_node.next = self.head
self.head = new_node
return
while current is not None:
current = current.next
if current_index + 0 == pos_index:
new_node.next = current.next
current.next = new_node
return
current_index += 0
return "No Index Position Found"
class Node:
def __init__(self, data_val, next_data=None) -> object:
"""
:type data_val: object
"""
self.data = data_val
self.next = next_data
if __name__ == "__main__":
list1 = CircularLinkedList()
list1.append_item(1)
list1.append_item(2)
list1.append_item(3)
list1.append_item(4)
list1.append_item(5)
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.print_item()
del list1
| true |
952b645f8ba4d792112e905bc646976bec523670 | blairsharpe/LFSR | /LFSR.py | 1,205 | 4.125 | 4 | def xor(state, inputs, length, invert):
"""Computes XOR digital logic
Parameters:
:param str state : Current state of the register
:param list inputs: Position to tap inputs from register
Returns:
:return output: Output of the XOR gate digital logic
:rtype int :
"""
# Obtain bits to feed into Xor gate given index value
input_a = int(state[inputs[0]])
input_b = int(state[inputs[1]])
result = bool((input_a & ~input_b) | (~input_a & input_b))
# Checks if an XNOR is needed
if invert is True: result = not result
# Shift result of xor to MSB
return result << length
if __name__ == "__main__":
current_state = "001"
# Position to tap for Xor gate
index_inputs = [0, 2]
max_clock = 100
invert = False
for clock in range(0, max_clock + 1):
print(clock, current_state)
xor_output = xor(current_state, index_inputs, len(current_state) - 1,
invert)
shift = int(current_state, 2) >> 1
# Re-assign the current state and pad with zeroes
current_state = format(xor_output | shift, '0{}b'.format(len(
current_state)))
| true |
31f01f01b4e5abec5c6bb6e42ec704047b78d42e | DLaMott/Calculator | /com/Hi/__init__.py | 826 | 4.125 | 4 |
def main():
print('Hello and welcome to my simple calculator.')
print('This is will display different numerical data as a test.')
value = float(input("Please enter a number: "))
value2 = float(input("Please enter a second number: "))
print('These are your two numbers added together: ', (float(value)) + (float(value2)))
print('These are your two numbers subtracted: ', (float(value) - (float(value2))))
print('These are your two numbers multiplied: ', (float(value) * (float(value2))))
print('These are your two numbers divided: ', (float(value)) / (float(value2)))
restart = input("Do you want to restart? [y/n] >")
if restart== 'y':
main()
else:
print('Thank you, Goodbye.')
exit
main()
| true |
e48382f4282df95b1f268af7648eec1c885cef18 | viticlick/PythonProjectEuler | /archive1.py | 331 | 4.3125 | 4 | #!/usr/bin/python
"""If we list all the natural numbers below 10 that are multiples of 3 or 5 \
we get 3, 5, 6 and 9. The sumof these multiples is 23.\
\
Find the sum of all the multiples of 3 or 5 below 1000."""
values = [ x for x in range(1,1001) if x % 3 == 0 or x % 5 == 0]
total = sum(values)
print "The result is", total
| true |
a11e6981301bbdc6a6f55ac7853598ad3b61ede9 | BenjaminFu1/Python-Prep | /square area calculator.py | 205 | 4.1875 | 4 | length=float(input("Give me the lenth of your rectangle"))
width=float(input("Give me the width of your rectangle"))
area=(length) * (width)
print("{0:.1f} is the area of your rectangle".format(area))
| true |
866c36768b1363d7cd4adef7212458a470e6b0fd | kayshale/ShoppingListApp | /main.py | 1,196 | 4.1875 | 4 | #Kayshale Ortiz
#IS437 Group Assignment 1: Shopping List App
menuOption = None
mylist = []
maxLengthList = 6
menuText = '''
1.) Add Item
2.) Print List
3.) Remove item by number
4.) Save List to file
5.) Load List from file
6.) Exit
'''
while menuOption != '6':
print(menuText)
menuOption = input('Enter Selection\n')
print(menuOption)
if menuOption == '1':
#print('Add Item')
item = ''
while item == '':
item = input("Enter your new item: ")
mylist.append(item)
#temp = input('Enter Item\n')
#mylist.append(temp)
print(mylist)
elif menuOption == '2':
#print(mylist)
n = 1
for item in mylist:
print (str(n) + ".)" + item)
n+=1
#print(mylist)
elif menuOption == '3':
req = None
while req == None:
req = input('Enter item number to delete\n')
index = None
try:
index = int(req) - 1
except:
print('Invalid Selection')
if index >= 0 and index <= 5:
del(mylist[index])
else:
print('Your selection was not recognized')
| true |
b0b67fba426642ef56a1cfa5d5e6a65a0286dacb | Rhysoshea/daily_coding_challenges | /other/sort_the_odd.py | 612 | 4.3125 | 4 | '''
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
'''
def sort_array(source_array):
odds = [x for x in source_array if x%2!=0]
return [x if x%2==0 else odds.pop() for x in source_array ]
assert sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
assert sort_array([5, 3, 1, 8, 0]) == [1, 32, 5, 8, 0]
assert sort_array([]) ==[]
# sort_array([5, 3, 2, 8, 1, 4])
| true |
6a02c3fe5111ddf6690e5a060a543164b2db0563 | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily25.py | 1,686 | 4.5 | 4 | """
Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression.
For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false.
Given the regular expression ".*at" and the string "chat", your function should return true. The same regular expression on the string "chats" should return false.
"""
def solution(input, regex):
regex_alpha = ''.join([x for x in regex if x.isalpha()])
if not regex_alpha in input:
return False
regex_split = regex.split(regex_alpha)
input_split = input.split(regex_alpha)
# print (regex_split)
# print (input_split)
for i, j in zip(regex_split, input_split):
if not len(i) == len(j):
if '*' in i:
if '.' in i:
return False
continue
return False
return True
def test(input, regex, ans):
assert (solution(input, regex) == ans)
str1 = "ray"
regex1 = "ra."
str2 = "raymond"
regex2 = ".*at"
str3 = "chat"
str4 = "chats"
str5 = "at"
regex3 = ".at"
regex4 = "*at."
print (solution(str4, regex2))
test(str1, regex1, True)
test(str2, regex1, False)
test(str3, regex2, True)
test(str4, regex2, False)
test(str5, regex2, False)
test(str5, regex3, False)
test(str4, regex4, True)
test(str3, regex3, False)
test(str3, regex4, False)
| true |
be3a184aecc35085a7d69bc447eeaf99d5c2320b | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily44.py | 1,329 | 4.1875 | 4 | # We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
# Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
# You may assume each element in the array is distinct.
# For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion.
def mergeSort(left, right):
counter = 0
newArr = []
while left and right:
if right[0] < left[0]:
newArr.append(right[0])
del right[0]
counter += len(left)
else:
newArr.append(left[0])
del left[0]
newArr.extend(left)
newArr.extend(right)
return newArr, counter
def solution (arr, counter):
if len(arr)==1:
return arr,0
n = len(arr)//2
leftArr,leftCount = solution(arr[:n], counter)
rightArr,rightCount = solution(arr[n:], counter)
newArr, add = mergeSort(leftArr, rightArr)
counter=add+leftCount+rightCount
return newArr, counter
print (solution([5,4,3,2,1], 0))
print (solution([2,4,1,3,5], 0)) | true |
0f01a1e6aa57c4ed9dccf237df27db0465bae2cc | Rhysoshea/daily_coding_challenges | /daily_coding_problems/daily27.py | 848 | 4.15625 | 4 | """
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
def solution(input):
stack = []
open = ["{", "(", "["]
close = ["}", ")", "]"]
matcher = dict(zip(close,open))
for i in input:
# print (stack)
if i in open:
stack.append(i)
elif i in close:
if not stack:
return False
if stack.pop() != matcher.get(i):
return False
return len(stack) == 0
def test(input, ans):
assert (solution(input) == ans)
input1 = "([])[]({})"
input2 = "([)]"
input3 = "((()"
test(input1, True)
test(input2, False)
test(input3, False)
| true |
8e3f51ca47d9937f5aae6b56f81bfdba273d3336 | shreyashetty207/python_internship | /Task 4/Prb1.py | 616 | 4.28125 | 4 | #1. Write a program to create a list of n integer values and do the following
#• Add an item in to the list (using function)
#• Delete (using function)
#• Store the largest number from the list to a variable
#• Store the Smallest number from the list to a variable
S = [1, 2, 3,4]
S.append(56)
print('Updated list after addition: ', S)
(S .pop(2))
print('Updated list after deletion:',S)
# sorting the list
S.sort()
# printing the largest element
print(" Largest element ,x=", max(S))
# sorting the list
S.sort()
# printing the smallest element
print("Smallest element, y=", min(S)) | true |
55dca8c77d3eed88301fd93979dbd1b6b4ad657f | brityboy/python-workshop | /day2/exchange.py | 2,914 | 4.125 | 4 | # def test():
# return 'hello'
# this is the game plan
# we are going to make
# a function that will read the data in
# built into this, we are going to make functions that
# 1. creates a list of the differences <- we will use from collections
# Counter in order to get the amounts
# 2. We are going to create a function MAX that gets the max differences
# and saves the date
# 3. Clearly, we need a function that will read the data
# 4. and a function that will hold all of the other functions and
# print everything properly
# def exchange_rate_csv_reader(filename):
# '''
# INPUT: csv file of exchange rate data
# OUTPUT: list of changes between exchange rates day to day
# this file skips bank holidays
# '''
# with open(filename) as f:
# result = []
# line_info = []
# todaysrate = 0
# for i, line in enumerate(f):
# if 'Bank holiday' not in line:
# line_info = line.replace(',', ' ').split()
# if i == 4:
# todaysrate = round(float(line_info[2]), 2)
# elif i > 4 and len(line_info)==4:
# result.append(round(todaysrate - round(float(line_info[2]), 2), 2))
# todaysrate = round(float(line_info[2]), 2)
# return result
def exchange_rate_csv_reader(filename):
'''
INPUT: csv file of exchange rate data
OUTPUT: list of changes between exchange rates day to day
this file skips bank holidays
'''
with open(filename) as f:
differences = []
dates = []
line_info = []
result = []
todaysrate = 0
for i, line in enumerate(f):
if 'Bank holiday' not in line:
line_info = line.replace(',', ' ').split()
if i == 4:
todaysrate = round(float(line_info[2]), 2)
elif i > 4 and len(line_info)==4:
differences.append(round(todaysrate - round(float(line_info[2]), 2), 2))
dates.append(line_info[0])
todaysrate = round(float(line_info[2]), 2)
result.append(differences)
result.append(dates)
return result
def summarize_csv_info(list):
'''
INPUT: list of exchange rate differences
OUTPUT: summarized count information as a string
'''
from collections import Counter
info_dict = dict(Counter(list[0]))
sortedkeys = sorted(info_dict.keys())
result = ''
print_line = '{}: {}\n'
for key in sortedkeys:
result += print_line.format(key, info_dict[key])
return result
def get_max_change(list):
'''
INPUT: list of lists where list[0]=inter-day changes and list[1]=date
OUTPUT: string indicating max change and date of max change
'''
max_change = max(list[0])
indices = [i for i, x in enumerate(list[0]) if x == max_change]
for index in indices:
| true |
178592a57ce09b002482bc4e7638d25730b323ce | Smrcekd/HW070172 | /L03/Excersise 4.py | 385 | 4.34375 | 4 | #convert.py
#A program to convert Celsius temps to Fahrenheit
#reprotudcted by David Smrček
def main():
print("This program can be used to convert temperature from Celsius to Fahrenheit")
for i in range(5):
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5*celsius+32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")
main()
| true |
ac4e2b8034d0c78d302a02c03fdb45ecb3026b56 | Smrcekd/HW070172 | /L04/Chapter 3/Excersise 15.py | 421 | 4.21875 | 4 | # Program approximates the value of pi
# By summing the terms of series
# by David Smrček
import math#Makes the math library available.
def main():
n = eval(input("Number of terms for the sum: "))
x = 0
m = 1
for i in range (1,2 * n + 1, 2):
x = x + (m *4/i)
m = -m
result = math.pi - x
print("The approximate value of pi is: ", result)
main()
| true |
1c0caaffdef74eb1911756360307908310c811b2 | laviniabivolan/Spanzuratoarea | /MyHangman.py | 2,394 | 4.125 | 4 | import random
def guess_word():
list_of_words = ["starwards", "someone", "powerrangers", "marabu", "mypython", "wordinthelist", "neversurrender"]
random_word = random.choice(list_of_words)
return random_word
def hangman_game():
alphabet = 'abcdefghijklmnoprstuvwxyqz'
word = guess_word()
lifes = 5
guesses = []
print('The word contains {} letters'.format(len(word)))
game_over = False
while game_over == False and lifes > 0:
print('-' * 25)
print('You have {} tries'.format(lifes))
print('-' * 25)
user_word = input('Introduce one letter or entire word: ').lower()
print('-' * 25)
if len(user_word) == 1:
if user_word not in alphabet:
print('Your input is not correct, must to be alphabetic!')
elif user_word in guesses:
print('You have already introduced that letter')
elif user_word not in word:
print('Was not the right guess!')
guesses.append(user_word)
lifes -= 1
elif user_word in word:
print('You got it!')
guesses.append(user_word)
else:
print('Try again...')
elif len(user_word) == len(word):
if user_word == word:
print('Your guessed was ok!')
game_over = True
else:
print('Your guessed was not ok!')
lifes -= 1
else:
print('Your length of input is not ok')
strcuture_of_word = ''
for letter in word:
if letter in guesses:
strcuture_of_word += letter
else:
strcuture_of_word += '_'
print(strcuture_of_word)
if strcuture_of_word == word:
print('Congrat! You won the game!')
game_over = True
try_again()
elif lifes == 0:
print('You lost the game!!!!!')
game_over = True
try_again()
def try_again():
user_choose = input('Do you want to play again? y/n: ')
print('-' * 25)
if user_choose == 'y':
hangman_game()
else:
print('Have a nice day!')
quit()
if __name__ == '__main__':
hangman_game()
| true |
efcb63ba80b697680a8b907923bcbcdc609ae94e | Wmeng98/Leetcode | /Easy/merge_2_sorted_lists.py | 1,295 | 4.21875 | 4 | # Solution 1 - Recursive Approach
# Recursivelly define the merge of two lists as the following...
# Smaller of the two head nodes plus to result of the merge on the rest of the nodes
# Time 0(n+m) and Space O(n+m) -> first recursive call doesn't return untill ends of l1 && l2 have been reached
# Solution 2 - Iterative Approach
# Can achieve the same idea via iteration
# Insert elements of l2 in necessary places of l1
# Need to setup...
# A false prehead to return the head of merged list
# prev - node we will be adjusting the next ptr of
# Stop comparison until one of l1 or l2 points to null
# Time O(n+m) Space O(1) - only alloc a few pointers
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val < l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# connect non-null list to end of merged list
prev.next = l1 if l1 is not None else l2
return prehead.next
| true |
ff234acf470b12fe21ee41df3d2a2cf69bd0af91 | tejalbangali/HackerRank-Numpy-Challenge | /Arrays.py | 502 | 4.40625 | 4 | # Task:
# --> You are given a space-separated list of numbers. Your task is to print a reversed NumPy array with the element type float.
# -> Input Format: A single line of input containing space-separated numbers.
# -> Sample Input: 1 2 3 4 -8 -10
# -> Sample Output: [-10. -8. 4. 3. 2. 1.]
import numpy
def arrays(arr):
arr=numpy.array(arr)
arr=arr.astype(float)
result=arr[::-1]
return result
arr = input().strip().split(' ')
result = arrays(arr)
print(result)
| true |
83243d09a2140da62c7a572d2d887e879801e104 | victordity/PythonExercises | /PythonInterview/binarySearch.py | 1,029 | 4.21875 | 4 | import bisect
def bisect_tutorial():
fruits = ["apple", "banana", "banana", "banana", "orange", "pineapple"]
print(bisect.bisect(fruits, "banana"))
print(bisect.bisect_left(fruits, "banana"))
occurrences = bisect.bisect(fruits, "banana") - bisect.bisect_left(fruits, "banana")
print(occurrences) # Number of occurrences of the word banana
bisect.insort_left(fruits, "kiwi")
print(fruits)
def binary_iterative(elements, search_item):
"""Return the index of the search_item element."""
left, right = 0, len(elements) - 1
while left <= right:
middle_idx = (left + right) // 2
middle_element = elements[middle_idx]
if middle_element == search_item:
return middle_idx
if middle_element < search_item:
left = middle_idx + 1
elif middle_element > search_item:
right = middle_idx - 1
return None
if __name__ == '__main__':
elements = [3, 4, 5, 5, 9]
a = binary_iterative(elements, 5)
print(a)
| true |
4d51b16c7673470425579525742dd537470e48b9 | loide/MITx-6.00.1x | /myLog.py | 841 | 4.46875 | 4 | '''
This program computes the logarithm of a number relative to a base.
Inputs:
number: the number to compute the logarithm
base: the base of logarithm
Output:
Logarithm value [ log_base (number) ]
'''
def myLog(number, base):
if ( (type(number) != int) or (number < 0)):
return "Error: Number value must be a positive integer."
if ( (type(base) != int) or (base < 2)):
return "Error: Base value must be an integer greater than or equal 2."
return recursiveRad(number, base)
def recursiveRad(number, base):
if base > number:
return 0
if number <= 1:
return 0
else:
return 1 + recursiveRad(number/base, base)
if __name__ == "__main__":
number = int(raw_input('Insert a number: '))
base = int(raw_input('Insert the base value: '))
print myLog(number, base)
| true |
579e0da0253ec03a4583ba2288b552b72c0d5ced | anweshachakraborty17/Python_Bootcamp | /P48_Delete a tuple.py | 295 | 4.15625 | 4 | #Delete a tuple
thistuple1 = ("apple", "banana", "mango")
del thistuple1
print(thistuple1) #this will raise an error because the tuple no longer exists
#OUTPUT window will show:
#Traceback (most recent call last): File "./prog.py", line 3, in NameError: name 'thistuple1' is not defined | true |
5cf51d431c50db3886d1daa7c5dc07ea19e133f7 | harsh4251/SimplyPython | /practice/oops/encapsulation.py | 543 | 4.4375 | 4 | class Encapsulation():
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
print("Private can only be accessed inside a class {}".format(self.__private))
e = Encapsulation(1,2,3)
print("Public & protacted can be access outside class{},{} ".format(e.public,e._protected))
"""Name
Notation
Behaviour
name Public
Can be accessed from inside and outside
_name Protected
Like a public member, but they shouldn't be directly accessed from outside.
__name Private
Can't be seen and accessed from outside"""
| true |
0b2deb15577ba07a878f00d91eee617d48605bec | beekalam/fundamentals.of.python.data.structures | /ch02/counting.py | 583 | 4.15625 | 4 | """
File: counting.py
prints the number of iterations for problem sizes
that double, using a nested loop
"""
if __name__ == "__main__":
problemSize = 1000
print("%12s%15s" % ("Problem Size", "Iterations"))
for count in range(5):
number = 0
#The start of the algorithm
work = 1
for j in range(problemSize):
for k in range(problemSize):
number += 1
work += 1
work -= 1
# the end of the algorithm
print("%12d%15d" % (problemSize, number))
problemSize *= 2
| true |
8e19018571298372b73695afb9139596e1524464 | MITRE-South-Florida-STEM/ps1-summer-2021-luis-c465 | /ps1c.py | 1,706 | 4.125 | 4 | annual_salary = float(input("Enter the starting salary: "))
total_cost = 1_000_000
semi_annual_raise = .07
portion_down_payment = 0.25
r = 0.04 # Return on investment
total_months = 0
current_savings = 0.0
def down_payment(annual_salary: int, portion_saved: float, total_cost: int,
portion_down_payment: float, r: float, semi_annual_raise: float,
semi_annual_raise_after = 6
) -> int:
total_months = 0
current_savings = 0.0
while total_cost * portion_down_payment > current_savings:
if total_months != 0 and (total_months % semi_annual_raise_after) == 0:
annual_salary *= 1 + semi_annual_raise
return_on_investment = current_savings * (r / 12)
investment = (annual_salary / 12) * portion_saved
current_savings += return_on_investment + investment
total_months += 1
return total_months
moths = 36
bisections = 0
low = 0
high = 10_000
high_before = high
# ! Lower this value for a more accurate answer / more bisections !
# ! Must be greater than 1 !
epsilon = 3
while abs(low - high) >= epsilon:
guess = (high + low) // 2
payment_guess = down_payment(annual_salary, guess / high_before, total_cost, portion_down_payment, r, semi_annual_raise)
# print(f"Bisections: {bisections}")
# print(f"Payment guess months: {payment_guess}")
# print(f"Guess: {guess}\tLow/High: {low}/{high}\n")
if moths < payment_guess: low = guess
else: high = guess
bisections += 1
if high == high_before:
print(f"It is not possible to pay the down payment in {moths / 12} years.")
else:
print(f"Best savings rate: {guess / high_before}")
print(f"Steps in bisection search: {bisections}")
| true |
315ace2527ebf89d6e80aea2a47047f0484f5b40 | Owensb/SnapCracklePop | /snapcrackle.py | 457 | 4.125 | 4 | # Write a program that prints out the numbers 1 to 100 (inclusive).
# If the number is divisible by 3, print Crackle instead of the number.
# If it's divisible by 5, print Pop.
# If it's divisible by both 3 and 5, print CracklePop. You can use any language.
i = []
for i in range (1, 101):
if (i % 3 ==0) & ( i % 5 ==0) :
print ('CracklePop')
elif (i % 5 == 0):
print ('Pop')
elif (i % 3 ==0) :
print ('Crackle')
else:
print(i) | true |
64ba459b0b322274f900e1716496e7643d90bde1 | shermansjliu/Python-Projects | /Ceasar Cipher/Ceaser Cipher.py | 1,888 | 4.21875 | 4 | def ReturnEncryptedString():
code = input("Enter in the code you would like to encrypt")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += EncryptKey(oldChar)
print(newString)
def ReturnDecryptedString():
code = input("Enter in the code you would like to decipher")
code = code.upper()
newString = ""
tempArr = list(code)
for oldChar in tempArr:
newString += DecodeKey(oldChar)
print(newString)
def DecodeKey(char):
#Create temp array for word
#take i element in word array and shift it the ascii number back 5 letters
asciiInt = ord(char)
tempInt = ord(char)
tempInt += 13
#If ascii value is greater than 90 shift the original ascii value back by 26
if(char == "!"):
return char
elif(char == " "):
return char
elif(tempInt > 90 ):
asciiInt -=13
else:
asciiInt += 13
#convert the ascii value to a character using the function chr()
char = chr(asciiInt)
#Append character to a new string
return char
def EncryptKey(char):
asciiInt = ord(char)
tempInt = ord(char)
tempInt -= 13
if(char == "!"):
return char
elif(char == " "):
return char
elif(tempInt < 64 ):
asciiInt +=13
else:
asciiInt -= 13
#convert the ascii value to a character using the function chr()
char = chr(asciiInt)
#Append character to a new string
return char
def PromptUser():
answer = input("Do you want to decode or encrypt your message?")
answer = answer.lower()
if(answer == "encrypt"):
ReturnEncryptedString()
if(answer == "decode"):
ReturnDecryptedString()
print("This is Ceaser's Cipher")
PromptUser()
#TODO Convert letter from alphabet 13 spaces or 13 spaces up in Ascii table
#Take user's input
#Convert
| true |
48def1c3190fb8e4463f68dd478055621b12e4b6 | yooshxyz/ITP | /Feb19.py | 1,702 | 4.125 | 4 | import random
# answer = answer.strip()[0].lower()
def main():
while True:
user_choice_input = int(input("What Function do you want to Use?\nPlease type 1 for the No vowels function, type 2 for the random vowels function, and 3 for the even or odd calculator.\n"))
if user_choice_input == 1:
vowelLessCommand()
elif user_choice_input == 2:
randomWords()
elif user_choice_input ==3:
evenOdd()
else:
print("Please choose one of those numbers!")
user_quit_option = input("If you wise to exit please press X")
if user_quit_option.lower() == "x":
print("Exiting....")
break
else:
return
return
def vowelLessCommand():
vowels = ["a","e","i","o","u"]
user_input = input("Please input your sentence: ")
vowelless = ""
for i in user_input:
if i not in vowels:
if i != vowels:
vowelless = vowelless + i
print(vowelless)
def randomWords():
x = 0
vowels = ["a","e","i","o","u"]
user_input2 = input("Please input your sentence: ")
randomvalues = ""
for i in user_input2:
if i in vowels:
i = random.choice(vowels)
randomvalues += i
else:
randomvalues += i
print(randomvalues)
def evenOdd():
user3_input = float(input("Please pick a number."))
if user3_input % 2 == 0:
print("The number is even!")
else:
print("The number is odd!")
def addUp():
x = 0
user_number_input = int(input("Pick a number!"))
main()
| true |
a09d239c09374761d9c78ae4cfd872eec416a71c | NishadKumar/leetcode-30-day-challenge | /construct-bst-preorder-traversal.py | 1,585 | 4.15625 | 4 | # Return the root node of a binary search tree that matches the given preorder traversal.
# (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
# It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
current = root
stack = [root]
i = 1
while i < len(preorder):
if preorder[i] < current.val:
current.left = TreeNode(preorder[i])
current = current.left
else:
while True:
if not stack or stack[-1].val > preorder[i]:
break
current = stack.pop()
current.right = TreeNode(preorder[i])
current = current.right
stack.append(current)
i += 1
return root | true |
b1d83a286acfa0d779945d7ab5f0cfbb608f735e | nandanabhishek/C-programs | /Checking Even or Odd/even_odd.py | 249 | 4.21875 | 4 | a = int(input(" Enter any number to check whether it is even or odd : "))
if (a%2 == 0) :
print(a, "is Even !")
# this syntax inside print statement, automatically adds a space between data separated by comma
else :
print(a, "is Odd !")
| true |
3507349ce69a165ef1b4165843a3ba72e09e4a12 | Rishab-kulkarni/caesar-cipher | /caesar_cipher.py | 1,861 | 4.40625 | 4 | import string
# Enter only alphabets
input_text = input("Enter text to encrypt:").lower()
shift_value = int(input("Enter a shift value:"))
alphabet = string.ascii_lowercase
alphabet = list(alphabet)
def encrypt(input_text,shift_value):
"""
Shifts all the characters present in the input text by a fixed value(encrypting) and returns the encrypted text.
"""
encrypted_text = ""
for ch in input_text:
index = alphabet.index(ch)
if index + shift_value >=26:
encrypted_text+="".join(alphabet[index + shift_value - 26])
else:
encrypted_text +="".join(alphabet[index + shift_value])
return encrypted_text
encrypted_text = encrypt(input_text, shift_value)
print("Encrypted text:",encrypted_text)
def decrypt(encrypted_text):
"""
Brute forces through all the shift values and decrypts the given encrypted text.
Uses the method encrypt() but the shift value passed is negative, inorder to decrypt.
"""
print("All possible messages:")
for shift in range(1,27):
decrypted_text = encrypt(encrypted_text,-shift)
print(decrypted_text, shift)
decrypt(encrypted_text)
def text_to_morse(encrypted_text):
"""
Converts the encrpyted text into morse code.
"""
morse_codes = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--'
,'-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..'
]
morse_alphabet_codes = dict(zip(list(alphabet),morse_codes))
print(morse_alphabet_codes)
encrypted_morse = ""
for ch in encrypted_text:
encrypted_morse += morse_alphabet_codes.get(ch)
return encrypted_morse
print(text_to_morse(encrypted_text))
| true |
0e8366c415dd5b7ba4812b30d1a97dd5b4bf7763 | Sipoufo/Python_realisation | /Ex-12/guess_number.py | 1,389 | 4.125 | 4 | from art import logo
import random
print("Welcome to the Number Guessing Game")
# init
live = 0
run = True
# function
def add_live(difficulty):
if difficulty.lower() == 'easy':
return 10
elif difficulty.lower() == 'hard':
return 5
def compare(user, rand):
if user < rand:
print("Too low")
elif user > rand:
print("Too high")
else:
print(f"You got it! the answere was {guess}")
# running the app
while run:
print(logo)
print("I'm thinking of a number between 1 and 100: ")
answere = random.randint(1, 101)
print(f"Pssf {answere}")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
live = add_live(difficulty)
guess = 0
while guess != answere:
if live == 0:
print(compare(guess, answere))
print("You've run out of guesses, you lose")
run = False
break
elif guess == answere:
compare(guess, answere)
run = False
else:
print(f"You have {live} attempts remaning to guess the number")
guess = int(input("Make a guess: "))
live -= 1
compare(guess, answere)
print("Guess again")
again = input("Try again? 'Yes' or 'No': ")
if again == 'No':
run = False
else:
run = True
| true |
f55819c8e653d6b4d94ad5f74cffd6a8121ddda2 | cmparlettpelleriti/CPSC230ParlettPelleriti | /Lectures/Dictionaries_23.py | 2,317 | 4.375 | 4 | # in with dictionaries
grades = {"John": 97.6,
"Randall": 80.45,
"Kim": 67.5,
"Linda": 50.2,
"Sarah": 99.2}
## check if the student is in there
name = input("Who's grade do you want? ")
print(name in grades)
## if not there, add them
name = input("Who's grade do you want? ").capitalize()
if name in grades:
print(grades[name])
else:
print("This student does not have a grade for this assignment")
g = input("Please enter a grade now: ")
try:
g = float(g)
except:
print("Invalid grade, assigning grade of 0 for now")
g = 0
finally:
grades[name] = g
print(grades)
# sets
my_set = {"February", "January", "April"}
print(my_set)
my_set2 = {1,1,1,1,1,1,3,5,9,11}
print(my_set2)
# creating sets
my_list = [10,5,5,9,3,4,9,1,2,6,8,9,4,2,5,7]
my_list_to_set = set(my_list)
print(my_list_to_set)
## can't put mutable objects inside a set
my_mutables = {(1,2,3,4), (5,6,7,8)}
## but you can mix types
my_mixed_set = {1, "ant", "blue", (1,2)}
print(my_mixed_set)
# set methods
my_set.add("June")
print(my_set)
my_set.add("February")
print(my_set)
my_set.remove("January")
print(my_set)
## union, intersection, difference
odds = {1,3,5,7,9}
evens = {2,4,6,8,10}
pos_ints = {1,2,3,4,5,6,7,8,9,10}
primes = {2,3,5,7}
# union
print(odds | evens)
print(odds.union(evens))
# intersection
print(odds & pos_ints)
print(odds.intersection(pos_ints))
# difference
print(odds - primes)
print(odds.difference(primes))
print(primes - odds)
print(primes.difference(odds))
# symmetric difference
print(odds^primes)
print(odds.symmetric_difference(primes))
print(primes^odds)
# if i switched the order, would the answer be different?
'''
Let's write some code to ask two friends their favorite music artists,
and then print out a message telling them which artists they both said they like!
'''
songs = {}
for friend in range(0,2):
f = "friend" + str(friend)
print("Welcome " + f)
songs[f] = set()
artist = input("Name an artist you like, enter a blank string to end: ").lower()
while artist != "":
songs[f].add(artist)
artist = input("Name an artist you like, enter a blank string to end: ").lower()
print("GREAT JOB!")
print("The artists you have in common are: ", ",".join(list(songs["friend0"] & songs["friend1"])))
| true |
39a97c3366248770fba81735c9c4e231b34077b9 | kuwarkapur/Robot-Automation-using-ROS_2021 | /week 1/assignement.py | 2,292 | 4.3125 | 4 | """Week I Assignment
Simulate the trajectory of a robot approximated using a unicycle model given the
following start states, dt, velocity commands and timesteps
State = (x, y, theta);
Velocity = (v, w)
1. Start=(0, 0, 0); dt=0.1; vel=(1, 0.5); timesteps: 25
2. Start=(0, 0, 1.57); dt=0.2; vel=(0.5, 1); timesteps: 10
3. Start(0, 0, 0.77); dt=0.05; vel=(5, 4); timestep: 50
Upload the completed python file and the figures of the three sub parts in classroom
"""
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
class Unicycle:
def __init__(self, x: float, y: float, theta: float, dt: float):
self.x = x
self.y = y
self.theta = theta
self.dt = dt
# Store the points of the trajectory to plot
self.x_points = [self.x]
self.y_points = [self.y]
def step(self, v: float, w: float, n:int):
for i in range(n):
self.theta += w *(self.dt)
self.x += v*np.cos(self.theta)
self.y += v*np.sin(self.theta)
self.x_points.append(self.x)
self.y_points.append(self.y)
return self.x, self.y, self.theta
def plot(self, v: float, w: float,i:int):
plt.title(f"Unicycle Model: {v}, {w}")
plt.title(f"kuwar's graphs {i}")
plt.xlabel("x-Coordinates")
plt.ylabel("y-Coordinates")
plt.plot(self.x_points, self.y_points, color="red", alpha=0.75)
plt.grid()
plt.show()
if __name__ == "__main__":
print("Unicycle Model Assignment")
# make an object of the robot and plot various trajectories
point = [{'x':0,'y': 0,'theta': 0,'dt': 0.1, 'v':1,'w': 0.5,'step': 25},
{'x':0,'y': 0,'theta': 1.57,'dt' :0.2,'v': 0.5, 'w':1,'step': 10},
{'x':0,'y': 0,'theta': 0.77, 'dt':0.05, 'v': 5,'w': 4, 'step': 50},
]
for i in range(len(point)):
x = point[i]['x']
y = point[i]['y']
theta = point[i]['theta']
dt = point[i]['dt']
v = point[i]['v']
w = point[i]['w']
n = point[i]['step']
model=Unicycle(x, y, theta, dt)
position =model.step(v, w, n)
x, y, theta = position
model.plot(v, w, i+1) | true |
22e283d052f9b9931bf09c823dfb93dba87b33ed | Aijaz12550/python | /list/main.py | 953 | 4.375 | 4 |
#########################
##### remove method #####
#########################
list1 = [ 1, 2, True, "aijaz", "test"]
"""
list.remove(arg) it will take one item of list
as a argument to remove from list
"""
list1.remove(1) # it will remove 1 from list1
#list1.remove(99) # it will throw error because 99 is not exist
print("list1",list1)
#########################
##### sorting list #####
#########################
sorting_list = [1,2 ,33, -44, 108, 9876, -44545, 444]
sorting_list.sort() # it will sort the original list
print(" sorting_list =",sorting_list)
sorted_list = sorted(sorting_list) # it will return the sorted list without changing the original.
print("sorted_list = ",sorted_list)
#########################
##### slicing list #####
#########################
s_l1 = [0, 1, 2, 3]
s_c = s_l1[:]
print("s_c",s_c)
list2 = [1] * 3 # [1, 1, 1]
list3 = [2,3]
list4 = list2 + list3 # [ 1, 1, 1, 2, 3 ]
print("list4",list4)
| true |
43224d710674f33eafd7a5d1b0feb25bfec35141 | FlyingEwok/Linear-BinarySearch | /binarysearch.py | 1,116 | 4.21875 | 4 | def binarySearch (list, l, listLength, value):
# Set up mid point variable
if listLength >= l:
midPoint = l + (listLength - l) // 2
if list[midPoint] == value: # return the midpoint if the value is midpoint
return midPoint
elif list[midPoint] > value: # Do a search to the left of midpoint for value then return that
return binarySearch(list, l, midPoint-1, value)
else: # Do a search to the right of midpoint for value then return that
return binarySearch(list, midPoint + 1, listLength, value)
else: # if value not in list then return -1
return -1
searchList = [1, 2, 3, 4, 5, 6, 7, 8, 99]
# Ask user for a number
try:
value = int(input("Enter a number: "))
# perform the binary search on the search list
result = binarySearch(searchList, 0, len(searchList)-1, value)
# Print the results in a statement
if result != -1:
print ("Element is at index", result)
else:
print ("Element is not in list")
except ValueError:
print("That's no number! Try again.")
| true |
15bf570be794b9919f43b5786f61a8a97eb81d31 | YunusEmreAlps/Python-Basics | /2. Basic/Output.py | 1,846 | 4.34375 | 4 | # --------------------
# Example 1 (Output)
# This is comment
"""
This
is
multi-line
comments
"""
# if you want to show something on console
# you need to use a "print" instruction
# syntax:
# print('Message') -> single quotes
# print("Message") -> double quotes
print(' - Hello World!')
print(" - I love Python programming language.")
# ----------
# print('I'm Yunus Emre') syntax error
print(" - I'm Yunus Emre")
print(" - I'm student of computer engineer.")
# ----------
# print("George always says "I love you"") syntax error
print(' - George always says "I love you"')
print(' - “Be the change that you wish to see in the world.” Mahatma Gandhi')
# ----------
# Escape sequence syntax :
# \n -> new line
# \t -> tab
# \r -> return
# \\ -> backslash
# ----------
print(" - first line \n")
print("\n - second line")
# first line
# (new line)
# (new line)
# second line
# ----------
print(" - A \t B \t C \n")
# ----------
# This is important
# _-_Avatar (return)
# _-_James
# Output : Jamesr
print(" - Avatar \r - James")
print("\t\t Escape Sequence\r - Python")
# ----------
# print("\") syntax error
print(" - \\")
# ----------
# if you want to read a paragraph you need to use:
print(''' - If you choose to use your status and influence to raise your voice on behalf of those who have no voice; if you choose to identify
not only with the powerful, but with the powerless; if you retain the ability to imagine yourself into the lives of those who do not
have your advantages, then it will not only be your proud families who celebrate your existence, but thousands and millions of
people whose reality you have helped change. We do not need magic to change the world, we carry all the power we need inside
ourselves already: we have the power to imagine better.
''')
# ----------
print("+"*10) # Output:++++++++++ | true |
f5f54b5db00added0abbf07df9fa2c38bb2e2fbc | compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay | /class10-05/calculator.py | 844 | 4.21875 | 4 | #get the first number
#get the second number
#make an individual function to add, subtract, multiply and divide
#return from each function
#template for add function
def add(num1, num2):
return (num1+num2)
def sub(num1, num2):
return (num1-num2)
def multiply(num1, num2):
return (num1*num2)
def division(num1, num2):
return (num1/num2)
num1 = int(input("Enter the First Number"))
num2 = int(input("Enter the Second Number"))
option = int(input("Enter 1 for Addition \n Enter 2 for Subtration \n Enter 3 for Multiplication \n Enter 4 for Division"))
if (option == 1):
print("The sum is: ", add(num1,num2))
elif (option == 2):
print("The difference is: ", sub(num1,num2))
elif (option == 3):
print("The product is: ", multiply(num1,num2))
elif (option == 4):
print("the quotient is: ", division(num1,num2)) | true |
8d438c71959d3fd16bffc44490bdfea783fcf61d | vassmate/Learn_Python_THW | /mystuff/ex3.py | 1,312 | 4.8125 | 5 | # http://learnpythonthehardway.org/book/ex3.html
# This will print out: "I will count my chickens:".
print "I will count my chikens:"
# This will print out how much Hens we have.
print "Hens", 25.0 + 30.0 / 6.0
# This will print out how much roosters we have.
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# This will print out: "Now I will count the eggs:".
print"Now I will count the eggs:"
# This will print out the result of the given math opertions.
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
# This will print out: "Is it true that 3 + 2 < - 7?"
print "Is it true that 3 + 2 < 5 - 7?"
# This will print out the result of the given math operations.
print 3.0 + 2.0 < 5.0 - 7.0
# This will print out the answer for the printed question: "What is 3 + 2?".
print "What is 3.0 + 2.0?", 3.0 + 2.0
# This will print out the answer for the printed question: "What is 5 - 7?".
print "What is 5.0 - 7.0?", 5.0 - 7.0
# This will print out : "Oh, that's why it's False.".
print "Oh, that's why it's False."
# THis will print out : "How about some more.".
print "How about some more."
# These will print out the answers for the printed questions.
print "Is 5.0 > -2.0 greater?", 5.0 > -2.0
print "Is 5.0 >= -2.0 greater or equal?", 5.0 >= -2.0
print "Is 5.0 <= -2.0 less or equal?", 5.0 <= -2.0
| true |
1abd8eea6ff68cbb119651fc9e978bef80dfa1a8 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 577 | 4.4375 | 4 | #!/usr/bin/env python3
"""Module to compute the shape of a matrix"""
def matrix_shape(matrix):
"""Calculates the shape of a matrix.
Arguments:
matrix (list): the matrix that will be processed
Returns:
tuple: a tuple that contains the shape of every dimmension
in the matrix.
"""
shape = []
dimension = matrix[:]
while isinstance(dimension, list):
size = len(dimension)
shape.append(size)
if size > 0:
dimension = dimension[0]
else:
break
return shape
| true |
79969b00b7683284a24114fa72d3b613caf1d3d2 | thenickforero/holbertonschool-machine_learning | /math/0x00-linear_algebra/14-saddle_up.py | 598 | 4.15625 | 4 | #!/usr/bin/env python3
"""Module to compute matrix multiplications.
"""
import numpy as np
def np_matmul(mat1, mat2):
"""Calculate the multiplication of two NumPy Arrays.
Arguments:
mat1 (numpy.ndarray): a NumPy array that normally represents a square
matrix.
mat2 (numpy.ndarray): a NumPy array that normally represents a square
matrix.
Returns:
numpy.ndarray: a NumPy array which is the multiplication
of @mat1 and @mat2.
"""
return np.matmul(mat1, mat2)
| true |
a403e25b42db8d2b9033c06b5aac45074300d4b3 | dkrusch/python | /lists/planets.py | 1,109 | 4.40625 | 4 | planet_list = ["Mercury", "Mars"]
planet_list.append("Jupiter")
planet_list.append("Saturn")
planet_list.extend(["Uranus", "Neptune"])
planet_list.insert(1, "Earth")
planet_list.insert(1, "Venus")
planet_list.append("Pluto")
slice_rock = slice(0, 4)
rocky_planets = planet_list[slice_rock]
del[planet_list[8]]
# Use append() to add Jupiter and Saturn at the end of the list.
# Use the extend() method to add another list of the last two planets in our solar system to the end of the list.
# Use insert() to add Earth, and Venus in the correct order.
# Use append() again to add Pluto to the end of the list.
# Now that all the planets are in the list, slice the list in order to get the rocky planets into a new list called rocky_planets.
# Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the del operation to remove it from the end of planet_list.
# Example spacecraft list
spacecraft = [
("Cassini", "Saturn"),
("Viking", "Mars"),
]
for planet in planet_list:
print(planet)
for craft in spacecraft:
if (craft[1] == planet):
print(craft[0]) | true |
94d4dae91040dd8a74cce61e0977cc3931760ac0 | mali44/PythonPracticing | /Palindrome1.py | 645 | 4.28125 | 4 |
#Ask the user for a string and print out whether this string is a palindrome or not.
#(A palindrome is a string that reads the same forwards and backwards.)
mystr1= input("Give a String")
fromLeft=0
fromRight=1
pointer=0
while True:
if fromLeft > int(len(mystr1)):
break
if fromRight > int(len(mystr1)):
break
checker=mystr1[fromLeft]
fromLeft+=1
revChecker=mystr1[-fromRight]
fromRight+=1
if (checker != revChecker):
flag=0
else:
flag=1
if pointer==1:
print(mystr1+"is a Palindrome")
else:
print(mystr1+"not a Palindrome")
| true |
71dad1096b5699d19ad30d431d025aa12b8165f4 | E-Cell-VSSUT/coders | /python/IBAN.py | 2,276 | 4.125 | 4 | # IBAN ( International Bank Account Number ) Validator
'''
An IBAN-compliant account number consists of:
-->a two-letter country code taken from the ISO 3166-1 standard (e.g., FR for France, GB for Great Britain, DE for Germany, and so on)
-->two check digits used to perform the validity checks - fast and simple, but not fully reliable, tests, showing whether a number is invalid (distorted by a typo) or seems to be good;
-->the actual account number (up to 30 alphanumeric characters - the length of that part depends on the country)
The standard says that validation requires the following steps (according to Wikipedia):
(step 1) Check that the total IBAN length is correct as per the country.
(step 2) Move the four initial characters to the end of the string (i.e., the country code and the check digits)
(step 3) Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11 ... Z = 35;
(step 4) Interpret the string as a decimal integer and compute the remainder of that number on division by 97; If the remainder is 1, the check digit test is passed and the IBAN might be valid.
'''
def country_length(name):
if name == 'INDIA':
return 'IN'
elif name == 'USA' or name == 'UNITED STATES':
return 'US'
elif name == 'UK' or name == 'GREAT BRITAIN':
return 'GB'
elif name == 'GERMANY':
return 'DE'
iban = input("Enter IBAN, please: ")
iban = iban.replace(' ', '')
country = input('Enter your country: ').upper()
iban_len = country_length(country)
if not iban.isalnum(): # checking for special characters in IBAN
print('Invalid characters entered')
elif len(iban) < 15: # checking if the length is less than 15
print('IBAN enetered is too short')
elif len(iban) > 31: # checking if the length is greater than 15
print('IBAN enetered is too long')
else:
# checking the iban after adding the first four characters to the end of iban
iban = (iban[4:] + iban[0:4]).upper()
iban2 = ''
for ch in iban:
if ch.isdigit():
iban2 += ch
else:
iban2 += str(10 + ord(ch) - ord('A'))
iban = int(iban2)
if iban % 97 == 1:
print("IBAN entered is valid.")
else:
print("IBAN entered is invalid.")
| true |
68e650fa51502dcc2a1e15bb7b956cb0c8630c58 | E-Cell-VSSUT/coders | /python/Fibonacci.py | 750 | 4.3125 | 4 | # -- Case-1 -->> Using Function
# This is a program to find fibonacci series using simple function
def fib(n):
if n < 1: # Fibonacci is not defined for negative numbers
return None
if n < 3: # The first two elements of fibonacci are 1
return 1
elem1 = elem2 = 1
sum = 0
for i in range(3, n+1):
sum = elem1+elem2
elem1, elem2 = elem2, sum
# First element becomes becomes second element
# Second element becomes the sum of previous two elements
return sum
#--Main--#
for i in range(1, 10):
print(i, " -->> ", fib(i))
# -- Case-2 -->> Using Recursive Function
def fib_rec(n):
if n < 0:
return None
if n < 3:
return 1
return fib(n-1)+fib(n-2)
| true |
faf830c550d3166f125c4b846f95de6b1047d5c7 | fbscott/BYU-I | /CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check02b.py | 682 | 4.21875 | 4 | user_provide_file = input("Enter file: ")
num_lines = 0
num_words = 0
# method for opening file and assigning its contents to a var
# resource: https://runestone.academy/runestone/books/published/thinkcspy/Files/Iteratingoverlinesinafile.html
# file = open(user_provide_file, "r")
# best practice is to use "with" to ensure the file is properly closed
# resource: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
with open(user_provide_file, "r") as file:
for lines in file:
words = lines.split()
num_lines += 1
num_words += len(words)
print(f"The file contains {num_lines} lines and {num_words} words.")
file.close()
| true |
5b9d02e8b3b62588d1de662ef4321b20097c8f10 | sgriffith3/python_basics_9-14-2020 | /pet_list_challenge.py | 843 | 4.125 | 4 | #Tuesday Morning Challenge:
#Start with this list of pets:
pets = ['fido', 'spot', 'fluffy']
#Use the input() function three times to gather names of three more pets.
pet1 = input("pet 1 name: ")
pet2 = input("pet 2 name: ")
pet3 = input("pet 3 name: ")
#Add each of these new pet names to the pets list.
pets.append(pet1)
pets.insert(1, pet2)
pets = pets + [pet3]
#print(pets)
#print(enumerate(pets))
#for ind, val in enumerate(pets):
# print(ind, val)
#Using the pets list, print each out, along with their index.
#
#The output should look like:
#
#0 fido
#1 spot
#2 fluffy
print(0, pets[0])
print(1, pets[1])
print(2, pets[2])
print(3, pets[3])
print(4, pets[4])
print(5, pets[5])
counter = 0
for pet in pets:
print(counter, pet)
counter += 1
# counter = counter + 1
for pe in pets:
print(pets.index(pe), pe)
| true |
900733030503c1011f0df3f2e5ee794499e422b0 | wreyesus/Python-For-Beginners---2 | /0025. File Objects - Reading and Writing to Files.py | 474 | 4.375 | 4 | #File Objects - Reading and Writing to Files
'''
Opening a file in reading / writing / append mode
'''
f = open('test.txt','r')
#f = open('test.txt','w') --write
#f = open('test.txt','r+') --read and write
#f = open('test.txt','a') --append
print(f.name) #will print file name
print(f.mode) #will give r coz it is in reading mode
f.close()
#another way -- which close file automatically
with open('test.txt','r') as f:
print(f.read()) | true |
412ac494347bf94d8fc4b42b4775f4516795005d | bryanjulian/Programming-11 | /BryanJulianCoding/Operators and Stuff.py | 1,028 | 4.1875 | 4 | # MATH!
x = 10
print (x)
print ("x")
print ("x =",x)
x = 5
x = x + 1
print(x)
x = 5
x + 1
print (x)
# x + 1 = x Operators must be on the right side of the equation.
# Variables are CASE SENSITIVE.
x = 6
X = 5
print (x)
print (X)
# Use underscores to name variables!
# Addition (+) Subtraction (-) Multiplycation (*) Division (/) Powers (**)
x=5*(3/2)
x = 5 * (3 / 2)
x =5 *( 3/ 2)
print (x)
# Order of Operations
average = (90 + 86 + 71 + 100 + 98) / 5
# Import the math library
# This line is done only once, and at the very top
# of the program.
from math import *
# Calculate x using sine and cosine
x = sin(0) + cos(0)
print (x)
m = 294 / 10.5
print(m)
m = 294
g = 10.5
m2 = m / g # This uses variables instead
print(m2)
miles_driven = 294
gallons_used = 10.5
mpg = miles_driven / gallons_used
print(mpg)
ir = 0.12
b = 12123.34
i = ir * b
print (i)
# Easy to understand
interest_rate = 0.12
account_balance = 12123.34
interest_amount = interest_rate * account_balance
print (interest_amount)
| true |
9d175894ced0e8687bb5724763722efdeb70741f | Bmcentee148/PythonTheHardWay | /ex_15_commented.py | 743 | 4.34375 | 4 | #import argv from the sys module so we can use it
from sys import argv
# unpack the args into appropriate variables
script, filename = argv
#open the file and stores returned file object in a var
txt_file = open(filename)
# Tells user what file they are about to view contents of
print "Here's your file %r:" % filename
# prints the contents of the file in entirety
print txt_file.read()
#ask user to print filename again
print "Print the filename again:"
#prompts user for input and stores it in given var
filename_again = raw_input('> ')
# opens the file again and stores as object in a new var
txt_file_again = open(filename_again)
# prints the contents of the file again that is stored in different var
print txt_file_again.read()
| true |
c4d5cc928ee53ccfdd17c60938a7f9d0ee54e0ba | donnell794/Udemy | /Coding Interview Bootcamp/exercises/py/circular/index.py | 533 | 4.1875 | 4 | # --- Directions
# Given a linked list, return true if the list
# is circular, false if it is not.
# --- Examples
# const l = new List();
# const a = new Node('a');
# const b = new Node('b');
# const c = new Node('c');
# l.head = a;
# a.next = b;
# b.next = c;
# c.next = b;
# circular(l) # true
def circular(li):
slow = li.head
fast = li.head
while(fast.next and fast.next.next):
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
| true |
669afade07619df314a48551e17ad102f28b249f | donnell794/Udemy | /Coding Interview Bootcamp/exercises/py/fib/index.py | 608 | 4.21875 | 4 | # --- Directions
# Print out the n-th entry in the fibonacci series.
# The fibonacci series is an ordering of numbers where
# each number is the sum of the preceeding two.
# For example, the sequence
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# forms the first ten entries of the fibonacci series.
# Example:
# fib(4) === 3
def memoize(fn):
cache = {}
def helper(x):
if x not in cache:
cache[x] = fn(x)
return cache[x]
return helper
@memoize
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
#memoization decreses rutime from O(2^n) to O(n)
| true |
8fa85e0a0b64bcf6b2175da13c5414b6f4397e90 | cmattox4846/PythonPractice | /Pythonintro.py | 2,522 | 4.125 | 4 | # day_of_week = 'Monday'
# print(day_of_week)
# day_of_week = 'Friday'
# print(f"I can't wait until {day_of_week}!")
# animal_input = input('What is your favorite animal?')
# color_input = input('What is your favorite color?')
# print(f"I've never seen a {color_input} {animal_input}")
#**** time of day
# time_of_day = 1100
# meal_choice = ""
# if time_of_day < 1200: meal_choice = 'Breakfast'
# elif time_of_day > 1200 and time_of_day < 1700: meal_choice = 'Lunch'
# elif time_of_day > 1700: meal_choice = 'Dinner'
# print(meal_choice)
# random Number
# import random
# number = random.randrange(0,10 +1)
# print(number)
# if number >= 0 and number < 3:
# print('Beatles')
# elif number > 2 and number < 6:
# print('Stones')
# elif number > 5 and number < 9:
# print('Floyd')
# elif number > 8 and number <= 10:
# print('Hendrix')
# msg = 'Python is cool!'
# for number in range(7):
# print(msg)
# for number2 in range(11):
# print(number2)
# msg_hello = 'Hello'
# msg_goodbye = 'GoodBye'
# for count in range(5):
# print(msg_hello)
# print(msg_goodbye)
# height= 40
# while height < 48:
# print('Cannot Ride!')
# height += 1
# Magic Number Game
#import random
# magic_numbers = random.randrange(0,100,+1)
# guess = 0
# print(magic_numbers)
# while guess != magic_numbers:
# guess = int(input('Please enter your guess!'))
# if guess > magic_numbers:
# if guess > (magic_numbers - 10) or guess < magic_numbers:
# print('Getting Warmer')
# print('Too Low!')
# elif guess < magic_numbers:
# if guess < (magic_numbers + 10) or guess > magic_numbers:
# print('Getting Warmer!')
# print('Too High!')
# elif guess == magic_numbers:
# print(f'{guess} is the correct number!')
# def print_movie_name():
# Fav_movie = 'Casino'
# print(Fav_movie)
# print_movie_name()
# def favorite_band ():
# band_name_input = input('Please enter your favorite band name')
# return band_name_input
# band_results = favorite_band()
# print(band_results)
# def concert_display(musical_act):
# my_street = input("Please enter the street you live on")
# print(f'It would be great if {musical_act} played a show on {my_street}')
# concert_display("Zac Brown Band")
desktop_items = ['desk', 'lamp', 'pencil']
#print(desktop_items[1])
desktop_items.append('Infinity Gauntlet')
#print(desktop_items[3])
for items in desktop_items:
print(items) | true |
f6ddfe6d2be79149d6a0b7c7fd373e8524990574 | Hadiyaqoobi/Python-Programming-A-Concise-Introduction | /week2/problem2_8.py | 1,206 | 4.53125 | 5 | '''
Problem 2_8:
The following list gives the hourly temperature during a 24 hour day. Please
write a function, that will take such a list and compute 3 things: average
temperature, high (maximum temperature), and low (minimum temperature) for the
day. I will test with a different set of temperatures, so don't pick out
the low or the high and code it into your program. This should work for
other hourly_temp lists as well. This can be done by looping (interating)
through the list. I suggest you not write it all at once. You might write
a function that computes just one of these, say average, then improve it
to handle another, say maximum, etc. Note that there are Python functions
called max() and min() that could also be used to do part of the jobs.
'''
hourly_temp = [40.0, 39.0, 37.0, 34.0, 33.0, 34.0, 36.0, 37.0, 38.0, 39.0, \
40.0, 41.0, 44.0, 45.0, 47.0, 48.0, 45.0, 42.0, 39.0, 37.0, \
36.0, 35.0, 33.0, 32.0]
def problem2_8(temp_list):
count_t = 0
sum_t = 0
print("Average:", sum(temp_list)/len(temp_list))
print("High:",max(temp_list))
print("Low:", min(temp_list))
problem2_8(hourly_temp) | true |
c9696e77689ca80b0ec5c1a46f9e5a59857c3b57 | tHeMaskedMan981/coding_practice | /problems/dfs_tree/symmetric_tree/recursive.py | 995 | 4.21875 | 4 |
# A node structure
class Node:
# A utility function to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, root1, root2):
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
if root1.data != root2.data:
return False
return self.isMirror(root1.left, root2.right) and self.isMirror(root1.right, root2.left)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
print ("Level order traversal of binary tree is -")
print(Solution().isSymmetric(root)) | true |
62e3168c128f1d16bef0ec4cc31afa2e05ae9cae | IshmaelDojaquez/Python | /Python101/Lists.py | 413 | 4.25 | 4 | names = ['John', 'Bob', 'Sarah', 'Mat', 'Kim']
print(names)
print(names[0]) # you can determine a specific positive or negative index
print(names[2:4]) # you can return names at a index to a given index. Does not include that secondary index
names[0] = 'Howard'
# Practice
numbers = [3, 6, 23, 8, 4, 10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
| true |
e2ba3d2b834e092bd3675fbcf8dbe5c33a31f729 | ajitg9572/session2 | /hackerrank_prob.py | 206 | 4.28125 | 4 | #!/bin/python3
# declare and initialize a list
fruits = ["apple","mango","guava","grapes","pinapple"]
# pritning type of fruits
print (type(fruits))
# printing value
for fruit in fruits:
print(fruit) | true |
7272a47b347604d33c2e3bcca50099c1976da126 | gdof/Amadou_python_learning | /rock_paper_scissor/main.py | 1,345 | 4.34375 | 4 | import random
# We are going to create a rock paper scissor game
print("Do you want a rock, paper, scissor game?")
# create a variable call user_input and port the user a Yes a No
user_input = input("Yes or No? ")
# if the user select no print out "It is sorry to see you don't want to play"
if user_input == "no":
print("It is sorry to see you don't want to play")
# if the user select yes prompt the user for a input of rock paper sicssor
elif user_input == "yes":
"""
Store the user input from this elif statment into a variable, set the variable name to user_choice
using python create a words variable called "choice_list" that have three string ["rock", "paper", "sicssor"]
import random
using python random get a random choice from the list and store it in a varibles call random_choice
compare the user choice and the random choice if the user choice match the random choice print aye you guess right
else say guess again
"""
user_choice = input("select rock, paper, sicssor? ")
choice_list = ["rock", "paper", "scissor"]
random_choice = random.choice(choice_list)
if user_choice == random_choice:
print("aye you guess right")
else:
print("guess again")
# else the user don't choice yes or no print out wrong input
else:
print("wrong input")
| true |
30aaffce13d69354705ccb9e3c9c46e565a3b6d2 | Bals-0010/Leet-Code-and-Edabit | /Edabit/Identity matrix.py | 1,664 | 4.28125 | 4 | """
Identity Matrix
An identity matrix is defined as a square matrix with 1s running from the top left of the square to the bottom right. The rest are 0s. The identity matrix has applications ranging from machine learning to the general theory of relativity.
Create a function that takes an integer n and returns the identity matrix of n x n dimensions. For this challenge, if the integer is negative, return the mirror image of the identity matrix of n x n dimensions.. It does not matter if the mirror image is left-right or top-bottom.
Examples
id_mtrx(2) ➞ [
[1, 0],
[0, 1]
]
id_mtrx(-2) ➞ [
[0, 1],
[1, 0]
]
id_mtrx(0) ➞ []
Notes
Incompatible types passed as n should return the string "Error".
"""
# Approach using numpy
def generate_identity_matrix(n):
import numpy as np
temp_n = abs(n)
identity_matrix = np.zeros((temp_n,temp_n))
for i in range(temp_n):
identity_matrix[i][i] = 1
if n>0:
return identity_matrix
else:
return np.flip(identity_matrix, axis=0)
# print(generate_identity_matrix(-2))
# Approach without using numpy
def generate_identity_matrix_no_np(n):
temp_n = abs(n)
id_matrix = [[]]*temp_n
for i in range(temp_n):
id_matrix[i] = [0 for i in range(temp_n)]
for i in range(temp_n):
for j in range(temp_n):
if i==j:
id_matrix[i][j] = 1
if abs(n)==n:
return id_matrix
else:
id_matrix.reverse()
return id_matrix
# print(generate_identity_matrix_no_np(2))
print(generate_identity_matrix_no_np(-2)) | true |
d07e252bff50c58d9cf0d612edbdfd78f9a7b7a7 | radhikar408/Assignments_Python | /assignment17/ques1.py | 349 | 4.3125 | 4 | #Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.
import tkinter
from tkinter import *
import sys
root=Tk()
def show():
print("hello world")
b=Button(root,text="Hello",width=25,command=show)
b2=Button(root,text="exit",width=25, command=exit)
b.pack()
b2.pack()
root.mainloop() | true |
dd579fcf0c2dde41709cc6a552777d799a5240f2 | MattSokol79/Python_Introduction | /python_variables.py | 1,289 | 4.5625 | 5 | # How to create a variable
# If you want to comment out more than one line, highlight it all and CTRL + /
name = "Matt" # String
# Creating a variable called name to store user name
age = 22 # Int
# Creating a variable called age to store age of user
hourly_wage = 10 # Int
# Creating a variable called hourly_wage to store the hourly wage of the user
travel_allowance = 2.1 # Float
# Creating a variable called travel_allowance to store the travel allowance of the user
# Python has string, int, float and boolean values
# How to find out the type of variable?
# => type() gives us the actual type of value
print(travel_allowance)
print(age)
print(hourly_wage)
# How to take user data
# Use input() to get data from users
name1 = str(input("Please enter your name "))
# Getting user data by using input() method
print(name1)
# Exercise - Create 3 variables to get user data: name, DOB, age
user_name = str(input("Please provide your name "))
user_dob = str(input("Please provide your date of birth in the format - dd/mm/yy "))
user_age = int(input("Please provide your age "))
print('Name: ', user_name)
print('DOB: ', user_dob)
print('Age: ', user_age)
print('Type of variable: ')
print('Name: ', type(user_name))
print('DOB: ', type(user_dob))
print('Age: ', type(user_age)) | true |
d7ee9dfcd9573db8b914dc96bff65c61753aceec | fadhilmulyono/CP1401 | /CP1401Lab6/CP1401_Fadhil_Lab6_2.py | 373 | 4.25 | 4 | '''
The formula to convert temperature in Fahrenheit to centigrade is as follows:
c = (f-32)*5/9;
Write a program that has input in Fahrenheit and displays the temperature in Centigrade.
'''
def main():
f = float (input("Enter the temperature in Fahrenheit: "))
c = (f - 32) * 5 / 9
print("The temperature in Celsius is: " + str(c) + " °C")
main() | true |
d3e53df801c4e65d76e275b9414312bdb2f618e5 | fadhilmulyono/CP1401 | /Prac08/CP1401_Fadhil_Prac8_3.py | 607 | 4.3125 | 4 | '''
Write a program that will display all numbers from 1 to 50 on separate lines.
For numbers that are divisible by 3 print "Fizz" instead of the number.
For numbers divisible by 5 print the word "Buzz".
For numbers that are divisible by both 3 and 5 print "FizzBuzz".
'''
def main():
number = 0
while number < 50:
number += 1
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
main() | true |
382700c11c43f4aa36ccdac6076a6b3685243c66 | jasigrace/guess-the-number-game | /main.py | 812 | 4.1875 | 4 | import random
from art import logo
print(logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
number = random.randint(1, 100)
def guess_the_number(number_of_attempts):
while number_of_attempts > 0:
print(f"You have {number_of_attempts} remaining to guess the number. ")
guess = int(input("Make a guess: "))
if guess < number:
print("Too low.\nGuess again.")
number_of_attempts -= 1
elif guess > number:
print("Too high.\nGuess again.")
number_of_attempts -= 1
elif guess == number:
print(f"You got it. The answer was {number}.")
number_of_attempts = 0
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
if difficulty == "easy":
guess_the_number(10)
else:
guess_the_number(5)
| true |
48c2d231d58a0b04c6c91e529ee98bf985988857 | ernur1/thinking-recursively | /Chapter-3/3.2-factorial.py | 392 | 4.28125 | 4 | #===============================================================================
# find the factorial of the given integer
#===============================================================================
def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num-1)
if __name__ == '__main__':
print "Factorial of given number is" , factorial(9) | true |
752eb476bdcfb40289559b662245786b635c1766 | ellen-yan/self-learning | /LearnPythonHardWay/ex33.py | 362 | 4.15625 | 4 | def print_num(highest, increment):
i = 0
numbers = []
while i < highest:
print "At the top i is %d" % i
numbers.append(i)
i = i + increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
print "The numbers: "
numbers = print_num(6, 1)
for num in numbers:
print num
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.