blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d29b902b56c3dcd3f132d6a3d699b061ccdb3bb6 | michaeldton/Fall20-Text-Based-Adventure-Game- | /main.py | 1,859 | 4.21875 | 4 | import sys
from Game.game import Game
# Main function calls the menu
def main():
menu()
# Quit function
def quit_game():
print("Are you sure you want to quit?")
choice = input("""
1: YES
2: NO
Please enter your choice: """)
if choice == "1":
sys.exit
elif choice == "2":
menu()
else:
print("You can only select 1 for yes or 2 for no")
quit_game()
# The playNewGame() initializes a new game from the beginning
def play_new_game():
print()
print("---- Starting New Game ----")
game = Game()
game.start_game()
# The loadCurrentGame() opens a file to the players current level
def load_current_game():
print()
print("---- Loading Save File ----")
game = Game()
game.load_game()
'''
The playGame() allows the user to play a new game, load an existing game,
or return to the main menu.
'''
def play_game():
choice = input("""
1: NEW GAME
2: LOAD GAME
3: GO BACK
Please enter your choice: """)
if choice == "1":
play_new_game()
elif choice == "2":
load_current_game()
elif choice == "3":
menu()
else:
print("Invalid choice, please select 1, 2, or 3.")
play_game()
# The main menu()
def menu():
print("************MAIN MENU**************")
print()
choice = input("""
1: PLAY GAME
2: QUIT
Please enter your choice: """)
if choice == "1":
play_game()
elif choice == "2":
quit_game()
else:
print("You must only select 1 to play or 2 to quit. Please try again.")
menu()
# Main function
if __name__ == '__main__':
main()
| true |
5ef61d947c51a4f5793a005629f22e6ca44e4cbf | iamdeepakram/CsRoadmap | /python/regularexpressions.py | 1,106 | 4.1875 | 4 | # find the patterns without RegEx
# some global variable holding function information
test = "362-789-7584"
# write isphonenumber function with arguments text
def isPhoneNumber(text):
global test
test = text
# check length of string
if len(text) != 12 :
return False
# check area code from index 0 to index 2
for i in range(0,3): # upto 3 but not including 3
if not text[i].isdecimal():
return False
# check hyphen in string
if text[3] != '-':
return False
# check area code from index 4 to index 6
for i in range(4, 7):
if not text[i].isdecimal():
return False
# check hyphen in string
if text[7] != '-':
return False
# check for phone number form index 8 to index 11
for i in range(8, 12):
if not text[i].isdecimal():
return False
#if return true print following
return True
print(test + ' is a phone number:' )
print(isPhoneNumber('362-789-7584'))
print('Is \"agents of shield\" is a phone number:')
print(isPhoneNumber('agents of shield'))
| true |
b3a1e3ab177fac333bc9ee0a5a0b379751807f58 | aklgupta/pythonPractice | /Q4 - color maze/color_maze.py | 2,950 | 4.375 | 4 | """Team Python Practice Question 4.
Write a function that traverse a color maze by following a sequence of colors. For example this maze can be solved by the sequence 'orange -> green'. Then you would have something like this
For the mazes you always pick a spot on the bottom, in the starting color and try to get to the first row. Once you reach the first row, you are out of the maze. You can move horizontally and vertically, but not diagonally. It is also allowed to move on the same node more then once.
Sample Input
Sequence
O G
Maze
B O R O Y
O R B G R
B O G O Y
Y G B Y G
R O R B R
Sample output
/ / / O /
/ / / G /
/ O G O /
/ G / / /
/ O / / /
"""
import copy
MAZE = []
SEQ = []
SOL = []
N = 0 # No of rows in maze
M = 0 # No of cols in maze
S = 0 # Sequence Length
def main():
"""Main Function.
Calls other function to work for it... :D
"""
# input the MAZE, SEQunece, and gereates a blank SOLution
get_inputs()
failed = True
for i in xrange(M):
if get_sol(copy.deepcopy(SOL), [['' for _ in x] for x in SOL], -1, [N-1, i]):
failed = False
print '\n'*3, 'SOLUTION:'
for row in SOL:
for e in row:
print e,
print ''
break
if failed:
print '\n'*3, 'FAILED, No Solution Found'
def get_inputs():
"""Input."""
global SOL, MAZE, SEQ, M, N, S
# Input Maze
MAZE = input('Enter a list of list as input matrix: ')
N = M = len(MAZE)
# Create Blank Solution
SOL = [['/' for _ in x] for x in MAZE]
# Get Sequence to use
S = int(raw_input('Enter length of Sequence: '))
for i in xrange(S):
col = raw_input('Enter Color Letter: ').upper()
SEQ.append(col)
print '\n', 'Maze:'
for i in xrange(N):
for j in xrange(M):
print MAZE[i][j],
print ''
print '\n', 'Sequence:'
print SEQ
def get_sol(cur_sol, when_reached, seq_pos, last_pos):
"""Sols."""
global SOL
seq_pos = 0 if seq_pos == S-1 else seq_pos + 1
i, j = last_pos
# print MAZE[i][j], SEQ[seq_pos], MAZE[i][j] == SEQ[seq_pos]
if MAZE[i][j] == SEQ[seq_pos]:
# Check if we are entering an infinite loop
if str(seq_pos) in when_reached[i][j]:
return False
# Updated current temp solution, and mark the path used
cur_sol[i][j] = SEQ[seq_pos]
when_reached[i][j] += str(seq_pos)
# If we reached the top
if i == 0:
SOL = cur_sol
return True
# Go Up
if i > 0 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i-1, j]):
return True
# Go Down
if i < N-1 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i+1, j]):
return True
# Go Left
if j > 0 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i, j-1]):
return True
# Go Right
if j < M-1 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i, j+1]):
return True
# Return False if no sol found
return False
if __name__ == '__main__':
main()
| true |
2e2040449bac85c3dcabef42f995a2bef7c00966 | pavit939/A-December-of-Algorithms | /December-09/url.py | 444 | 4.1875 | 4 | def https(s):
if(s[0:8]=="https://"):
return '1'
else:
return '0'
def url(s):
if (".com" in s or ".net" in s or ".org" in s or ".in" in s):
return "1"
else :
return '0'
s = input("Enter the string to check if it is an URL")
c = https(s)
if c =='1':
u = url(s)
if u =='1':
print(f"{s} is an URL")
else:
print(f"{s} is not an URL")
else:
print(f"{s} is not an URL")
| true |
63488064897109f0ba3806912b1fcf38e759a97f | Krishna-Mohan-V/SkillSanta | /Assignment101-2.py | 964 | 4.40625 | 4 | # Python program to find the second largest number in a list
# Method 1
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.sort()
print("Second largest Number in the List is ",lst[-2])
# Method 2
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.sort()
lst.reverse()
print("Second largest Number in the List is ",lst[1])
# Method 3
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.remove(max(lst))
print("Second largest Number in the List is ",max(lst))
| true |
e15850165397b66795497cfa10d2495139998de0 | Davenport70/python-basics- | /practice strings.py | 1,351 | 4.5625 | 5 | # practice string
# welcome to Sparta - excercise
# Version 1 specs
# define a variable name, and assign a string with a name
welcome = 'Hello and welcome!'
print(welcome)
# prompt the user for input and ask the user for his/her name
user_input = input('What is your name?')
print(user_input)
# use concatenation to print a welcome method and use method to format the name/input
print(f'Hello and welcome {user_input} thanks for the name!')
# version 2
# ask the user for a first name and save it as a variable
user_input_first_name = input('What is your first name?')
print(user_input_first_name)
# ask the user for a last name and save it as a variable
user_input_last_name = input('What is your last name?')
print(user_input_last_name)
# do the same but use a different message andza
# use interpolation to print the message
user_input_full_name = input('What is your first name') + ' ' + input('What is your last name')
print(user_input_full_name)
# Calculate year of Birth
# gather details on age and name
user_input_full_name = input('What is your first name') + ' ' + input('What is your last name')
age = input(f'Hello {user_input_full_name} can I take your age?')
birthday = 2020 - int(age)
input('Can I have your name please?')
print(f'OMG {user_input_full_name}, you are {age} years old so you were born in {birthday} year')
| true |
47f5e052808e5a77df1a15980e1ea37fad4756e4 | raghavgr/Leetcode | /reverse_string344.py | 862 | 4.3125 | 4 | """
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
class Solution:
""" 2 solutions """
def reverseString(self, s):
"""
in-place reverse string algorithm
i.e. another string is not used to store the result
:type s: str
:rtype: str
"""
chars = list(s)
for i in range(len(s) // 2):
temp = chars[i]
chars[i] = chars[len(s) - i - 1]
chars[len(s) - i - 1] = temp
return ''.join(chars)
def reverseString_pythonic(self, s):
"""
Reverse string using slicing
:type s: str
:rtype: str
"""
return s[::-1]
obj = Solution()
print(obj.reverseString("hello")) # 'olleh'
print(obj.reverseString_pythonic("clara")) # 'aralc' | true |
c834fd40f3a86542a2d81ea0297c71d1cf1853fd | JoshMez/Python_Intro | /Dictionary/Empty_Dict.py | 245 | 4.21875 | 4 | #Aim: To learn about empty dictionaries
#
#Creating an empty dictionary.
dict = {} #Put two curly braces. #No space between them.
#
#Adding values to the empty dictionay.
#
dict['Jason'] = 'Blue'
dict['Belle'] = 'Red'
dict['John'] = 'Black'
#
#
| true |
c7136ec6647afc0f3044059082e63a55d80506d5 | JoshMez/Python_Intro | /Programming_Flow/List_Comprehension.py | 298 | 4.25 | 4 | #Basic demonstration of list comprehension.
#Variable was declared.
#List was create with the square brackets.
#value ** 2 was created.
#The a for loop was created ; NOTICE : THere was not the semi:colon as the end.
squares = [ value ** 2 for value in range(1,11) ]
print(squares)
| true |
bfd57f6ad775a8c6cd91ba2db417421d9716a415 | JoshMez/Python_Intro | /Functions/Exercies_8.py | 1,645 | 4.75 | 5 | #8-1. Message: Write a function called display_message() that prints one sentence
#telling everyone what you are learning about in this chapter. Call the
#function, and make sure the message displays correctly.
#Creating a function.
def display_message():
"""Displaying the chapter focuses on"""
print("In this lesson, the focus is on functions.")
#Calling the functions
display_message()
#8-2. Favorite Book: Write a function called favorite_book() that accepts one
#parameter, title. The function should print a message, such as One of my
#favorite books is Alice in Wonderland. Call the function, making sure to
#include a book title as an argument in the function call.
#
#Supplying one parameter
def favorite_book(book):
"""Showing my favorite book"""
print(f"My fav book is {book.title()}")
#Calling the function along with an argument.
favorite_book("alice in wonderland\n\n")
#8.3
#Defining a function called make_shirt()
def make_shirt(size, message):
"""This is the size of the t-shit"""
print(f"Size {size}")
print(f'{message}\n')
make_shirt('M', "Being successful means SECOND BY SECOND")
######
#####
#8.4
def make_shirt(size='large', message='I love Python'):
"""New print """
print(f"Size: {size}")
print(f"{message}\n")
#Calling the function
make_shirt(size='M', message='One second at a time is how you build success.')
######
#8.5
#Creating a function.
def describe_city(city, country="Iceland"):
"""Tells you where you statement is """
print(f"Josh is currently in {city} which is in the {country}")
#Using the definition.
describe_city('Gaborone', country='Botswana')
| true |
f77853c57409d16a7d23731165daa4fb70a2bf20 | JoshMez/Python_Intro | /While_Input/Dict_User_Input.py | 714 | 4.25 | 4 | #Creating an empty dictionary.
#
#Creating an empty dictionary.
responses = {}
#
#Creating a flag.
polling_active = True
####
#
while polling_active:
#Prompting the user for input.
naming = input("Whats your name: ")
response = input("Which mountain do you want to visit: ")
#Store the responses in the dictionary
responses[naming] = response
#Seeing if anyone else want to add.
repeat = input("Do you want to add another person as well, Yes or No: ")
#
if repeat == 'no' or repeat == 'N' or repeat == "No":
print("Ending the program ")
polling_active = False
#
for name,r in responses.items():
print(f"Hi {name}, it looks like you want to visit {r}") | true |
a0f6073ebcf2f8159b91f630968acb177b9b561b | JoshMez/Python_Intro | /Dictionary/Loop_Dict.py | 1,293 | 4.90625 | 5 | #Aim: Explain Loop and Dictionaries.
#
#
#There are several ways to loop through a dictionary.
#Loop through all of Key-pair values.
#Loop through keys only.
#Loop though values only.
#
#
############Example of looping through all dictionary key-pair values####################
#
#Creating a dictionary of a User information.
User_0 = {'username': 'jmez',
'first name' : 'Josh',
'Last name' : 'Mezieres'
}
#Loop through all key-value pair info
#The for loop will contain 2 variable.
#One variable --- The one which comes first represent the Key
#after 1st varaible stated, a comma comes in straight afterwards.
#Then a second variable will be used to define the key.
#Seeing as loop is going through 2 variables. - Add .items(), after the dictionary.
#
for user_cat, info in User_0.items():
print(f"Key: {user_cat.title()}")
print(f"Info: {info}\n\n")
#
#
#
#Think about dictionaries working well for working well with pairs.
#Creating a dictionary with peoples name and programming languages.
Names_Lang = {'jane': 'c',
'arkus': 'python',
'allistair': 'ruby'
}
#
for Name, lang in Names_Lang.items():
print(f"{Name.title()}'s favourite programming language is {lang.title()}\n")
###############
| true |
f95e10517f70584b947de934b5fa33dee7d149bc | JoshMez/Python_Intro | /Dictionary/Nesting_2.py | 601 | 4.1875 | 4 | aliens = []
#Basically creating the variable 30 times over.
#
#The range just tells Python how many times we want to loop and repeat.
#Each time loop occurs, we create a new alien and append it to the new alien list.
for alien in range(30):
new_alien = {'color': 'green',
'points': 5,
'speed': 'slow'
}
aliens.append(new_alien)
#Using slicing to get the the 1st liness of the list.
for alien in aliens[:5] :
print(alien)
########
#How many aliens are there in the list.
print(f"The amout of alients in the list are {len(aliens)}" )
#
#
| true |
1068634872d3d4acb23453519b7f6e3b9069bcae | JoshMez/Python_Intro | /Programming_Flow/Number_Lists.py | 1,243 | 4.53125 | 5 | #Creating lists that contain number in Python is very important.
#Making a list with even numbers in it.
even_numbers = list(range(0,11,2)) #The list function has been used to say that a lists is being created. #Passing the range arguments in that , stating arugments in that.
print(even_numbers)
#Creating a list , with a range of number in them.
#Creating a list of numbers.
numbers = list(range(1, 20+1))
#Printing the list that was created.
print(numbers)
lists = [] #Do not give you variable key definitions.
#Want to create a list of all square numbers, in the given range.
for number in numbers:
lists.append(number ** 2 ) #Number is our temporary variable.
print(list)
print( "*" * 100)
print()
print("This part will focus on functions that are useful when working with lists.")
#Using the min function in A LIST OF numbers.
numbers2 = list(range(1 ,30 + 1 ))
print(numbers2)
min_numbers = min(numbers2)
print(min_numbers)
#Using the max function to find the maximum amount of numbers in a lists.
numbers3 = list(range(1,21))
print(numbers3)
print(max(numbers3))
#Calculating the sum of number in a lists.
numbers4 = list(range(1, 25))
print(numbers4)
print(sum(numbers4))
| true |
38936a50b1ef5570cef7a9cd19e1774ddc7e21ce | shekhar270779/Learn_Python | /prg_OOP-05.py | 2,388 | 4.5625 | 5 | '''
Class Inheritance: Inheritance allows a class to inherit attributes and methods from parent class.
This is useful as we can create subclass which inherits all functionality of parent class, also if required
we can override, or add new functionality to sub class without affecting parent class
'''
class Employee:
sal_hike_per = 4
def __init__(self, fname, lname, sal):
self.fname = fname
self.lname = lname
self.sal = sal
def fullname(self):
return self.fname + ' ' + self.lname
@classmethod
def set_sal_hike_per(cls, per):
cls.sal_hike_per = per
def apply_sal_hike(self):
self.sal = int(self.sal * (1 + self.sal_hike_per/100))
# Create Sub Class engineer which inherits Employee
class Engineer(Employee):
pass
e1 = Engineer('Tom', 'Walter', 30000)
print(e1.fullname())
e1.apply_sal_hike()
print(e1.sal)
class Manager(Employee):
sal_hike_per = 10 # overriding class variable
e2 = Manager("Kim", "Jones", 30000)
e2.apply_sal_hike()
print(f"{e2.fullname()} after salary hike has salary {e2.sal}")
class Developer(Employee):
def __init__(self, fname, lname, sal, main_skill):
super().__init__(fname, lname, sal)
self.main_skill = main_skill
e3 = Developer("Ash", "Watson", 30000, "Python")
print(f"{e3.fullname()} has key skill as {e3.main_skill}")
class Lead(Employee):
def __init__(self, fname, lname, sal, employees=None):
super().__init__(fname, lname, sal)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_employee(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_employee(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_employees(self):
print(f"Team of {self.fullname()}")
for emp in self.employees:
print('--->' + emp.fullname())
e4 = Lead("Ashley", "King", 30000, [e1])
print(f"{e4.fullname()} ")
e4.print_employees()
print(f"Adding employees to team of {e4.fullname()}")
e4.add_employee(e2)
e4.add_employee(e1)
e4.print_employees()
print(f"Removing {e1.fullname()} from team of {e4.fullname()}")
e4.remove_employee(e1)
e4.print_employees()
| true |
8bdc82cc4590b320da4b8f2e8462b3db0960ea59 | andu1989anand/vtu-1sem-cpl-lab-in-python | /palindrome1.py | 450 | 4.34375 | 4 | print "\n Python program to reverse a given integer number and check whether it is a"
print "PALINDROME or not. Output the given number with suitable message\n\n"
num=input("Enter a valid integer number:")
temp = num
rev=0
while(num != 0):
digit=num % 10
rev=rev * 10 + digit
num=num / 10
print "\n\n The reversed number",rev
if(temp == rev):
print "\n The number is PALINDROME\n"
else:
print "\n The number is not PALINDROME\n"
| true |
eaa8e5da435544cd8e07457a6e90e79c5a59591c | pilifengmo/Electrical-Consumption-Prediction-System | /PROJECT/website/model.py | 1,776 | 4.125 | 4 | import sqlite3 as sql
class Database(object):
""" Create database if not exist """
def __init__(self):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("create table if not exists users (id integer primary key autoincrement, username text not null UNIQUE, email text not null UNIQUE, password text not null)")
con.close()
""" Insert new user into the database """
def insertUser(self, username, email, password):
con = sql.connect("database.db")
try:
cur = con.cursor()
cur.execute("INSERT INTO users (username,email,password) VALUES (?,?,?)", (username,email,password))
con.commit()
except sql.IntegrityError as err:
con.close()
return 0
finally:
con.close()
""" Get records of all the users in the database """
def retrieveUsers(self):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("SELECT username,email, password FROM users")
users = cur.fetchall()
con.close()
return users
""" Get an active user """
def activeUser(self, email, password):
con = sql.connect("database.db")
try:
cur = con.cursor()
cur.execute("SELECT email, password FROM users WHERE email = '" + email + "' AND password = '" + password + "'")
users = cur.fetchall()
return users
except sql.Error as err:
con.close()
return 0
finally:
con.close()
""" Is user valid """
def isUserValid(self, email, password):
if len(self.activeUser(email,password)) > 0:
return True
return False
| true |
e9d5619d853a46cfe7f3e26f693d56ae14768567 | hashncrash/IS211_Assignment1 | /assignment1_part2.py | 559 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"IS 211 Assignment 1, part 2. Dave Soto"
class Book(object):
author = " "
title = " "
"Book Class information"
def __init__(self, author, title):
self.author = author
self.title = title
"Function to dsiplay the book author and title"
def display(self):
bookinfo = '"{}, written by {}"'.format(self.title, self.author)
print bookinfo
BOOK_1 = Book('John Steinbeck', 'Of Mice and Men')
BOOK_2 = Book('Harper Lee', 'To Kill a Mockingbird')
BOOK_1.display()
BOOK_2.display()
| true |
d5ed2a5b8c599a693c41178f7096995589fa4dc0 | s290717997/Python-100-Days | /day1-15/day7/day7_5.py | 657 | 4.25 | 4 | #练习5:计算指定的年月日是这一年的第几天
days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def if_leap_year(year):
if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:
return True
else:
return False
def which_day(year, month, day):
sum = 0
for i in range(1, month):
sum += days_of_month[i-1]
if i == 2 and if_leap_year(year):
sum += 1
pass
return sum + day
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == '__main__':
main() | true |
e2defc1b4568b4f52e7c4ac3249d6a67e17275b6 | Krashex/pl | /Chapter5/DaddyChooseGame.py | 2,264 | 4.53125 | 5 | pairs = {'Oleg': 'Petr',
'Artur': 'Denis',
'Ivan': 'Petr'}
choice = None
print("""
Type 1 - if you want to know smb's father's name
Type 2 - if you want to add new pairs
Type 3 - if you want to remove sm pair
Type 4 - if you want to change sm pair
Type 5 - if you want to show all pairs
Type 6 - if you want to see the table
Type 7 - if you want to quit.
P.S. Be careful and don't give same names to sons!""")
while choice != 7:
choice = int(input('Type number: '))
if choice == 1:
answer = input("Type son's name: ")
if answer not in pairs:
print('There is no such a name, if you want to add pair press 2')
else:
print(pairs[answer], 'is the', answer + "'s", 'father')
elif choice == 2:
new_son = input("Type new son's name: ")
new_father = input("Type new father's name: ")
pairs[new_son] = new_father
elif choice == 3:
print("Type son's name and you'll delete pair with this son")
removed = input('Enter name: ')
if removed in pairs:
del pairs[removed]
else:
print("There is no such a name...")
elif choice == 4:
change = input("Type son's name in pair that you want to change: ")
if change in pairs:
new_name = input("Now type new father's name: ")
pairs[change] = new_name
else:
print("There is no such a name...")
elif choice == 5:
for item in pairs.items():
print(item[0] + " " + item[1])
elif choice == 6:
print("""
Type 1 - if you want to know smb's father's name
Type 2 - if you want to add new pairs
Type 3 - if you want to remove sm pair
Type 4 - if you want to change sm pair
Type 5 - if you want to show all pairs
Type 6 - if you want to see the table
Type 7 - if you want to quit.
P.S. Be careful and don't give same names to sons!""")
elif choice == 7:
break
else:
print("There is no such a number...")
| true |
632144ea0c2dc95a6a87d20d642528339be71a52 | wilcerowii/mtec2002_assignments | /class10/labs/exceptions.py | 1,367 | 4.21875 | 4 | """
exceptions.py
=====
To handle errors, use a try/catch block:
-----
try:
# do your stuff
except SomeError:
# deal with some error
-----
optionally... you can continue catching more than one exception:
-----
.
.
except AnotherError:
# deal with another error
-----
Substitute SomeError with the kind of error you want to handle - for example:
KeyError
ValueError
TypeError
IndexError
ZeroDivisionError
"""
#KeyError
d = {"shape":"circle"}
print d =['shape']
print d['color']
except keyError: 'color'
print "that key doesn't exist!!!!"
print "done"
#ValueError (conversion errors)
try:
print int("this is not a number")
except ValueError:
print "it dont thats a number"
#TypeError
type:
print "foo" * "bar"
except TypeError:
print "you cant multiply by that"
#IndexError
my_list = ["same", "stuff"]
try:
print my_list[2]
except IndexError:
print "that index is out of range"
#ZeroDivisionError
try:
5 / 0
except ZeroDivisionError
print "that's a no-no"
#catching multiple possible exceptions - try possible KeyError AND TypeError
like dictionary value divided by another value
#ex... which player do you want to add a score to, and add that score
d = {"score":10}
k = "score"
divisor = 2
try:
print d[k] / divisor
except:KeyError:
print "thatkey doesnt exist"
except:ZeroDivisionError:
print "you cant divide by zero"
| true |
90952d5c964ca74bb1c221b4cf93395799f1f564 | jbrownxf/mycode | /wk1proj/gotime2 | 1,544 | 4.1875 | 4 | #!/usr/bin/env python3
#imports
import random
#This is a board game. Every player rolls a dice from 1-12 first to 100 wins
#By Josh Brown
from random import randint
#ask for number of players, creates a dic for every player
num_player = input("How many will be playing Dicequest?(2-6 players) ")
num_players =int(num_player) + 1 #allows me to start numbering players at 1 instead of 0
#takes the input value from user and turns it into an append list
list_players = []
for x in range(1, num_players):
list_players.append('Player ' + str(x))
print(list_players)
mylist = []
## creating dictionaries with proper strcutures
for x in range(len(list_players)):
dic = {'name': list_players[x], 'score' : 0}
mylist.append(dic)
print(mylist)
##dice roll code
min = 1
max = 6
## while loop that will increase the players score with a dice roll function until score 100 is met
##I need a way to call the name value first and then roll the dice
## use a for loop with a +1 to cycle through values of 'name'
win=False
while win != True:
for turn in range(len(list_players)):
roll= (random.randint(min, max))
print(mylist[turn]['name'] + ' rolled ' + str(roll))
mylist[turn]['score'] += roll #(random.randint(min, max))
print(mylist[turn]['name'] + ' is at ' + str(mylist[turn]['score']))
if mylist[turn]['score'] >= 15:
print('The winner is ' + mylist[turn]['name'] + ' with a score of ' + str(mylist[turn]['score']) + '!')
win = True
break
| true |
f745f56706575fc6f3e565b026029103c51cca4a | adnanhanif793/Python-Codes | /Basic/com/Anagram.py | 448 | 4.1875 | 4 | '''
Created on 18-Mar-2019
@author: adnan.hanif
'''
def check(s1, s2):
# the sorted strings are checked
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
# driver code
n=int(input("Enter the number of terms"))
i=0
while(i<n):
s1 =input("enter first")
s2 =input("enter second")
check(s1, s2) | true |
3043d49c09e87ff59adc9386745996dbfeccf057 | jonalynnA-cs29/Intro-Python-I | /src/05_lists.py | 2,269 | 4.53125 | 5 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
'''
Python List append()
Add a single element to the end of the list
Python List extend()
Add Elements of a List to Another List
Python List insert()
Inserts Element to The List
Python List remove()
Removes item from the list
Python List index()
returns smallest index of element in list
Python List count()
returns occurrences of element in a list
Python List pop()
Removes element at the given index
Python List reverse()
Reverses a List
Python List sort()
sorts elements of a list
Python List copy()
Returns Shallow Copy of a List
Python List clear()
Removes all Items from the List
Python any()
Checks if any Element of an Iterable is True
Python all()
returns true when all elements in iterable is true
Python ascii()
Returns String Containing Printable Representation
Python bool()
Converts a Value to Boolean
Python enumerate()
Returns an Enumerate Object
Python filter()
constructs iterator from elements which are true
Python iter()
returns an iterator
Python list()
creates a list in Python
Python len()
Returns Length of an Object
Python max()
returns the largest item
Python min()
returns the smallest value
Python map()
Applies Function and Returns a List
Python reversed()
returns the reversed iterator of a sequence
Python slice()
returns a slice object
Python sorted()
returns a sorted list from the given iterable
Python sum()
Adds items of an Iterable
Python zip()
Returns an iterator of tuples
'''
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
x.insert(5, 99)
print(x)
# Print the length of list x
print(len(x))
# Print all the values in x multiplied by 1000
for num in x:
print(num * 1000) # This is the preferred method for something this simple
# List Comprehension is better (less code) for things that are more complicated
x1000 = [n * 1000 for n in x]
# ^^^^^^^^^ ^^^^^ ^^^^
# output input filter
print(x1000)
| true |
698c957da6315ef6124c57ca3b22aa7a6776df0b | nshattuck20/Data_Structures_Algorithms1 | /ch9/9-1.py | 630 | 4.59375 | 5 | '''
Section 9-1:
Recursive Functions
'''
#Example of recursive function
#I used the code from the animation example in the course material
def count_down(count):
if count == 0:
print('Go!')
else:
print(count)
count_down(count -1)
count_down(2) # recursively call count_down 3 times.
#Another example is a program that prints alphabet backward
def backward_aplhabet(current_letter):
if current_letter == 'a':
print(current_letter)
else:
print(current_letter)
prev_letter = chr(ord(current_letter) - 1)
backward_aplhabet(prev_letter)
starting | true |
efcb7864f7ec7260c361402910aea5a5b9cbb091 | nshattuck20/Data_Structures_Algorithms1 | /ch8/8-6.py | 347 | 4.46875 | 4 | '''
8-6 List Comprehensions:
Form:
new_list = [expression for name in iterable]
3 components:
1. The expression to evaluate each iterable component
2. A loop variable to bind to the components
3. An iterable object
'''
#Example
my_list = [5, 10, 15]
my_list_plus5 = [(i + 5) for i in my_list]
print('New list contains' , my_list_plus5) | true |
17786b5a311cfbb8e4c2e56f7bf0e9ce35e9269a | nshattuck20/Data_Structures_Algorithms1 | /ch9/9-5-1.py | 874 | 4.40625 | 4 | '''
9-5-1
Write a program that outputs the nth Fibonacci number, where n is a
user-entered number. So if the user enters 4, the program should
output 3 (without outputting the intermediate steps).
Use a recursive function compute_nth_fib that takes n as
a parameter and returns the Fibonacci number.
The function has two base cases: input 0 returns 0, and input 1 returns 1.
'''
def compute_nth_fib(num):
# if base case ...
if num == 0 or num == 1:
return num
else:
return compute_nth_fib(num-1) + compute_nth_fib(num-2)
# return print(compute_nth_fib(num))
print('This program will find the nth Fibonacci \n'
'number. Example: entering 4 returns 3, because\n'
'3 is the 4th number in the Fibonacci sequence.\n')
nth_number = int(input('Which number would you like to find?'))
print(compute_nth_fib(nth_number)) | true |
148c9c7ffecb1938db146f2c7e263e82bdfb741e | nshattuck20/Data_Structures_Algorithms1 | /Chapter4/4.9/dictionary_basics.py | 451 | 4.34375 | 4 | '''
Simple program demonstrating the basics of Dictionaries.
'''
players = {'Lionel Messi' : 10,
'Cristiano Ronaldo' : 7
}
print(players)
#Accessing an entry uses brackets [] with the specified key
print('The value of this player is :' + str(players['Cristiano Ronaldo']))
#Editing the value of an entry
players['Lionel Messi'] = 11
print(players)
#Adding an entry
players['Cristian Pulisic'] = 22
print(players)
#Deleting an entry
del players['Lionel Messi']
print(players) | true |
1fa915224e3880af57d0012bd843a6d76dc184ad | nshattuck20/Data_Structures_Algorithms1 | /ch7/7-7.py | 1,097 | 4.71875 | 5 | '''Class customization
* Referes to how classes can be altered by rhe
programmer to suit her needs.
* _str_() changes how to print the output of an object
'''
class Toy:
def __init__(self, name, price, min_age):
self.name = name
self.price = price
self.min_age = min_age
truck = Toy('Monster Truck X', 14.99, 5)
print(truck) # print the memory address of truck
class Toy:
'''
Using the __str__() special method name to change
the output of the Toy object.
'''
def __init__(self, name, price, min_age):
self.name = name
self.price = price
self.min_age = min_age
def __str__(self):
return ('%s costs only $%.2f. Not for children under %d!' %
(self.name, self.price, self.min_age))
truck = Toy('Monster Truck X', 14.99, 5)
print(truck)
'''
Operator overloading using rich comparison methods:
__lt__(self, other) less-than(<)
__gt__(self, other) greater-than(>)
__le__(self, other) less-than or equal-to(<=)
__ge__(self, other) greater-than or equal-to(>=)
__eq__(self, other) equal to (==)
__ne__(self, other) not-equal to (!=
)
''' | true |
906a5fdf384a4825b3cfa126777f35b9d1cb0b4c | mattprodani/letter-box | /Dictionary.py | 1,049 | 4.15625 | 4 | class Dictionary():
def __init__(self, dictionary, gameboard):
""" Builds a dictionary object containing a list of words as well as groups them into a Dictionary
separated by starting letter, where starting letters are in gameboard.
"""
wordList = []
self.wordGroups = {}
# Converts text file to list
# Populates a dictionary with word groups based on length
for line in dictionary:
word = line.strip().upper()
if word[0] in gameboard.getGameboard():
if word[0] in self.wordGroups.keys():
self.wordGroups[word[0]].append(word)
else:
self.wordGroups[word[0]] = [word]
def getKeys(self):
""" Returns a list of valid keys corresponding to groups by starting letter """
return sorted(list(self.wordGroups.keys()), reverse = True)
def getWords(self, key):
""" Gets words from dictionary starting with a given letter """
return self.wordGroups[key]
| true |
e0638d35fea87b4176d06cc0e33f136a805b7554 | CB987/dchomework | /Python/Python104/blastoff3.py | 237 | 4.1875 | 4 | # countdown that asks user where to start
n = int(input("From what number should start our countdown?")) #getting user input
while n >= 0: #setting end condition
print(n) #instructing to print number
n -=1 #incrementing downwards | true |
59c6d6de128a455c43a756ff527d25ce053e15ca | CB987/dchomework | /Python/Python104/blastoff2.py | 365 | 4.4375 | 4 | # create a countdown from 10 to 0, then prints a message
n = 10 #start point of countdown
while n >= 0: # set duration of countdown
print(n) #printing the number
n -=1 #Incrementing down, sends back up to print. loops until condition is false
if n < 0: #instructing when to print the message
print("May the Force Be With You") #print the message | true |
f675d32ecf2cf6d0afef4b975674d4adfdfd0bb2 | alisheryuldashev/playground | /Python/classes.py | 780 | 4.4375 | 4 | #this snippet shows how to create a class in Python.
#this program will prompt for information, append same into a class, and output a message.
#create a class called Student
class Student:
def __init__(self,name,dorm):
self.name = name
self.dorm = dorm
#import custom functions from CS50 library used in Harvard Introduction to Computer Science course.
from cs50 import get_string
#import class Student
from test14class import Student
students = []
dorms = []
#prompt user for information and append it to the class called Student
for i in range(3):
name = get_string("Name: ")
dorm = get_string("Dorm: ")
s = Student(name, dorm)
students.append(s)
for student in students:
print(f"{student.name} lives in {student.dorm}")
| true |
d56bdfbf76c0cbbce6c42a98844db12474e9c51b | Sandhie177/CS5690-Python-deep-learning | /ICP3/symmetric_difference.py | 610 | 4.28125 | 4 | # -*- coding: utf-8 -*-
#A={1,2,3,4}
#B={1,2}
def list1():
n=eval(input("How many numbers do you have in the list?")) #takes number of elements in the list
i=0
list1={0} #creating an empty set
list1.remove(0)
for i in range(n):
x=int(input("enter a number\n"))
list1.add(x) #adding new numbers to the list
print("the list is",list1) #prints the list
return list1 #returns the list
A=list1() #calls the function list1 to take input list A
B=list1() #calls the function list1 to take input list B
print ("the symmetric difference between set A and B is:", A^B)
| true |
015efad385e902e83ba1d21e2e4e7bf86d29a5a2 | Sandhie177/CS5690-Python-deep-learning | /Assignment_1/Assignment_1c_list_of_students.py | 1,271 | 4.4375 | 4 | #Consider the following scenario. You have a list of students who are attending class "Python"
#and another list of students who are attending class "Web Application".
#Find the list of students who are attending “python” classes but not “Web Application”
#function to create list
def list1():
n=eval(input("Student number:")) #takes number of elements in the list
i=0
list1=[] #creating an empty set
#list1.remove(0)
for i in range(n):
x=str(input("enter name\n"))
list1.append(x) #adding new members to the list
print("the list of student is",list1) #prints the list
return list1 #returns the list
#creating function to find out the difference
def Diff(li1, li2):
#converting the list into set and substracting
return (list(set(li1) - set(li2)))
#creating python database
print ("For python class,") #mentioning the name of class
python=list1() #calls the function list1 to take input for python class
#creating web_application database
print ("\n For web application class,") #mentioning the name of class
web_app=list1() #calls the function list1 to take input for web application class
d = (Diff(python, web_app))
print ("the list of students who are taking python but not web application is:", d) | true |
5c267a5620aa7a658ccdb79e677f3998207756a3 | sciencefixion/HelloPython | /Hello - Basics of Python/sliceback.py | 857 | 4.28125 | 4 | letters = "abcdefghijklmnopqrstuvwxyz"
backwards = letters[25:0:-1]
print(backwards)
backwards2 = letters[25::-1]
print(backwards2)
# with a negative step the start and stop defaults are reversed
backwards3 = letters[::-1]
print(backwards3)
# Challenge: Using the letters string add some code to create the following slices
# create a slice that produces the characters "qpo"
# slice the string to produce "edcba"
# slice the string to produce the last 8 characters in reverse order
slice1 = letters[-10:-13:-1]
slice2 = letters[-22::-1]
slice3 = letters[-1:-9:-1]
print(slice1)
print(slice2)
print(slice3)
# alternate solution
print(letters[16:13:-1])
print(letters[4::-1])
print(letters[:-9:-1])
# defaults for the stop and step values
print(letters[-4:])
print(letters[-1:])
# defaults for the start and step
print(letters[:1])
print(letters[0])
| true |
4b1b47754908d1408d23be833869d656231ec113 | casanova98/Project-201501 | /Practical one/q1_fahrenheit_to_celsius.py | 232 | 4.21875 | 4 |
#q1_fahrenheit_to_celsius.py
answer = input("Enter the temperature you want in Celsius!")
x = float(answer)
celsius = round((5/9) * (x - 32), 1)
print("The temperature from Fahrenheit to Celsius to 1 decimal place is", celsius)
| true |
9d2ef8e3764b1709b9dfcbf68bb4af5bd4b64eae | casanova98/Project-201501 | /Practical two/q08_top2_scores.py | 552 | 4.125 | 4 |
students = int(input("Enter number of students: "))
names = []
score = []
while students != 0:
names.append(str(input("Enter your name: ")))
score.append(int(input("Enter your score: ")))
students -= 1
highest = max(score)
print("Student with highest score is:", names[score.index(highest)], "with a score of:", highest)
names.pop(score.index(highest))
score.pop(score.index(highest))
highest2 = max(score)
print("Student with second highest score is:", names[score.index(highest2)], "with a score of:", highest2)
| true |
783d04424384829bec20a0b6d4dddca93f46e3ae | Smily-Pirate/100DaysOfCode | /Day1.py | 971 | 4.125 | 4 | # Day1 of 100 days of coding.
# Starting from list.
# Accessing Values in Lists.
list1 = ['hi', 'there', 18, 1]
list2 = [1, 2, 3, 4, 5, 6, 7, 8]
print(list1[0])
print(list2[2])
# Updating list
list1[0] = 'ghanshyam'
list1[1] = 'joshi'
list2[7] = 'hi'
print(list1)
print(list2)
list1.append('10')
print(list1)
# Deleting List element
del list1[3]
del list2[7]
print(list1)
print(list2)
# Basic List Operations
# length
value = [1, 2, 'hi']
print(len(value))
print(len([1, 8, 'ji']))
# Concatenation
notvalue = [5, 'no']
new_value = value + notvalue
print(new_value)
# Repetition
hi = ['hi']
print("Value: " +str(hi )* 4 )
# Membership
values = 3
if values in value:
print("Yes")
else:
print("no")
# Iteration
for x in [1, 2, 3, 4]:
print(x)
# Slicing
number = [1, 2, 3, 4]
print(number[4:])
# Function len()
print(len(number))
# Function max()
print(max(number))
# Function min()
print(min(number))
# Function list
no = {'a', 'b'}
print(list(no)) | true |
49ba616fc87d3f9287ef22e444a7b872839f1aa7 | Akshay-Chandelkar/PythonTraining2019 | /Ex21_Arthimetic.py | 1,458 | 4.125 | 4 |
print("Free fall code to begin")
def add(num1,num2):
sum = num1 + num2
print("The sum of two numbers is : ", sum)
def sub(num1,num2):
sub = num2 - num1
print("The difference between the two numbers is : ", sub)
def mul(num1,num2):
mul = num1 * num2
print("The multiplication of the two numbers is : ", mul)
def div(num1,num2):
div = num2/num1
print("The division of the two numbers is :", div)
def Menu():
while True:
print("1. Add\n2. Substract\n3. Multiply\n4. Division\n5. Exit")
choice = int(input("Enter your choice :: "))
if(choice > 0 and choice <6):
return choice
else:
print("Please enter the correct choice.")
def ArithmaticOperations(num1,num2):
choice = 0
while choice != 5:
choice = Menu()
if(choice == 1):
add(num1,num2)
elif (choice == 2):
sub(num1,num2)
elif (choice == 3):
mul(num1,num2)
elif (choice == 4):
div(num1,num2)
elif (choice == 5):
break
else:
Menu()
def main():
num1 = int(input("Please enter first number : "))
num2 = int(input("Please enter second number : "))
ArithmaticOperations(num1,num2)
#add(num2=30,num1=10)
#sub(num1,num2)
#mul(num1,num2)
#div(num1,num2)
if __name__ == '__main__':
main()
| true |
c57f2c473a90a15353b101a8bd2e6b8f4031ceb3 | Akshay-Chandelkar/PythonTraining2019 | /Ex64_Stack_List.py | 2,492 | 4.125 | 4 | def IsStackFull(L1):
if IsStackEmpty(L1):
print("\nThe stack is empty.\n")
elif len(L1) >= 6:
return True
else:
print("\nThe stack is not full.\n")
def IsStackEmpty(L1):
if L1 == []:
return True
else:
return False
def Push(L1):
if not IsStackFull(L1):
no = eval(input("\nEnter the element to push in the stack :: "))
L1.append(no)
else:
print("\nSorry cant add an element as the stack is full\n")
return L1
def Pop(L1):
if not IsStackEmpty(L1):
print("\nRemoved the element {} from top of the stack\n ".format(L1.pop()))
else:
print("\nSorry cant remove an element as the stack is empty.\n")
def Peep(L1):
if not IsStackEmpty(L1):
print("\nThe current top of the stack element is {}\n".format(L1[len(L1)-1]))
else:
print("\nSorry the stack is empty.\n")
def Display(L1):
if not IsStackEmpty(L1):
print("\nThe current stack is {}\n".format(L1))
else:
print("\nThe stack is empty.\n")
'''
def DeleteStack(L1):
if not IsStackEmpty(L1):
del(L1)
print("The stack deleted successfully.")
else:
print("The stack is empty.")
'''
def menu(L1):
#choice = 0
while True:
print("Enter the stack operation ::\n1. Push\n2. Pop\n3. IsStackFull\n4. IsStackEmpty\n5. Peep\n6. Display\n7. DeleteStack\n8. Exit\n")
choice = eval(input("Enter your choice :: "))
if choice == 1:
Push(L1)
elif choice == 2:
Pop(L1)
elif choice == 3:
if IsStackFull(L1):
print("\nThe stack is full.\n")
elif choice == 4:
if IsStackEmpty(L1):
print("\nThe stack is empty.\n")
else:
print("\nThe stack is not empty.\n")
elif choice == 5:
Peep(L1)
elif choice == 6:
Display(L1)
elif choice == 7:
if not IsStackEmpty(L1):
del(L1)
print("\nThe stack deleted successfully.\n")
else:
print("\nThe stack is empty.\n")
L1 = []
elif choice == 8:
break
else:
print("\nYou have entered an invalid choice.\n")
def main():
print("Create a stack \n")
L1 = []
menu(L1)
if __name__ == '__main__':
main() | true |
d8dc56075b59c4790ef758177723e44a2b09bf8f | vonnenaut/coursera_python | /7 of 7 --Capstone Exam/probability.py | 854 | 4.21875 | 4 | # Fundamentals of Computing Capstone Exam
# Question 12
def probability(outcomes):
""" takes a list of numbers as input (where each number must be between 1 and 6 inclusive) and computes the probability of getting the given sequence of outcomes from rolling the unfair die. Assume the die is rolled exactly the number of times as the length of the outcomes input. """
total_rolls = len(outcomes)
individual_probabilities = [0.1, 0.2, 0.3, 0.15, 0.05, 0.2]
lt_sum = 0 # sum of likelihood of a value times that value times the total number of rolls
probability = 1
for idx in range(len(outcomes)-1):
probability *= individual_probabilities[outcomes[idx]-1]
return probability
print probability([4, 2, 6, 4, 2, 4, 5, 5, 5, 5, 1, 2, 6, 2, 6, 6, 4, 6, 2, 3, 5, 5, 2, 1, 5, 5, 3, 2, 1, 4, 4, 1, 6, 6, 4, 6, 2, 4, 3, 2, 5, 1, 3, 5, 4, 1, 2, 3, 6, 1]) | true |
56555a338b03786e7de3d8cd5546f8d3b5f65158 | vonnenaut/coursera_python | /7 of 7 --Capstone Exam/pick_a_number.py | 1,280 | 4.15625 | 4 | # Fundamentals of Computing Capstone Exam
# Question 17
scores = [0,0]
player = 0
def pick_a_number(board):
""" recursively takes a list representing the game board and returns a tuple that is the score of the game if both players play optimally by choosing the highest number of the two at the far left and right edge of the number list (board)
returns a tuple with current player's score first and other player's score second """
global player
start = 0
end = len(board)
print "board:", board
# base case
if len(board) == 1:
print "\n\n---base case reached---"
return board
print "\n\n------ recursive case ------"
print "board:", board
print "board[0]:", board[0]
print "board[len(board)-1]:", board[len(board)-1]
if board[0] >= board[len(board) - 1]:
print "True"
choice = board[0]
start = 1
else:
print "False"
choice = board[len(board)-1]
end -= 1
print "board[start:end]:", board[start:end]
pn_helper(player, choice)
if player == 0:
player = 1
else:
player = 0
return pick_a_number(board[start:end])
def pn_helper(player, value):
global scores
scores[player] += value
print "scores:", scores
print pick_a_number([5,2,3,1])
# print pick_a_number([12, 9, 7, 3, 4, 7, 4, 7, 3, 16, 4, 8, 12, 1, 2, 7, 11, 6, 3, 9, 7, 1]) | true |
dcceddfae83a164aeae8bfa0fdb6177fad4b90de | vonnenaut/coursera_python | /2 of 7 -- Intro to Interactive Programming with Python 2/wk 6/quiz_6b_num8.py | 2,021 | 4.34375 | 4 | """
We can use loops to simulate natural processes over time. Write a program that calculates the populations of two kinds of “wumpuses” over time.
At the beginning of year 1, there are 1000 slow wumpuses and 1 fast wumpus. This one fast wumpus is a new mutation. Not surprisingly, being fast gives it an advantage, as it can better escape from predators.
Each year, each wumpus has one offspring. (We'll ignore the more realistic niceties of sexual reproduction, like distinguishing males and females.). There are no further mutations, so slow wumpuses beget slow wumpuses, and fast wumpuses beget fast wumpuses. Also, each year 40% of all slow wumpuses die each year, while only 30% of the fast wumpuses do.
So, at the beginning of year one there are 1000 slow wumpuses. Another 1000 slow wumpuses are born. But, 40% of these 2000 slow wumpuses die, leaving a total of 1200 at the end of year one. Meanwhile, in the same year, we begin with 1 fast wumpus, 1 more is born, and 30% of these die, leaving 1.4. (We'll also allow fractional populations, for simplicity.)
Beginning of Year Slow Wumpuses Fast Wumpuses
1 1000 1
2 1200 1.4
3 1440 1.96
… … …
Enter the first year in which the fast wumpuses outnumber the slow wumpuses. Remember that the table above shows the populations at the start of the year.
"""
year = 2
num_slow_wumpuses = 1000
num_fast_wumpuses = 1
def YearoftheFastWumpus(year, num_slow_wumpuses, num_fast_wumpuses):
while num_slow_wumpuses > num_fast_wumpuses:
num_slow_wumpuses = 2 * (num_slow_wumpuses - (num_slow_wumpuses * 0.4))
num_fast_wumpuses = 2 * (num_fast_wumpuses - (num_fast_wumpuses * 0.3))
print "Year: " + str(year) + "\n# Slow: " + str(num_slow_wumpuses) + "\n# Fast: " + str(num_fast_wumpuses)
year += 1
return "Fast wumpuses overtake on year " + str(year)
print YearoftheFastWumpus(year, num_slow_wumpuses, num_fast_wumpuses)
## #1 36.5 49
## #2 912.5 343
## #7 168
## #8 46 (must be 45 or 47) | true |
c9d3d1735eadee86c6601193da7690ed39d6e472 | 777shipra/dailypython | /assignment_acadview/question_9.py | 255 | 4.125 | 4 | sentence=raw_input("enter your sentence :")
uppercase_letters=0
lowercase_letters=0
for x in sentence:
if x.isupper():
uppercase_letters +=1
elif x.islower():
lowercase_letters +=1
print uppercase_letters
print lowercase_letters
| true |
b67904bd5415cde5c5ddc1a4e1cb121c47778274 | 777shipra/dailypython | /enumerate.py | 261 | 4.25 | 4 | choices=['pizza','ice','nachos','trigger']
for i,item in enumerate(choices):
print i,choices #prints the whole list
print i,item #prints the content of the list
for i,items in enumerate (choices,1):
print i,items #begins the itteration from index 1
| true |
c222489968812c65d58847cbe1b7780f9f620b4c | elormcent/centlorm | /conditional.py | 542 | 4.21875 | 4 | i = 6
if(i % 2 == 0):
print ("Even Number")
else:
print ("Odd Number")
def even():
number = int(input("Enter a whole number :- "))
if (number > 0 % 2 == 0):
print("It\'s an even number, nice work")
elif (number > 0 % 2 == 1):
print("it\'s an odd number, good job")
elif (number == 0):
print("you entered \'0' 'Zero'")
elif (number < 0 ):
print("you entered a negetive number")
else:
print("Enter a number greater than \'0' 'Zero'")
even()
| true |
e40b81ba5afa39fdfe0b6384a5802695f53b1662 | olivianauman/programming_for_informatics | /untitled-2.py | 995 | 4.40625 | 4 | # turtle trys
import turtle # set window size
turtle.setup(800,600)
# get reference to turtle window
window = turtle.Screen()
# set window title bar
window.title("making a shape")
# set background color
window.bgcolor('purple')
the_turtle = turtle.getturtle()
# default turtle # 3 attributes: positioning, heading (orientation), pen
# creating a box with relative positioning
the_turtle.hideturtle()
# to see the turtle or not to see. #the_turtle.forward(100) # relative positioning
# the turtle starts by looking to the right (0 degrees)
the_turtle.setposition(100, 0)
# absolute positioning the_turtle.left(90) # turning 90 degrees to the left #the_turtle.setheading(135) # explicitly lookig in the 90 deg angle # see what happends when you change 90 above to something else
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
# exit on close window
turtle.exitonclick() | true |
a4c327eb87a6b535eeb6a6750f86279eedf0b16b | peterlulu666/CourseraStartingWithPython | /Assignment 4.6.py | 1,064 | 4.4375 | 4 | # 4.6 Write a program to prompt the user for
# hours and rate per hour using input to
# compute gross pay. Pay should be the
# normal rate for hours up to 40 and time-and-a-half
# for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function
# called computepay() and use the function to do the
# computation. The function should return a value.
# Use 45 hours and a rate of 10.50 per hour to test
# the program (the pay should be 498.75). You should
# use input to read a string and float() to convert
# the string to a number. Do not worry about error
# checking the user input unless you want to - you
# can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
def computepay(h, r):
h = float(h)
r = float(r)
if h <= 40:
pay = h * r
else:
pay = 40 * r + (h - 40) * r * 1.5
return pay
hrs = float(input("Enter Hours:"))
rate_per_hour = float(input("Enter rate per hour:"))
p = computepay(hrs, rate_per_hour)
print("Pay", p)
| true |
43141dce566e017494468bec1d4ff2d904f45477 | RekidiangData-S/SQLite-Project | /sqlite_App/app.py | 751 | 4.15625 | 4 | import database
#database.create_db()
def main():
print("""
WELCOME TO STUDENTS DATABASE
############################
Select Operation :
(1) for create Table
(2) for Add Record
(3) for Show Records
(4) for Delete Records
(5) for Records Selection
""")
operation = input("Enter your Choice : ")
if operation == "2":
database.add_record()
elif operation == "3":
database.show_all()
elif operation == "4":
database.delete_one(id)
elif operation == "5":
database.select()
elif operation == "1":
print("Please Contact DataBase Admonistrator for this Operation")
else:
print("Try again !!")
main()
#database.add_record()
#database.show_all()
#database.delete_one(id) | true |
d13dcf6e579b458d12f013700eb760936d9f2e4c | cubicova17/Python_scripts | /fib.py | 936 | 4.21875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose: FibNumbers
#
# Author: Dvoiak
#
# Created: 07.10.2014
# Copyright: (c) Dvoiak 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
def fib(x):
"""Recursive function of Fibonacci number"""
if x==0:
return 0
elif x==1:
return 1
else:
return fib(x-1)+fib(x-2)
def fib2(x):
"""Making a list of "x" fib numbers (not recursive)
Returns a list of fib numbers"""
l = [0,1]
while len(l)<=x:
l.append(l[-1]+l[-2])
return l
def fib3(x):
"""Another way to get fib number (not recursive)"""
a = 0
b = 1
for i in range(x-1):
a,b = b,a+b
return b
def main():
N = 7
print fib(N)
print fib2(N)
print fib3(N)
if __name__ == '__main__':
main() | true |
b882a6c8f38065b75d2fdeff2c640cc84ac731f4 | kimchison/HardWay | /ex30.py | 424 | 4.125 | 4 | people = 20
cars = 40
buses = 50
if cars > people:
print "We should take the cars..."
elif cars < people:
print "We should not take the cars..."
else:
print "We can't decide."
if buses > cars:
print "Thats too many buses"
elif buses < cars:
print "Maybe we could take the buses"
else:
print "We still can't decide"
if people > buses:
print "Lets just take the buses"
else:
print "Fine, lets stay at home then..." | true |
576672d0fdacac1002b6d96deed88c7ada514fd4 | mschruf/python | /division_without_divide_operation.py | 1,493 | 4.3125 | 4 | def divide(numerator, denominator, num_decimal_places):
"""Divides one integer by another without directly using division.
Args:
numerator: integer value of numerator
denominator: integer value of denominator
num_decimal_places: number of decimal places desired in result
Returns:
- Type 'float' containing result of division to specified number of
decimal places; final digit not rounded
Raises:
ValueError: if 'denominator' is zero or 'num_decimal_places' is not
positive integer
"""
if denominator == 0 or num_decimal_places < 0:
raise ValueError
pieces = []
# determine sign of final number, then make both numerator and denominator
# positive for simplicity
sign = 1
if numerator < 0:
sign = -sign
numerator = -numerator
if denominator < 0:
sign = -sign
denominator = -denominator
if sign < 0:
pieces.append('-')
# determine integral part
num_units = 0
while numerator >= denominator:
numerator -= denominator
num_units += 1
pieces.append(str(num_units))
pieces.append('.')
# determine fractional part
for _ in range(num_decimal_places):
numerator *= 10
num_units = 0
while numerator >= denominator:
numerator -= denominator
num_units += 1
pieces.append(str(num_units))
return float(''.join(pieces))
| true |
e366ffbd98c7cf6e860489e91b1f07457695b5ab | KishenSharma6/SF-Airbnb-Listings-Analysis | /Project_Codes/03_Processing/Missing_Stats.py | 1,102 | 4.15625 | 4 | import pandas as pd
import numpy as np
def missing_calculator(df,data_type = None):
"""
The following function takes a data frame and returns a dataframe with the following statistics:
data_type takes a string or list of strings referenceing data type
missing_count: Number of missing values per column
missing_%: Returns the % of total values missing from the column
The function also returns a list of columns that containg
"""
if data_type == None:
missing = pd.DataFrame(index=df.isna().sum().index)
missing['count'] = df.isna().sum()
missing['percentage'] = (missing['count']/len(df)) * 100
missing = missing[missing['percentage'] > 0].sort_values(by = 'percentage', ascending = False)
else:
missing = pd.DataFrame(index=df.select_dtypes(data_type).isna().sum().index)
missing['count'] = df.isna().sum()
missing['percentage'] = (missing['count']/len(df)) * 100
missing = missing[missing['percentage'] > 0].sort_values(by = 'percentage', ascending = False)
return(missing) | true |
320c5067f7607baedb6009db27bca5f99e60b74e | muralimandula/cspp1-assignments | /m7/p3/Functions - Assignment-3/assignment3.py | 1,521 | 4.125 | 4 | """
A program that calculates the minimum fixed monthly payment needed
in order pay off a credit card balance within 12 months
using bi-section method
"""
def payingdebt_offinayear(balance, annual_interestrate):
""" A function to calculate the lowest payment"""
def bal_d(balance, pay, annual_interestrate):
""" A function to calculate balance"""
balnace_due = balance
for _ in range(1, 13):
unpaid_balance = balnace_due - pay
balnace_due = unpaid_balance*(1 + (annual_interestrate/12.0))
return balnace_due
payment_low = balance/12.0
monthly_interestrate = annual_interestrate/12.0
payment_high = (balance*((1 + monthly_interestrate)**12))/12.0
payment = (payment_high + payment_low)/2.0
epsilon = 0.03
while True:
# print(bal_d(balance, payment, annual_interestrate))
if bal_d(balance, payment, annual_interestrate) > epsilon:
payment_low = payment
elif bal_d(balance, payment, annual_interestrate) < -epsilon:
payment_high = payment
else:
return round(payment, 2)
payment = (payment_high + payment_low)/2.0
# if bal_d(balance, payment, annual_interestrate) <= epsilon:
def main():
"""
A function for output
"""
data = input()
# data = "4773 0.2"
data = data.split(' ')
data = list(map(float, data))
print("Lowest Payment: " + str(payingdebt_offinayear(data[0], data[1])))
if __name__ == "__main__":
main()
| true |
7d25fca29ef23d397b784da8567293279cf4d0ca | alvinuy1110/python-tutorial | /oop/basic.py | 867 | 4.40625 | 4 | #####
# This is the OOP tutorial
#####
title = "OOP Tutorial"
print(title)
# Basic class
print("\nBasic Class\n")
# class definition
class A():
# constructor
def __init__(self):
print("classA initialized")
# constructor
def __init__(self, name=None):
print("classA initialized")
self.name=name
def get_name(self):
return self.name;
def set_name(self, name):
self.name = name;
pass
# Main stuff
a = A() # constructor
a.name="classA"
print(a.get_name()) # method call
# unknown property
# attr = a.prop1 # will throw an Error
attr = getattr(a,'prop1', 'defaultValue') # safe retrieval and return defaultValue if not available
print(attr)
a.set_name("newClass") # method invocation
print(a.get_name())
# constructor 2
a2=A("A2")
print(a2.get_name())
# call destructor
del a
del a2
| true |
2aaad3f3fe4b0a57e481f2b752266a7dc636a6e3 | alvinuy1110/python-tutorial | /loop/loop.py | 809 | 4.4375 | 4 | #####
# This is the Looping tutorial
#####
title = "Looping Tutorial"
print(title)
# Looping
print("\n\nLooping\n\n")
myMap = {"key1": "value1", "key2": 1234}
print(myMap)
# print the entries
print("\nKey-Value\n")
for k, v in myMap.items():
print(k, v)
# loop with the index
print("\nIndex-Value\n")
for (i, v) in enumerate(myMap):
print(i, v)
# loop 2 lists
print("\nZip example\n")
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
# while if loop
print("\nWhile loop\n")
x = 0
while (True):
if (x >= 5):
break
elif (x > 2):
print("{0} is greater than 2".format(x))
x = x + 1
else:
print(x)
x = x + 1
| true |
c115a55e98a112cbd4f2170590cfbbb219c9720a | cal1log/python | /tuples.py | 243 | 4.125 | 4 | #!/usr/bin/env python3
'''creating a tuple'''
tup = (10, 20, 30, 40)
'''getting a tuple index value'''
print(tup[2])
'''impossible to change values in a tuple'''
try:
tup[2] = 60
except:
print("a tuple can not changes your values")
| true |
69b832863c278164de52ef419b82d3c4d5bee86d | sudhanvalalit/Koonin-Problems | /Koonin/Chapter1/Exercises/Ex5.py | 1,427 | 4.1875 | 4 | """
Exercise 1.5: Write programs to solve for the positive root of x^2-5 using the Newton-Raphson
and secant methods. Investigate the behavior of the latter with changes in the initial guesses
for the root.
"""
import numpy as np
from scipy.misc import derivative
tolx = 1e-6
def f(x):
return x**2 - 5.0
def Newton_Raphson(f, x):
dx = 0.2
fvalue = f(x)
count = 0
while abs(fvalue) > tolx:
x += dx
fprime = derivative(f, x, 1e-4)
fvalue = f(x)
dx = -fvalue/fprime
count += 1
if count > 1000:
raise Exception("Exceeded the number of iterations.")
break
return x
def Secant(f, x):
diff = 0.1
df = 0.1
while abs(diff) > tolx:
x1 = x + df
f1 = f(x)
f2 = f(x1)
dx = x1 - x
df = f2 - f1
df = -f(x1) * dx/df
diff = f2 - f1
x = x1
return x
def main():
result = Newton_Raphson(f, 4.0)
print("Root using Newton Raphson method: {:.6F}".format(result))
result1 = Secant(f, 4.0)
print("Root using Secant method: {:.6F}".format(result1))
# Investigate the behavior of latter method, i.e. secant method
print("Iter \t Result \t Error")
for i in range(10):
result = Secant(f, i)
diff = np.sqrt(5) - result
print("{:2} \t {:.6f} \t {:.5E}".format(i, result, diff))
if __name__ == "__main__":
main()
| true |
02774b2a40e58bf843a661fde07fc87b91bcdabd | Scientific-Computing-at-Temple-Physics/prime-number-finder-Scadow121 | /primes.py | 1,479 | 4.25 | 4 | # This is a comment. Python will ignore these lines (starting with #) when running
import math as ma
import time
# To use a math function, write "ma." in front of it. Example: ma.sin(3.146)
# These functions will ask you for your number ranges, and assign them to 'x1' and 'x2'
x1 = raw_input('smallest number to check: ')
x2 = raw_input('largest number to check: ')
# This line will print your two numbers out
print x1, x2
""" Text enclosed in triple quotes is also a comment.
This code should find and output all prime numbers between (and including) the numbers entered initially.
If no prime numbers are found in that range, it should print a statement to the user.
Now we end the comment with triple quotes."""
# The rest is up to you!
x1=int(x1)
x2=int(x2)
if x1 < x2:
print "The prime numbers between" ,x1, "and" ,x2, "are:"
x = x1
d = 2
while x != (x2+1):
if x != d:
q = x%d
if q != 0:
if d >= x:
if x > 0:
print x
x = x+1
d = 2
else:
x = x+1
d = 2
else:
d = d+1
else:
x = x+1
d = 2
else:d = d+1
else:
print "Invalid Input Detected!"
time.sleep(0.5)
print "Initiating Self-Destruct Sequence (This may take a while)..."
time.sleep(10)
| true |
3b7ec7522103f8d09d04e3955ffc1167c1aca47d | abdulwasayrida/Python-Exercises | /Exercise 6.18.py | 569 | 4.21875 | 4 | #Exercise 6.18
#Display a matrix of 0s and 1s
#Rida Abdulwasay
#1/12/2018
def printMatrix(n): #Create a function
from random import randint
for side1 in range (n):
for side2 in range (n):
print(randint(0, 1), end=" ") #randint generates the random number sequence
print(" ")
#Prompt the user to enter a number
def main ():
number = eval (input ("Please enter a number: "))
printMatrix(int(number))
if number <= 0:
print ("That is not a valid number:")
main () #Call the main function
| true |
e65af2007a3a9096a6dc4569338d5b84aa4e93fa | abdulwasayrida/Python-Exercises | /RegularPolygon.py | 1,418 | 4.3125 | 4 | #Exercise 7.5
#Geometry: n-sided regular polygon
#Rida Abdulwasay
#1/14/2018
import math
#Create a Class named RegularPolygon
class RegularPolygon:
def __init__(self, n = 3, side = 1, x = 0, y = 0):
self.__n = n
self.__side = side
self.__x = x
self.__y = y
#Create a function to the number of side (n)
def getN(self):
return self.__n
#Create a function to get the length of the side
def getSide(self):
return self.__side
#Create a function to get the X coordinate of the center
def getX(self):
return self.__x
#Create a function to get the Y coordinate of the center
def getY(self):
return self.__y
#Create a function to get the Perimeter
def getPerimeter(self):
perimeter = self.__n * self.__side
return perimeter
#Create a function to get the Area
def getArea(self):
n = self.__n
side = self.__side
areaPart1 = n * (side **2)
areaPart2 = 4 * math.tan ( math.pi / n )
area = areaPart1 / areaPart2
return area
#Create a function to set the number of sides
def setN(self, n):
self.__n = n
#Create a function to set the side length
def setSide(self, side):
self.__side = side
#Create a function to set the center coordinates
def setXY(self, x, y):
x , y = self.__x , self.__y
| true |
e6a084c2bf6c0c34e3ffcd81ec94d893412a74db | chengming-1/python-turtle | /W7/lab-7/names.py | 612 | 4.1875 | 4 |
# Create an empty dictionary
names = {}
names['Wash'] = 'Rick'
names['Geier'] = 'Caitlin'
names['DiLisio'] = 'Armand'
names['wang']='chengming'
a = input("Enter the last name of a student: ")
b = input("Enter the First name of a student: ")
names[a]=b
while True:
last_name = input("Enter a student's last name: ")
if last_name in names:
print("Their first name is", names[last_name])
if last_name not in names:
print("I dont know that student")
if last_name == "":
# If the user hits enter without entering a name, stop the loop
break
| true |
09b19aa33e576b71a463bd1aced49b14e2e0d74b | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Exercise/page_85_exercise_04.py | 657 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Assume that the variables x and y refer to strings. Write a code segment that prints these strings in
alphabetical order. You should assume that they are not equal.
Solution:
The sorted words are:
bui
khang
le
ngoc
"""
# Program to sort alphabetically the words form a string provided by the user
my_str = "LE BUI NGOC KHANG"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
| true |
53878427622bba5b8e795204524588c123540e36 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_203_exercise_02.py | 719 | 4.25 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton.
(Hint: The estimate of the square root should be passed as a second argument to the function.)
Solution:
2.0000000929222947
"""
approximating = 0.000001
def newton2(x, estimate):
"""
Calculate approximating square
:param estimate:
:param x: enter a number to calculate approximating square
:return: the estimate of its square root
"""
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference > approximating:
estimate = newton2(x, estimate)
return estimate
print(newton2(4, 1)) | true |
34df6e92f6125e3408e46221b645c44b2855e728 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_182_exercise_02.py | 569 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: The factorial of a positive integer n, fact(n), is defined recursively as follows:
fact(n) = 1 , when n = 1
fact(n) n * fact (n-1) , otherwise
Define a recursive function fact that returns the factorial of a given positive integer
Solution:
Enter n to calculate: 3
Factorial of 3 is: 6
"""
number = int(input("Enter n to calculate: "))
def fact(n):
if n == 1:
return 1
else:
return n * fact(n - 1)
result = fact(number)
print(f"Factorial of {str(number)} is: " + str(result)) | true |
81125a2c8610d4531755bb4a53cb19aa3d946c96 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_02.py | 640 | 4.40625 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script that inputs a line of encrypted text and a distance value and outputs plaintext using a
Caesar cipher. The script should work for any printable characters
Solution:
Enter the coded text: khoor#zruog
Enter the distance value: 3
hello world
"""
# Request the inputs
code = input("Enter the coded text: ")
distance = int(input("Enter the distance value: "))
plainText = ''
for ch in code:
ordvalue = ord(ch)
cipherValue = ordvalue - distance
if cipherValue < 0:
cipherValue = 127 - (distance - (1- ordvalue))
plainText += chr(cipherValue)
print(plainText) | true |
7a5c1a0d7c416a8f88934c5b6daecb4c36fefa45 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_204_exercise_09.py | 623 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a program that computes and prints the average of the numbers in a text
file. You should make use of two higher-order functions to simplify the design.
Solution:
Enter the file name: textnumber.txt
The average is 3.0
"""
def main():
fileName = input("Enter the file name: ")
total = 0
count = 0
with open(fileName, 'r') as f:
for line in f:
for num in line.strip().split():
total += float(num)
count += 1
print("\nThe average is " + str(total / count))
if __name__ == '__main__':
main() | true |
47c65a3c577e406863dba437b479719540e39061 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Projects/page_99_exercise_02.py | 1,005 | 4.3125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should
indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle,
the square of one side equals the sum of the squares of the other two sides.
Solution:
Enter length a: 3
Enter length b: 4
Enter length c: 5
The triangle is a right triangle
Enter length a: 2
Enter length b: 3
Enter length c: 4
The triangle is not a right triangle
"""
# Requests the input
a = int(input("Enter length a: "))
b = int(input("Enter length b: "))
c = int(input("Enter length c: "))
# compute the squares
square1 = a ** 2
square2 = b ** 2
square3 = c ** 2
# Check condition and print ringt triangle or normal triangle
if square1 + square2 == square3 or square2 + square3 == square1 or square1 + square3 == square2:
print("The triangle is a right triangle")
else:
print("The triangle is not a right triangle") | true |
6873aa32b9630205bbc7475864686dd85187beaa | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_06.py | 1,004 | 4.375 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5
to code a new encryption algorithm. The algorithm should add 1 to each character’s numeric ASCII value, convert
it to a bit string, and shift the bits of this string one place to the left. A single-space character in the
encrypted string separates the resulting bit strings.
Solution:
Enter a message: Hello, World!
0010011 1001101 1011011 1011011 1100001 011011 000011 0110001 1100001 1100111 1011011 1001011 000101
"""
plainText = input("Enter a message: ")
code = ""
for ch in plainText:
ordValue = ord(ch) + 1
bstring = ""
while ordValue > 0:
remainder = ordValue % 2
ordValue = ordValue // 2
bstring = str(remainder) + bstring
# shift one bit to left
if len(bstring) > 1:
bstring = bstring[1:] + bstring[0]
# Add encrypted character to code string
code += bstring + " "
print(code) | true |
81627d0a80c0c03f3027ff7296a3638a447c37e7 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_133_exercise_09.py | 941 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script named copyfile.py. This script should prompt the user for the names of two text files.
The contents of the first file should be input and written to the second file.
Solution:
Enter the input file name: test9.txt
Enter the output file name: test9_output
This script creates a program listing from a
source program. This script should prompt the user for the names of two files. The
input filename could be the name of the script itself, but be careful to use a different
output filename!
"""
# request the input
inputFile = input("Enter the input file name: ")
outputFile = input("Enter the output file name: ")
# open the input file and read the text
outfile = open(outputFile, "w")
# open the input files
with open(inputFile, 'r') as file:
index = 1
for line in file:
print(line)
outfile.write("%d>"%index + line)
index += 1
outfile.close() | true |
fc90debc52d5f84e0d03ab770ba10746405d657f | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH07/Exercise/page_218_exercise_03.py | 480 | 4.46875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Add a function named circle to the polygons module. This function expects the same arguments as the square
and hexagon functions. The function should draw a circle. (Hint: the loop iterates 360 times.)
Solution:
"""
import turtle
def polygon(t, length, n):
for _ in range(n):
t.fd(length)
t.lt(360 / n)
bob = turtle.Turtle()
bob.penup()
bob.sety(-270)
bob.pendown()
polygon(bob, 30, 60)
turtle.mainloop()
| true |
26ce3efa3df58e629c706ad5da9b8457ba0e9d52 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_199_exercise_02.py | 317 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write the code for a filtering that generates a list of the positive numbers in a list
named numbers. You should use a lambda to create the auxiliary function.
Solution:
[1, 79]
"""
numbers = [1, -2, -66, 79]
result = list(filter(lambda x: x > 0, numbers))
print(result) | true |
5c5fc3250152575883481aca9ee77e0a632f7c95 | Dukiemar/RSA-Encryption | /RSA_Encryption.py | 2,632 | 4.34375 | 4 | import random
def PGP_encryption():
p=input("enter the 1st prime number:")#prompts the user to enter the value for p
q=input("enter the 2nd prime number:")#prompts the user to ented the value for q
message=input("enter message:")
def isPrime(n): #this function ristricts the user to only enter prime numbers
for i in (range (2,n)):
if n%i==0:
return False
return True
if isPrime (int(p))==False or isPrime(int(q))==False:
return "not prime numbers" #if and of the numbers are not prime the system prompts the user
return encrypt(int(p),int(q),str(message))#if the numbers entered are prime the function the runs the encrypt function
def encrypt(p,q,string): #Main encryption algorithm
n=p*q #calculate the value for n which is the product of p x q
z=(p-1)*(q-1) #calculate the value for z which represent phi n
def gcd(x, y): #this is the general function the computes the greatest common divisor between two numbers
while x != 0:
(x, y) = (y % x, x)
return y
for i in range (2,n): #this function computes the value fo e which is relatively prime to z
if gcd(i,z)==1:
e=i
def Extended_Euclid(m,n):# this function utilizes the gcd function to compute the value for d using modulo inverse
if gcd(m,n)!=1:
return "Invalid"
A1,A2,A3 = 1,0,m
B1,B2,B3 = 0,1,n
while B3!=0:
Q = A3//B3
T1,T2,T3 = A1-Q*B1,A2-Q*B2,A3-Q*B3
A1,A2,A3 = B1,B2,B3
B1,B2,B3 = T1,T2,T3
d=A1%n
return d
print ("The values for n :", n,",The value for e:",e,",The value for z:",z,",The value for d:",Extended_Euclid(e,z))
x=[]
for i in range(0,len(string)): #perform conversions to produce the encrypted message in string format
x+=[ord(string[i])]
msg=[]
for a in x:
c=(a**e)%n
msg+=[c]
fin_msg=""
for ele in msg:
fin_msg+=str(ele)+ " "
print("Message:")
print (fin_msg)
def decrypt(fin_msg,n,z,e):# decrypts the encrypted message
dec_msg=""
msg=fin_msg.split(" ")
d=(Extended_Euclid(e,z))
for i in range (0,len( msg)-1):
m= int((int(msg[i])**d)%n)
dec_msg+=chr(m)
return dec_msg
print ("Decrypted Message : ")
return decrypt(fin_msg,n,z,e)
| true |
f7df966b90cd84cadf6805203d190df700a58f9f | prastabdkl/pythonAdvancedProgramming | /chap7lists/plotting/sec5piechart.py | 511 | 4.25 | 4 | # plotting a Piechart
# Author: Prastab Dhakal
# Chapter: plotting
import matplotlib.pyplot as plt
def main():
#create a list of values
values=[20,60,80,40]
#title
plt.title("PIE CHART")
#create a list of labels for the slices.
slice_labels=['1st Qtr','2nd Qtr','3rd Qtr','4th Qtr']
#create a pie chart from the values
plt.pie(values,labels=slice_labels,colors=('r','b','y','c'))
#display the pie chart.
plt.show()
#defining main function
main() | true |
941f9950cf21e526a0cb8c50feb2a553d6e5d4c3 | prastabdkl/pythonAdvancedProgramming | /chap6FilesAndException/others/save_file_records.py | 2,541 | 4.125 | 4 | # This program gets employee data from the user and
# saves it as records in the employee.txt file.
# read the records and show until the end is reached handles the value errors,
# read file error and searches the file until the end is reached
#
# Author: Prastab Dhakal
# Chapter: Files and Exception(Complex problem)
def write_records():
# Get the number of employee records to create.
num_emps = int(input('How many employee records ' +'do you want to create? '))
# Open a file for writing.
emp_file = open('employees.txt', 'w')
# Get each employee's data and write it to the file.
for count in range(1, num_emps + 1):
# Get the data for an employee.
try:
print('Enter data for employee #', count, sep='')
name = input('Name: ')
id_num = int(input('ID number: '))
dept = input('Department: ')
except ValueError:
print('invalid input: ValueError')
# Write the data as a record to the file.
emp_file.write(name + '\n')
emp_file.write(str(id_num) + '\n')
emp_file.write(dept + '\n')
# Display a blank line.
print()
# Close the file.
emp_file.close()
print('Employee records written to employees.txt.')
# Call the main function.
def read_records():
try:
infile = open('employes.txt','r')
name = infile.readline()
while name != '':
id_num = infile.readline()
dept = infile.readline()
#print the data
#name = name.rstrip()
#id_num = id_num.rstrip()
#dept =dept.rstrip()
print('Name:',name,'id_num:',id_num,'dept:',dept,sep='')
name = infile.readline()
infile.close()
except Exception:
print('File not found')
exit(0)
def search_records():
found = False
search = input('Enter the name you want to search?')
emp_file = open('employees.txt','r')
name = emp_file.readline()
while name != '':
id_num = emp_file.readline()
dept = emp_file.readline()
name = name.rstrip()
if name == search:
print('Name:',name)
print('id_num:',id_num,end='')
print('Dept:',dept)
found = True
name = emp_file.readline()
emp_file.close()
if not found:
print('The name',search,'was not found')
def main():
write_records()
read_records()
search_records()
main() | true |
d5fc347cad1f2a3a1cd26cab15653aea5f9bb986 | rodri0315/pythonCSC121 | /chapter3/area_of_rectangles.py | 966 | 4.59375 | 5 | # Chapter 1 Assignment
# Author: Jorge Rodriguez
# Date: February 5, 2017
print('You will enter the length and width for two rectangles')
print('The program will tell you which rectangle has the greater area')
# get length and width of 2 rectangles
rect_length1 = float(input('Enter the length of the first rectangle: '))
rect_width1 = float(input('Enter the width of the first rectangle: '))
rect_length2 = float(input('Enter the length of the second rectangle: '))
rect_width2 = float(input('Enter the width of the first rectangle: '))
# calculate area of both rectangles
rect_area1 = rect_width1 * rect_length1
rect_area2 = rect_length2 * rect_width2
# compare which rectangle has the greater area
if rect_area1 > rect_area2:
print('Your first rectangle has a greater area than your second rectangle')
elif rect_area1 < rect_area2:
print("Your second rectangle had a greater area than your first rectangle")
else:
print('Both rectangles had the same area!')
| true |
fab42d2bbb28bff895054c136584314f4091fb20 | xis24/CC150 | /Python/FreqOfMostFrequentElement.py | 965 | 4.25 | 4 | from typing import List
class FreqOfMostFrequentElement:
'''
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
'''
def maxFrequency(self, nums: List[int], k: int) -> int:
left = 0
ret = 1 # min value
curSum = 0
for right in range(len(nums)):
curSum += nums[right]
# we want to find out the valid condition curSum + k >= nums[right] * (right - left +1)
# so when the while condition stops, it's the condition.
while curSum + k < nums[right] * (right - left + 1):
curSum -= nums[left]
left += 1
ret = max(right - left + 1, ret)
return ret
| true |
29108375b2c46d239764d70dd6b7fc4416c5e89d | xis24/CC150 | /Python/SortColors.py | 931 | 4.15625 | 4 | from typing import List
class SortColors:
# 1. discuss the approach
# 2. run the test case
# 3. ask if I can start to code
# 4. start to code
# 5. run test case with code
# 6. time complexity and space complexity
def sortColors(self, nums: List[int]) -> None:
zeros = 0 # position next zero should be
twos = len(nums) - 1 # posisiton next two should be
cur = 0 # current position
while cur <= twos:
if nums[cur] == 2:
nums[cur], nums[twos] = nums[twos], nums[cur]
twos -= 1
elif nums[cur] == 0:
nums[cur], nums[zeros] = nums[zeros], nums[cur]
zeros += 1
cur += 1
else:
cur += 1
return nums
if __name__ == '__main__':
obj = SortColors()
print(obj.sortColors([2, 1, 0, 2]))
print(obj.sortColors([2, 2, 1, 2]))
| true |
2d8c9ba19b177f95ecf6e65da4c5a5c353390d42 | travisthurston/OOP_example | /Card.py | 549 | 4.125 | 4 | #Card class is a blueprint of the card object
#This is the parent or base class for Minion
class Card:
#initializer to create the attributes of every class object
def __init__(self, cost, name):
self.cost = cost
self.name = name
#attributes - argument - parameter - describes the object
#give the card a cost attribute
#give the card a name attribute
#behaviors - methods - functions
def printCardInfo(self):
print("Name:" + self.name)
print("Cost:" + str(self.cost))
| true |
4a2186d1443b1dcba7bd4a02c93afe9cb55e4855 | Ustabil/Python-part-one | /mini_projects/guess_the_number/guess_the_number.py | 2,497 | 4.28125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#Codeskulptor URL: http://www.codeskulptor.org/#user40_06oB2cbaGvb17j2.py
import simplegui
import random
current_game = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
# remove this when you add your code
global secret_number
if current_game == 0:
range100()
elif current_game == 1:
range1000()
else:
print "Something bad happened..."
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
# remove this when you add your code
global secret_number
global allowed_Guesses
global current_game
current_game = 0
allowed_Guesses = 7
secret_number = random.randrange(0, 100)
print "\nGuess a number between 0 and 100, within", allowed_Guesses, "guesses!"
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global allowed_Guesses
global current_game
current_game = 1
allowed_Guesses = 10
secret_number = random.randrange(0, 1000)
print "\nGuess a number between 0 and 1000, within", allowed_Guesses, "guesses!"
def input_guess(guess):
# main game logic goes here
global allowed_Guesses
guess = int(guess)
allowed_Guesses -= 1
# remove this when you add your code
print "\nGuess was", guess
if guess == secret_number:
print "Correct!"
new_game()
elif allowed_Guesses == 0:
print "No more guesses!"
new_game()
elif guess > secret_number:
print "Lower!"
print "Remaining guesses:", allowed_Guesses
elif guess < secret_number:
print "Higher!"
print "Remaining guesses:", allowed_Guesses
else:
print "Something weird happened o.O"
# create frame
frame = simplegui.create_frame('Guess the Number', 200, 200)
# register event handlers for control elements and start frame
button1 = frame.add_button('Range is 0 - 100', range100, 200)
button2 = frame.add_button('Range is 0 - 1000', range1000, 200)
inp = frame.add_input('Enter a guess:', input_guess, 200)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true |
4523e4efe62db4005d9e09b9fa8e5f20b548ef81 | grebwerd/python | /practice/practice_problems/shortestPath.py | 1,021 | 4.15625 | 4 | def bfs_paths(graph, start, goal):
queue = [(start, [start])] #queue is a list made up of a tuple first tuple is a start and the second tuple is a list
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path): #for each next adjacency node not in the set already
print("next is ", next)
if next == goal: # if next equals the goal
yield path + [next] #add the goal to the path, breaks out and returns a generator
else:
print("Adding the node ", next, " to the path")
queue.append((next, path + [next]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
def main():
graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])}
print(shortest_path(graph, 'A','F'))
if __name__ == '__main__':
main() | true |
befb06130ebf46def192f3a33c799e7139303290 | abaker2010/python_design_patterns | /decorator/decorator.py | 861 | 4.125 | 4 | """
Decorator
- Facilitates the addition of behaviors to individual objects without
inheriting from them
Motivation
- Want to augment an object with additional functionality
- Do no want to rewrite or alter existing code (OCP)
- Want to keep new functionality separate (SRP)
- Need to be able to interact with existing structures
- Two options:
- Inherit from required object (if possible)
- Build a Decorator, which simply references the decorated object(s)
"""
import time
def time_it(func):
def wrapper():
start = time.time()
result = func()
end = time.time()
print(f'{func.__name__} took {int(end - start) * 1000} ms')
return result
return wrapper
@time_it
def some_op():
print('Starting op')
time.sleep(1)
print('We are done')
return 123
# some_op()
# time_it(some_op)
some_op()
| true |
69ceec17993f350329a7f6214657fc9aae84ef1a | Zolton/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 806 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of
***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
test = "THtHThth"
test2 = "abcthefthghith"
test3 = "abcthxyz"
count = 0
def count_th(word):
global count
if len(word) == 0:
return count
if word[:2] == "th":
count = count + 1
word = word[2:]
count_th(word)
elif word[:2] != "th":
if word[1:3] == "th":
count = count + 1
word = word[2:]
count_th(word)
elif word[1:3] != "th":
word = word[2:]
count = count
count_th(word)
return count
print(count_th(test))
| true |
7c2549bcb4f95d76184c334a4968773a0ab7e500 | Zchhh73/Python_Basic | /chap6_struct/struct_break_continue.py | 208 | 4.15625 | 4 | for item in range(10):
if item == 3:
break
print('Count is : {0}'.format(item))
print('\n')
for item in range(10):
if item == 3:
continue
print('Count is : {0}'.format(item)) | true |
4b1bb8a4e501b50680d29d4688405b1a5c0f8bf4 | mgtz505/algorithms | /implementations/sorting_algorithms/quicksort.py | 518 | 4.15625 | 4 | print("Implementation of Quicksort")
test_data = [3,11,4,0,7,2,12,7,9,6,5,10,3,14,8,5]
def quickSort(N):
length = len(N)
if length <= 1:
return N
else:
larger, smaller = [], []
pivot = N.pop()
for num in N:
if num < pivot:
smaller.append(num)
else:
larger.append(num)
return quickSort(smaller) + [pivot] + quickSort(larger)
print(quickSort(test_data)) #[0, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10, 11, 12, 14]
| true |
3e36b2f72dbe1c248365e51566f81a21e6e18b3e | alex-mucci/ce599-s17 | /18-Design and Classes/Car.py | 2,655 | 4.4375 | 4 | #constansts
START_NORTH = 0
START_SOUTH = 0
START_EAST = 0
START_WEST = 0
# Define the class
class Car(object):
"""
Base class for a car
"""
def __init__(self, color,location = [0,0],direction = 'N'):
if len(location) < 2 or len(location) > 2:
print('location is the x,y coordinates of the car')
else:
self.color = color
self.location = location
self.x = location[0]
self.y = location[1]
self.direction = direction
def go(self,units,movement):
"""
function to move the car the given distance in the given direction
"""
if movement == 'forward':
if self.direction == 'N':
self.y = self.y + units
elif self.direction == 'S':
self.y = self.y - units
elif self.direction == 'E':
self.x = self.x + units
elif self.direction == 'W':
self.x = self.x - units
else:
print('Direction options are N, S, E, and W')
self.location = [self.x,self.y]
elif movement == 'backward':
if self.direction == 'N':
self.y = self.y - units
elif self.direction == 'S':
self.y = self.y + units
elif self.direction == 'E':
self.x = self.x - units
elif self.direction == 'W':
self.x = self.x + units
else:
print('Direction options are N, S, E, and W')
self.location = [self.x,self.y]
else:
print('Possible movements are forward and backward')
def turn_right(self):
if self.direction == 'N':
self.direction = 'E'
elif self.direction == 'S':
self.direction = 'W'
elif self.direction == 'E':
self.direction = 'S'
elif self.direction == 'W':
self.direction = 'N'
else:
print('direction is wrong')
def turn_left(self):
if self.direction == 'N':
self.direction = 'W'
elif self.direction == 'S':
self.direction = 'E'
elif self.direction == 'E':
self.direction = 'N'
elif self.direction == 'W':
self.direction = 'S'
else:
print('direction is wrong')
def printcar(self):
print('Car Color is ' + self.color)
print('Car Location is ')
print(self.location)
print('Car Direction is ' + self.direction)
| true |
8969c70857b05f92b3cec8f3339bb543498b39e3 | kolevatov/python_lessons | /simple_object.py | 550 | 4.15625 | 4 | # Simple object
class Simple(object):
"""Simple object with one propertie and method"""
def __init__(self, name):
print("new object created")
self.__name = name
def __str__(self):
return "Simple object with name - " + self.__name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print ("Wrong value")
else:
self.__name = new_name
obj1 = Simple("Buba")
print (obj1)
obj1.name = ""
print (obj1) | true |
ef5efede1db142e41aba118dc0d78efa371ad209 | vishnuk1994/ProjectEuler | /SumOfEvenFibNums.py | 1,045 | 4.46875 | 4 | #!/bin/python3
import sys
# By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
# creating dict to store even fib nums, it helps in reducing time at cost of extra space
# by rough estimate; it is better to use space as for high value of n, it will recalculate the series
mapOfEvenFibNum = {0:0,1:2}
# getting nth even fib num.
# formula used is based on the logic that every third element in fibonacci is even
# refer : https://www.geeksforgeeks.org/nth-even-fibonacci-number/
def getEvenFib(n):
if n in mapOfEvenFibNum:
return mapOfEvenFibNum[n]
return ( 4* getEvenFib(n-1) + getEvenFib(n-2) );
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
count = 1
reqSum = 0
num = getEvenFib(count)
# getting fib num till we reach n
# updating dict with values
while num <= n:
reqSum += num
mapOfEvenFibNum[count] = num
count += 1
num = getEvenFib(count)
print(reqSum)
| true |
f2c0bda23f4292e676e3d246d28f6f158145f7e9 | ibbur/LPTHW | /16_v4.py | 1,017 | 4.25 | 4 | print "What file would you like to open?"
filename = raw_input("> ")
print "Opening the file %r for you..." % filename
review = open(filename)
print review.read()
target = open(filename, 'w')
print "\n"
print "I will now clear the file contents..."
target.truncate()
print "I will now close the file..."
target.close()
print "I will now reopen the file so we can add new text..."
freshfile = open(filename, 'w')
print "Let's write three new lines to the file. Begin entering text..."
line1 = raw_input("1> ")
line2 = raw_input("2> ")
line3 = raw_input("3> ")
print "\n I will now write to the file..."
freshfile.write ('{}\n{}\n{}\n' .format(line1,line2,line3))
freshfile.close()
reviewagain = open(filename)
print "Let's read the file to make sure everything is as it should be..."
print "---------------"
print reviewagain.read()
print "---------------"
print "I will now clean up behind us by closing the file..."
reviewagain.close()
print "The file is now closed, and this exercise is now complete!"
| true |
3dc2910eea2580527783d8e35114c110e44b3f11 | GanSabhahitDataLab/PythonPractice | /Fibonacci.py | 661 | 4.3125 | 4 | # Find PI to the Nth Digit - Enter a number and have the program generate π (pi) up to
# that many decimal places. Keep a limit to how far the program will go
def fibonaccisequence_upton():
askForInput()
def askForInput():
n = int(input("Enter number of Fibonnacci sequence"))
fibgenerated = fibonaccialgorithm(n)
for i in fibgenerated:
print(i)
def fibonaccialgorithm(n):
generated_fib = []
for i in range(0, n):
if i > 1:
generated_fib.append(generated_fib[i - 1] + generated_fib[i - 2])
else:
generated_fib.append(i)
return generated_fib
| true |
3865e1e3cf60023a368f629cb21a3b163d61fa59 | claudiamorazzoni/problems-sheet-2020 | /Task 6.py | 435 | 4.4375 | 4 | # Write a program that takes a positive floating-point number as input and outputs an approximation of its square root.
# You should create a function called sqrt that does this.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
import math
num = float(input("Please enter a positive number: "))
sqrt = math.sqrt(num)
print("The square root of {} is approx. {}" .format(num, "%.1f" % sqrt)) | true |
02a11bf65defec6e1280af02fabf2411dea09e85 | Nithinnairp1/Python-Scripts | /lists.py | 1,073 | 4.25 | 4 | my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
print(my_list[-1])
n_list = ["Happy", [2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
odd = [1, 3, 5]
odd.append(7)
print(odd)
odd = [1, 3, 5]
print(odd + [9, 7, 5])
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
print(my_list.pop(1))
# append() - Add an element to the end of the list
# extend() - Add all elements of a list to the another list
# insert() - Insert an item at the defined index
# remove() - Removes an item from the list
# pop() - Removes and returns an element at the given index
# clear() - Removes all items from the list
# index() - Returns the index of the first matched item
# count() - Returns the count of number of items passed as an argument
# sort() - Sort items in a list in ascending order
# reverse() - Reverse the order of items in the list
# copy() - Returns a shallow copy of the list | true |
9e76ed8832052f6d5066700f222bea4d4df69b50 | TrihstonMadden/Python | /plot-dictionary.py | 1,226 | 4.125 | 4 | # plot-dictionary.py
import tkinter as tk
import turtle
def main():
#table is a dictionary
table = {-100:0,-90:10,-80:20,-70:30,-60:40,-50:50,
-40:40,-30:30,-20:20,-10:10,0:0,
10:10,20:20,30:30,40:40,50:50,
60:40,70:30,80:20,90:10,100:0,
}
print(" KEYS ")
print(table.keys())
print(" VALUES ")
print(table.values())
#turtle graphics
twin = turtle.Screen()
twin.clear()
t = turtle.Turtle()
#tWin = turtle.Screen()
for h,k in table.items(): #get the items in the dictionary
print(h, k) # trace code
#x,y = table[n]
t.speed(.5)
t.penup()
t.goto(h,k)
t.pendown()
t.circle(5)
twin.exitonclick()
main()
"""
This code uses a dictionary with keys ranging from
-100 to 100 incrementing by 10.
Each key has a value of 0 as an integer.
To retrieve the values in the dictionary "table" a for loop is used.
The x cooridate on a python turtle screen corresponds to h while
the y value cooresponds to k.
**************************************
for h,k in table.items(): #get the items in the dictionary
print(h, k) #trace code
h and k are then ploted using
t.goto(h,k)
t.pendown()
t.circle(5)
Change the values from 0 to another integer.
Try to make something grovey.
"""
| true |
0cb9dbd2051790e0992b5a5c55456efe184911d3 | Jethet/Practice-more | /python-katas/EdabPalin.py | 778 | 4.3125 | 4 | # A palindrome is a word, phrase, number or other sequence of characters which
# reads the same backward or forward, such as madam or kayak.
# Write a function that takes a string and determines whether it's a palindrome
# or not. The function should return a boolean (True or False value).
# Should be case insensitive and special characters (punctuation or spaces)
# should be ignored.
import string
def is_palindrome(txt):
exclude = set(string.punctuation)
txt = ''.join(ch for ch in txt if ch not in exclude).replace(' ','').lower()
#print(txt)
return txt == txt[::-1]
print(is_palindrome("A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!")) # True
print(is_palindrome("Neuquen")) # True
print(is_palindrome("Not a palindrome")) # False
| true |
b447f6804b1aaf41f103aa9b75afd2814c207163 | Jethet/Practice-more | /small-projects/inverseRandNum.py | 720 | 4.21875 | 4 | import random
# instead of the computer generating a random number, the user is giving the number
def computer_guess(x):
low = 1
high = x
feedback = ""
while feedback != "c":
# you cannot have low and high be the same:
if low != high:
guess = random.randint(low, high)
else:
guess = low # could also be high because low and high are the same here
feedback = input(f"Is {guess} too high (H), too low (L), or correct (C)?".lower())
if feedback == "h":
high = guess - 1
elif feedback == "l":
low = guess + 1
print(f"The computer guessed your number, {guess} correctly!")
computer_guess(10) | true |
22800ea3b59510039284cf345034c94c1ee4b99a | Jethet/Practice-more | /python-katas/3_Sum.py | 239 | 4.1875 | 4 | # Return sum of two int, unless values are the same: then return double.
def sum_double(a, b):
if a == b:
return 2 * (a + b)
else:
return a + b
print(sum_double(1,2))
print(sum_double(3,2))
print(sum_double(2,2))
| true |
3f0aa8fd1025b9f1d919f544cbf78dbc91c44699 | Jethet/Practice-more | /python-katas/EdabAltCaps.py | 362 | 4.4375 | 4 | # Create a function that alternates the case of the letters in a string.
# The first letter should always be UPPERCASE.
def alternating_caps(txt):
print(alternating_caps("Hello")) # "HeLlO"
print(alternating_caps("Hey, how are you?")) # "HeY, hOw aRe yOu?"
print(alternating_caps("OMG!!! This website is awesome!!")) # "OmG!!! tHiS WeBsItE Is aWeSoMe!!"
| true |
394c0e41664f79b95e279ff063f7584a49f675cf | Jethet/Practice-more | /python-katas/EdabCountUniq.py | 384 | 4.28125 | 4 | # Given two strings and a character, create a function that returns the total
# number of unique characters from the combined string.
def count_unique(s1, s2):
return len(set(s1 + s2))
print(count_unique("apple", "play")) #➞ 5
# "appleplay" has 5 unique characters:
# "a", "e", "l", "p", "y"
print(count_unique("sore", "zebra")) #➞ 7
print(count_unique("a", "soup")) #➞ 5
| true |
e398b42c4309d60d59ea97a5e341532502fb0a1c | Jethet/Practice-more | /python-katas/EdabIndex.py | 686 | 4.375 | 4 | # Create a function that takes a single string as argument and returns an
# ordered list containing the indexes of all capital letters in the string.
# Return an empty array if no uppercase letters are found in the string.
# Special characters ($#@%) and numbers will be included in some test cases.
def indexOfCaps(word):
caps_list = []
for x in word:
if x.isupper() == True:
y = word.index(x)
caps_list.append(y)
return caps_list
print(indexOfCaps("eDaBiT")) # [1, 3, 5]
print(indexOfCaps("eQuINoX")) # [1, 3, 4, 6]
print(indexOfCaps("determine")) #[]
print(indexOfCaps("STRIKE")) # [0, 1, 2, 3, 4, 5]
print(indexOfCaps("sUn")) # [1]
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.