blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c4acbc2cc9cbbe534af749af6b6ceb44ee854b6f | kcthogiti/ThinkPython | /Dice.py | 352 | 4.1875 | 4 |
import random
loop_control = "Yes"
Min_num = int(raw_input("Enter the min number on the dice: "))
Max_num = int(raw_input("Enter the Max number on the dice: "))
def print_rand():
return random.randrange(Min_num, Max_num)
while loop_control == "Yes":
print print_rand()
loop_control = raw_input("Do you want to continue? Yes or No: ")
| true |
6275eae9107c2d92a9df5f2c8749389434917a82 | SDrag/weekly-exercises | /exercise1and2.py | 1,450 | 4.375 | 4 | ###################
### Exercise 1: ###
###################
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# Test the function with the following value.
x = 18
ans = fib(x)
print("Fibonacci number", x, "is", ans)
### My name is Dragutin, so the first and last letter of my name (D + N = 4 + 14) give the number 18. The 18th Fibonacci number is 2584.
###################
### Exercise 2: ###
###################
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Sreckovic"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
### My surname is Sreckovic
### The first letter S is number 83
### The last letter c is number 99
### Fibonacci number 182 is 48558529144435440119720805669229197641
### ord() function in Python: Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.
| true |
2d94305898adc3a1227bc7790f1d769c4da93426 | gautam06/Python | /py5_StdDataTypes.py | 2,933 | 4.21875 | 4 | #Python Standard DataTypes
print "Numbers String List Tuple Dictionary"
print "Numbers -> int (-1,786,-0x260,0x69), float(15.20,-25.1,-32.3e100), complex(3.14j, .876j, 4.53e-7j)"
print ""
#Number Examples
print ("\n-------------------------------------")
print ("Number Exaples");
print ("-------------------------------------")
var1 = 1
var2 = 10
print "var1: ",var1
print "var2: ",var2
#One can delete reference to a object by del statement
del var1; #delete reference
#or del var1, var2
#Below line gives error var1 not defined
#print "var1: ",var1
#String Examples ------------------------
s = "Indian Hero Saktiman"
print ("\n-------------------------------------")
print ("String Examples")
print ("-------------------------------------")
print (s) #print complete string
print (s[0]) #print first character
print (s[7:11]) #print characters from 7 to 10
print (s[7:]) #print string starting from 7
print (s * 2) #print string two times
print (s + " The Real Hero") #print concatenated string
#List Examples ----------------------------
print ("\n-------------------------------------")
print ("List Examples")
print("-------------------------------------")
list = [ 'abcd ', 786 , 23.36,'gautam',70.2]
tinylist =[123,'gautam']
print (list) #prints complete list
print (list[0]) #prints first element of list
print (list[0:3]) #prints elements 1st to 3rd
print (list[3:]) #prints elements starting from 4
print (tinylist * 2) #print list two times
print (list + tinylist) #prints concatenated lists
print ("Changing value in touple")
list[2] = 66.06 #possible to change value
print (list)
#Tuples Examples ----------------------------
print ("\n-------------------------------------")
print ("Tuples Examples")
print ("-------------------------------------")
print ("Tuples are enclosed within parenthesis\n")
tuple = ( 'abcd', 786, 2.23, 'gautam', 70.2)
tinytuple = (123,'gautam')
print (tuple) #prints complete tuple
print (tuple[0]) #prints first element of tuple
print (tuple[0:3]) #prints elements 1st to 3rd
print (tuple[3:]) #prints elements starting from 4
print (tinytuple * 2) #print tuple two times
print (tuple + tinytuple) #prints concatenated tuples
#Below code gives error as it does not support modification
#tuple[2] = 1000
#Dictionary Examples ----------------------------
print ("Dictionary is kind of Hash-Table Type")
print ("Dictionary works like associative array")
print ("\n-------------------------------------")
print ("Dictionary Examples")
print ("-------------------------------------")
dict = {}
dict['one'] = "one"
dict[2] = "two"
tinydict = {'name':'gautam','college':'rollwala computer center','code':3245}
print (dict['one']) #prints value for 'one' key
print (dict[2]) #prints value for 2 key
print (tinydict) #prints complete dictionary
print (tinydict.keys()) #prints all the keys
print (tinydict.values()) #prints all the values
| true |
41a907c8a5062f01e3a671521178e70de9a91ad5 | sahibseehra/Python-and-its-Applications | /Python+data sciences+sql+API/7.py | 237 | 4.15625 | 4 | #declaring list:
l=[]
n=input("enter no of students")
n=int(n)
for i in range(0,n):
name=input("enter student name=")
l.append(name)#if there is no list , then elements are appended on the next memory location
print(l)
| true |
0fa5ad12cd25202d70e1a2e06a6bccb2d62e1f97 | kburr6/Python-Projects | /Python Basics/Strings and Lists/append_first_to_last.py | 252 | 4.15625 | 4 | # Input series of comma-separated strings
s = input('Please enter a series of comma-separated strings: ')
# Split on comma+space to create the list
l = s.split(', ')
# Append the first element to list l and then print the list
l.append(l[0])
print(l)
| true |
91cad9a7f2bc9c5680e9b18d38df530a15d2b2f4 | kburr6/Python-Projects | /Python Basics/Numpy_Examples/numpy_boolean_indexing.py | 405 | 4.125 | 4 | import numpy as np
def elements_twice_min(arr):
"""
Return all elements of array arr that are greater than or equal to 2 times
the minimum element of arr.
Parameters
----------
arr: NumPy array (n, m)
Returns
-------
NumPy Array, a vector of size between: 0 and (n * m) - 1
"""
return arr[arr >= 2*np.amin(arr)]
print(elements_twice_min([[3,7,8],[3,4,5]]))
| true |
6e423f0f7678f06dd5de0e7235c4afa5295358e1 | apoorvasharma007/networks | /geolocationserver.py | 2,618 | 4.125 | 4 | #Apoorva Sharma
'''
In this program I have written a simple server script which will listen for a connection from a remote client. To locate the remote client I need his IP Address. When the server accepts a connection request by .accept() call, it returns a new socket descriptor for connecting to the client and ADDRESS STRUCTURE which stores the IP ADDRESS AND PORT NUMBER of the client. From this address structure I have extracted the IP Address of the client.
With the IP Address known, I query a free to use online database of global IP Addresses for the location of this particular IP Address. The API used by "https://ipinfo.io/" automatically returns the location of the IP Address as a simple JSON structure listing country name, city name, zip code etc. I have parsed the JSON by using python's default json library. The parsed information is displayed on the console.
I also learnt that if an IP Address which is local to a network is given, then client cannot be located. In this case, such reserved IP's along with other IP ranges that haven’t yet been allocated and therefore also shouldn’t appear on the public internet are sometimes known as bogons. Thus, in such cases the API of ipinfo.io returns "bogon=true".
'''
import socket # For socket programming.
import urllib.request # For querying the url of ipinfo.io and receive a JSON response.
import json # To parse JSON structures.
HOST='147.32.69.80' #dummy IP address for hosting a server.
PORT=65432 #port number for the server to listen on.
serversocket=socket.socket() #create a socket for the server.
serversocket.bind((HOST,PORT)) #bind the socket to the specific port.
serversocket.listen(5) # now the server is listening for requests to connect on the specified port.
while:
client,addr=serversocket.accept() #connect to the client and store its IP Address and port number in structure addr. addr[0]=IP Address, addr[1]=Port Number.
url="https://ipinfo.io/" #generate a url to send a query to for the geolocation of the client.
print ('Connected to client from' , addr[0]) #prints on the console the IP Address of the client.
url+=addr[0] #append the IP Address of the client to generate full url on which we will send the query.
result=urllib.request.urlopen(url).read() #request for JSON response from ipinfo.io
json.loads(result) # parse the JSON structure obtained.
print(result) # print the geolocation obtained.
client.close() #close the communication channel.
serversocket.close()#close server when done.
| true |
631574b48da15331f564f48abfba61c69360e2b8 | charlesluch/Code | /Py4eSpec/01-Py4e/myCode/computePay.py | 966 | 4.34375 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Award time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of time-and-a-half 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):
if(float(h)<=40) :
p = float(h) * float(r)
else :
p = (float(r)*40) + (float(h)-40)*(float(r)*1.5)
return p
hrs = input("Enter Hours: ")
rate = input("Enter Rate: ")
p = computepay(hrs,rate)
print(p)
| true |
224a0428bfa61a020187e8f7ccc18d503761bd68 | elaverdiere1/100_days_code | /day1_name_generator.py | 419 | 4.5 | 4 | #1. Create a greeting for your program.
print("Welcome to Band Name Generator")
#2. Ask the user for the city that they grew up in.
city = input("what is the name of the city you grew up in?\n")
#3. Ask the user for the name of a pet.
pet = input("what is a name of a pet you owned?\n")
#4. Combine the name of their city and pet and show them their band name.
print("Your band name could be "+ city + ' ' + pet + ".")
| true |
f861a0d32f7f3169b44a4d49ebba770b18012f4a | dona126/Python-Programming | /Basics/conditionals.py | 521 | 4.28125 | 4 | #Use of if,elif and else statements.
#Example 1
age=int(input("Enter age:"))
if(age>18):
print("Hey, i can vote!")
elif(age==0):
print(":)")
else:
print("I can't vote.")
#Example 2
score =float( input("Enter Score: "))
if score>=0.0 and score<=1.0:
if( score >= 0.9):
print("A Grade")
elif( score >= 0.8):
print("B Grade")
elif( score >= 0.7):
print("C Grade")
elif( score >= 0.6):
print("D Grade")
else:
print("F Grade")
else:
print("Error!")
| true |
acb20a11f7ea9c0c258726621c975bdf1b3e1f98 | dona126/Python-Programming | /Practice/valleyCount.py | 694 | 4.5 | 4 | # A hiker moves a step UP or a step DOWN. Start and end at sea level.
# Mountain- start with step UP and end with step DOWN.
# Valley- start with step DOWN and end with step UP.
# Find number of valleys walked through.
# Uses;
# U for UP
# D for DOWN
#Input:
#path="U D D D U D U U"
#Output:1
#
def valleyCount(path):
count=0
result=0
for x in path:
if x=="D":
count=count-1
if x=="U":
count=count+1
if(count==0):
result=result+1
return(result)
path=input("Enter all the steps taken ('U' or 'D') as space separated:")
path=path.split(" ")
result=valleyCount(path)
print(result)
| true |
31c114bff52bcfe0ca5c9cc5bf951ff266efd639 | msipola/CBM101 | /K_Mathematical_Modeling/Section 3/solutionExercise1.py | 1,188 | 4.375 | 4 | from IPython.display import display, Latex
print("First, we expand the expression of the random variable of which we want to compute the expectation value:")
display(Latex('$ (N-<N>)^2 = N^2-2*N*<N>+<N>^2$'))
print("because <N> is just a number.")
print("")
print("Then we compute the expectation value of the sum of all terms as the sum of the expectation values of each term:")
display(Latex('$ <(N-<N>)^2> = <N^2>-<2*N*<N>>+<<N>^2>$'))
print("")
print("And finally we scrutinize all terms: the first one is the expectation value of the random variable N^2, which is what it is. 2*N*<N> is the product of a random variable, N, by a number, 2*<N>. Hence the expectation value of the product is the expectation value of the random variable times the number:")
display(Latex('$ <2*N*<N>> = 2*<N>*<N> = 2*<N>^2$'))
print("finally the last term is the expectation value of a number, that is not even a random variable. Hence its expectation value is itself!")
display(Latex('$ <<N>^2>=<N>^2$'))
print("")
print("Summing all three terms we get to simplify the second and the third to finally obtain:")
display(Latex('$ <(N-<N>)^2> = <N^2>-2*<N>^2+<N>^2 = <N^2>-<N>^2$'))
| true |
da4115f4f762b550a6fb2bd07b451294a5de68b9 | yamada46/Python_class | /Lab2.py | 1,157 | 4.1875 | 4 | '''
Module 8 - Lab 2
1 1 unread reply. 1 1 reply.
Instructions:
When you try to open a file that doesn't exist on your file system the open function raises a nice error called FileNotFoundError
```bash
>>> open('some_file_location.txt', 'r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'some_file_location.txt'
>>>
```
Write a script called lab2.py. In the script write some pseudo code that opens a non-existant file location and use try/except to handle the FileNotFoundError and output a nicer message for the user about what happened?
Let's say some other type of error happens but we don't know the specifc name of it. How can our try/excepthandle this?
Files must always be closed! If an error is thrown how can we assure the file still gets closed?
Post your code and answers to this discussion board for credit
HINT: look up try/except/finally and python built-in exceptions (Links to an external site.)
'''
#!/usr/bin/env python3
# Mod8 Lab2
try:
open("/Users/gailyamada/test.txt", "r")
except:
if FileNotFoundError:
print("File does not exist!") | true |
b70765edd48e29f40027e612e2d2af9e07d528e0 | yamada46/Python_class | /Mod5_Lab3.py | 1,603 | 4.34375 | 4 | #! /Users/gailyamada/PycharmProjects/ITFDN2018/venv/bin/python3
'''
Module 5 - Lab 3
Denise Elizabeth Mauldin
Let's do some analysis of the Seattle Wage Data CSV file
Make sure you have downloaded the data from here:
https://catalog.data.gov/dataset/city-of-seattle-wage-data/resource/1b351da9-d1a9-48e4-850c-a1af51c43852 (Links to an external site.)Links to an external site.
with open
For this lab:
Read in the CSV file using csv.reader
Store the header line in a variable using next (Links to an external site.)Links to an external site.
Create a dictionary to store the list of 'Hourly Rate' by job title (hint: this is a dictionary where the value is a list - seattle[job] = [rates]. You'll need to use dictionary.get to see if the key exists in each dictionary and create it if it does not.)
Write the dictionary to a file
Stretch Goals
After your data structure is created, use a for loop to go over each job and calculate the average pay
Print a sentence for each job saying how many people work that job and what the average pay is. (hint: if there's one person, you just need to print the first value of the rates list)
Calculate the highest paying job
Print the seattle dictionary to a file
Store the department as the first key and print out the average wage by job title in the department
'''
# open the file and read in the file
import csv
file_handle = open("./City_of_Seattle_Wage_Data.csv")
reader = csv.reader(file_handle)
for row in reader:
print(row)
'''
header = []
header = row[0].split(",")
print(header)
# get the header line and save it as header
#header = row[0].split(",")
'''
| true |
994964e186d4034cccb1f89d1a78feff148e7717 | yamada46/Python_class | /Mod3_Lab2.py | 1,191 | 4.25 | 4 | '''
Mod3_Lab2
make a variable with one animal
find unique letter
give user letters + 3 guesses
compare each guess to unique letters
print out the matches
'''
# Make a list of animal
animal = "raccoon"
unique = set(animal)
#print(unique)
# store guesses
guessed_letter = set()
num_guess = len(unique)
#print(num_guess)
print("Figure out the secret animal. Guess some letters in it's name! You get ", num_guess," tries ")
# get user input
counter = 0
while counter < num_guess:
guess = input("Guess a letter in the secret animal's name: ")
if guess in unique:
print("Yes, you guessed a letter! ")
guessed_letter.add(guess)
print(guessed_letter)
counter+= 1
else:
print("That letter is not in the animal name")
counter+= 1
print("You have ", num_guess - counter, "left!")
print("These are the letters you have guessed correctly ", guessed_letter)
print("The number of letters in the secret animal name is ",len(animal))
guess_animal = input("Guess what the animal is: ")
if guess_animal == animal:
print("Congrats! You've guessed correctly!\n")
print("You have won a frisbee!\n")
else:
print("Sorry you lose!\n")
| true |
94d518d89abbcdab41f6354a1a9735568fc58399 | dbbudd/Python-Experiments | /AI/EasyAI_examples/Mastermind1.py | 2,729 | 4.21875 | 4 | #!/usr/bin/env python
#!/usr/bin/env python
"""Python Mastermind
Program that tests your skills at the game Mastermind.
"""
import random
instructions = """
=== The Mastermind game ===
Object of the Game
The computer picks a sequence of 4 pegs, each one being one of any of six colors.
The object of the game is to guess the exact positions of the colors in the
sequence in as few guesses as possible. After each guess, the computer
gives you a score of exact and partial matches. A black peg indicates an exact
match, a white peg a partial match (right color, wrong position).
Rules
1. The sequence can contain pegs of colors: red, yellow, green, blue, purple, orange
2. A color can be used any number of times in the sequence.
3. All four pegs of the secret sequence will contain a color -
no blanks/empties are allowed.
4. Each guess must consist of 4 peg colors - no blanks.
You should enter each color of your guess separately at the prompt. Use lower case.
"""
# constants setup
colors = ['red', 'yellow', 'green', 'blue', 'purple', 'orange']
# generate secret code
secretCode = []
i=0
while i<4:
color = random.randint(0,5)
secretCode.append(colors[color])
i=i+1
print 'Secret: ', secretCode
fullMatches=0
guessNum=1
while (fullMatches<>4):
# Set up loop variables
fullMatches = 0
partialMatches = 0
secretCodeCopy = secretCode[:]
guess = []
print 'Guess:', guessNum
i=0
while i<len(secretCode):
print 'Enter a color from:',
print colors,
color=raw_input()
guess.append(color)
i=i+1
# Full matches
i=0
while i<len(guess):
if guess[i] == secretCodeCopy[i]:
fullMatches = fullMatches+ 1
secretCodeCopy[i] = 'X'
guess[i]='Y'
i=i+1
# Partial Matches
i=0
while i<len(guess):
j=0
while j<len(secretCodeCopy):
if guess[i] == secretCodeCopy[j]:
partialMatches = partialMatches+ 1
secretCodeCopy[j] = 'X'
guess[i]='Y'
j=j+1
i=i+1
#print response
print fullMatches,
print ' blacks'
print partialMatches,
print ' whites'
if fullMatches == 4:
print 'You guessed it in', guessNum
guessNum=guessNum+1
def Negamax (board, depth, maxDepth):
if (board.isGameOver() or depth == maxDepth):
return board.evaluate(), null
bestMove = null
bestScore = -INFINITY
for move in board.getMoves():
newBoard = board.makeMove(move)
score = Negamax(newBoard, depth+1, maxDepth)
score =-score #alternate players
if (score > bestScore):
bestScore = score
bestMove = move
return bestScore, bestMove
| true |
8b7206d46407012cbf76fae9dc6b8294dbfad69a | justinclark-dev/CSC110 | /code/Chapter-12/fibonacci.py | 460 | 4.125 | 4 | # This program uses recursion to print numbers
# from the Fibonacci series.
def main():
print('The first 10 numbers in the')
print('Fibonacci series are:')
for number in range(1, 11):
print(fib(number))
# The fib function returns the nth number
# in the Fibonacci series.
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
# Call the main function.
main()
| true |
8199f930e624b3fff1407da55bb68b7b94265303 | justinclark-dev/CSC110 | /sample-programs/week2/circle.py | 975 | 4.5625 | 5 |
# circle.py
# Program to calculate area and circumference of a circle.
# NOTE: we import the math module so we can use the built-in definition for pi.
# The output section demonstrates formatting numbers for output;
# notice how the format function performs appropriate rounding.
# CSC 110
# 9/25/2011, updated 10/4/2016
import math
print("This program will ask for the radius of a circle then calculate the area and circumference")
print()
print()
# get radius
radius = float(input('Please enter radius: '))
# do the math. Notice the syntax for using pi
area = math.pi * radius ** 2
circumference = math.pi * radius * 2
# output results
print('Given a circle with radius =' + str(radius))
print('The area = ' + format(area, '.4f') + ' and the circumference = ' \
+ format(circumference, '.4f'))
# test cases, confirmed by hand
# radius of 10 produces an area = 314.1593 and circumference = 62.8319
# radius of 1 gives area = 3.1416 and circumference = 6.2832 | true |
70d689c1704d84da2b580c62c9ce96946ef0184d | justinclark-dev/CSC110 | /code/Chapter-5/draw_circles.py | 761 | 4.34375 | 4 | import turtle
def main():
turtle.hideturtle()
circle(0, 0, 100, 'red')
circle(-150, -75, 50, 'blue')
circle(-200, 150, 75, 'green')
# The circle function draws a circle. The x and y parameters
# are the coordinates of the center point. The radius
# parameter is the circle's radius. The color parameter
# is the fill color, as a string.
def circle(x, y, radius, color):
turtle.penup() # Raise the pen
turtle.goto(x, y - radius) # Position the turtle
turtle.fillcolor(color) # Set the fill color
turtle.pendown() # Lower the pen
turtle.begin_fill() # Start filling
turtle.circle(radius) # Draw a circle
turtle.end_fill() # End filling
# Call the main function.
main()
| true |
4d670180768a15612fb0e713a9c84f91467ebc23 | justinclark-dev/CSC110 | /sample-programs/week7/sin_cos_solution.py | 1,675 | 4.25 | 4 | # sin_cos_solution2017.py
# One possible solution for the trapezoid / sin_cos_squared lab exercise.
# CSC 110
# Winter, 2017
import math # import statement needed for math.pi, math.sin() and math.cos()
def main():
# Part 1a:
print('\nPart 1a: The area shown on the table row is ' \
+ format(area_trapezoid(4, 5, 8), '.2f'))
# Part 1b:
answer = area_trapezoid(2, 7, 9) - area_trapezoid(3.2, 4.2, 2)
print('\nPart 1b: If you did it correctly, this should be 33.1: ' \
+ format(answer, '.1f'))
# Part 2:
show_sin_cos_squared_table(8)
show_sin_cos_squared_table(20)
# END of 'main' function definition.
# a trapezoid has a height and a top length and bottom length.
# The top and bottom lengths are typically referred to as base2 and base1
# See this website for a picture http://math.com/tables/geometry/areas.htm
# DO NOT MAKE ANY CHANGES TO THIS FUNCTION DEFINITION
def area_trapezoid(base1, base2, height):
area = height / 2.0 * (base1 + base2)
return area
# displays ("prints") a table containing (intervals + 1) rows
# showing values for 'n' ranging from 0 to 2pi and sin(n), cos(n), and
# (sin^2(n) + cos^2(n)) for each value of 'n'.
def show_sin_cos_squared_table(intervals):
first = 0.0
last = math.pi * 2
step = (last - first) / intervals
print('\n\n n sin(n) cos(n) sin^2(n) + cos^2(n)')
for i in range(intervals + 1):
num = i * step
ans = math.sin(num) ** 2 + math.cos(num) ** 2
print(format(num, '.4f') + format(math.sin(num), '8.3f') \
+ format(math.cos(num), '8.3f') + format(ans, '22.17f'))
main()
| true |
881d7d16bd126bd54adc97dd4fdc80f34bb758ff | justinclark-dev/CSC110 | /sample-programs/week2/representational_error.py | 2,519 | 4.25 | 4 |
# representational_error.py
#
# A demonstration of representational error
# CSC 110
# Sp'12
message = """The sequence of Python statements in this file demonstrates that even very
simple calculations, such as repeatedly adding 0.1 to a number, can result
in very small errors in the result. This kind of error is normal and is
related to the way in which 'floating point' numbers are represented
(stored) in the computer. All numbers are stored in a binary (base 2)
format, and conversions from a binary to a decimal (base 10) format are
not perfect, in the same way that it is difficult to represent the number
1/3 in a decimal format. When viewing the output produced by the first
section of this program, you will notice that the decimal value shown is
sometimes a tiny bit larger or smaller than it should be.
These errors are rarely of any consequence in normal calculations.
However, they do make it impossible to reliably test whether or not a
floating point number is exactly equal to some value. Rather, we usually
test to see if two floating point numbers are equal to within some small
allowable error.\n"""
print(message)
x = 0.1
print(x)
x += 0.1 # UPDATE the value of x
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
x += 0.1
print(x)
print()
message = """The same sequence of numbers as above is repeated below, but the 'format'
function is used to display each number with a fixed number of digits after
the decimal point.
When the 'format' function is called as it is in this program, the function
returns a STRING representation of the numeric value with the specified
number of digits after the decimal point, even if one or more of the
trailing digits are zeros. The function also automatically rounds the
number in an appropriate way.
Because 'format' returns a STRING value, it should be used only to display
a numeric result to the user in a visually pleasing way. Use the 'round'
function to round numbers that must be used in further calculations. The
'round' function returns a numeric value (type int).\n"""
print(message)
x = 0.1
print(format(x, '.1f'))
x += 0.1
print(format(x, '.2f'))
x += 0.1
print(format(x, '.3f'))
x += 0.1
print(format(x, '.4f'))
x += 0.1
print(format(x, '.3f'))
x += 0.1
print(format(x, '.3f'))
x += 0.1
print(format(x, '.3f'))
x += 0.1
print(format(x, '.3f'))
x += 0.1
print(format(x, '.3f'))
print()
x = 11223344.5566
print(format(x, '.2f'))
print(format(x, ',.2f'))
| true |
ec3ed0d9d053666f982aeb763eab95f7abc0ff93 | justinclark-dev/CSC110 | /code/Chapter-5/random_numbers.py | 256 | 4.15625 | 4 | # This program displays a random number
# in the range of 1 through 10.
import random
def main():
# Get a random number.
number = random.randint(1, 10)
# Display the number.
print('The number is', number)
# Call the main function.
main()
| true |
e67622cc50ed79eb5b7fd439f432c4b9735d6b8d | justinclark-dev/CSC110 | /code/Chapter-3/sort_names.py | 388 | 4.5 | 4 | # This program compare strings with the < operator.
# Get two names from the user.
name1 = input('Enter a name (last name first): ')
name2 = input('Enter another name (last name first): ')
# Display the names in alphabetical order.
print('Here are the names, listed alphabetically.')
if name1 < name2:
print(name1)
print(name2)
else:
print(name2)
print(name1)
| true |
0e5bb675ace9199be4ead4f5fbf03e2dd78f226e | justinclark-dev/CSC110 | /code/Chapter-5/hypotenuse.py | 453 | 4.4375 | 4 | # This program calculates the length of a right
# triangle's hypotenuse.
import math
def main():
# Get the length of the triangle's two sides.
a = float(input('Enter the length of side A: '))
b = float(input('Enter the length of side B: '))
# Calculate the length of the hypotenuse.
c = math.hypot(a, b)
# Display the length of the hypotenuse.
print('The length of the hypotenuse is', c)
# Call the main function.
main()
| true |
9c924b4fec9a4cad771cb19b9c08e66fe91e14e5 | justinclark-dev/CSC110 | /code/Chapter-10/coin_argument.py | 503 | 4.15625 | 4 | # This program passes a Coin object as
# an argument to a function.
import coin
# main function
def main():
# Create a Coin object.
my_coin = coin.Coin()
# This will display 'Heads'.
print(my_coin.get_sideup())
# Pass the object to the flip function.
flip(my_coin)
# This might display 'Heads', or it might
# display 'Tails'.
print(my_coin.get_sideup())
# The flip function flips a coin.
def flip(coin_obj):
coin_obj.toss()
# Call the main function.
main()
| true |
b4dcce09936d8277e06e00eccc9ce8ed71496e35 | justinclark-dev/CSC110 | /code/Chapter-2/string_input.py | 219 | 4.34375 | 4 | # Get the user's first name.
first_name = input('Enter your first name: ')
# Get the user's last name.
last_name = input('Enter your last name: ')
# Print a greeting to the user.
print('Hello', first_name, last_name)
| true |
3c0421300920f0a4cad73d4433b93b4e6bd6e2de | justinclark-dev/CSC110 | /code/Chapter-6/modify_coffee_records.py | 1,960 | 4.4375 | 4 | # This program allows the user to modify the quantity
# in a record in the coffee.txt file.
import os # Needed for the remove and rename functions
def main():
# Create a bool variable to use as a flag.
found = False
# Get the search value and the new quantity.
search = input('Enter a description to search for: ')
new_qty = int(input('Enter the new quantity: '))
# Open the original coffee.txt file.
coffee_file = open('coffee.txt', 'r')
# Open the temporary file.
temp_file = open('temp.txt', 'w')
# Read the first record's description field.
descr = coffee_file.readline()
# Read the rest of the file.
while descr != '':
# Read the quantity field.
qty = float(coffee_file.readline())
# Strip the \n from the description.
descr = descr.rstrip('\n')
# Write either this record to the temporary file,
# or the new record if this is the one that is
# to be modified.
if descr == search:
# Write the modified record to the temp file.
temp_file.write(descr + '\n')
temp_file.write(str(new_qty) + '\n')
# Set the found flag to True.
found = True
else:
# Write the original record to the temp file.
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
# Read the next description.
descr = coffee_file.readline()
# Close the coffee file and the temporary file.
coffee_file.close()
temp_file.close()
# Delete the original coffee.txt file.
os.remove('coffee.txt')
# Rename the temporary file.
os.rename('temp.txt', 'coffee.txt')
# If the search value was not found in the file
# display a message.
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
# Call the main function.
main()
| true |
a7c1397b07bbcb2ee45c221f089e39526f836981 | justinclark-dev/CSC110 | /sample-programs/week4/sort_names.py | 539 | 4.5625 | 5 | # sort_names.py
#
# This program demonstrates how the < operator can
# be used to compare strings.
# from Tony Gaddis
def main():
# Get two names from the user.
name1 = input('Enter a name (last name first): ')
name2 = input('Enter another name (last name first): ')
# Display the names in alphabetical order.
print('Here are the names, listed alphabetically.')
if name1 < name2:
print(name1)
print(name2)
else:
print(name2)
print(name1)
# Call the main function.
main()
| true |
4146805a276701f7682d09357f1fbb17d9601418 | justinclark-dev/CSC110 | /lab-activity-3.py | 1,054 | 4.28125 | 4 | # CSC 110 - Lab Activity #3
# Simple Functions with Parameters
# Section 03
# Justin Clark
# 1/22/2020
# Part 1:
# ==============
# print(s, a, b, c)
# output: apple 3 6 12
# output: banana 4 5 13
# output: cherry 6 3 15
# output: date 5 3 13
# output: elderberry 5 3 13
# output: fig 6 2 14
# output: ate 6 3 15
# Part 2:
# ==============
def show_message():
message = "\nWelcome to the updated tip calculator.\n" \
+ "This program will show you several options for a tip amount.\n"
print(message)
def show_tip(billAmount, tipPercent):
tipCalculated = billAmount * (tipPercent / 100)
tipMessage = "A {}% tip on a ${:.2f} bill amounts to ${:.2f}." \
"\n".format(tipPercent, billAmount, tipCalculated)
print(tipMessage)
def main():
show_message()
bill_amount = float(input('Please enter the amount of the bill: $'))
print('\n')
show_tip(bill_amount, 15)
show_tip(bill_amount, 18)
show_tip(bill_amount, 20)
show_tip(bill_amount, 25)
main() # start the program
| true |
310e714493f57c69ee45f848374b9a6909a84328 | justinclark-dev/CSC110 | /Labs/class-examples-3.6.2020.py | 517 | 4.125 | 4 |
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for letter in alphabet:
print(letter, end=', ')
original_string = 'abcdefghijklmnopqrstuvwxyz'
# reverse order of string (short way)
new_string = original_string[::-1]
print(new_string)
# reverse order of string (long way)
for i in range(len(original_string)-1,-1,-1):
print(i, original_string[i])
new_string += original_string[i]
print (new_string)
if type(new_string).isalpha:
print("is alpha")
'a' in alphabet
numbers = [1,2,3,4,5,6,7,8]
5 in numbers | true |
75a0bfe6189a61afdb89d6a28d78302b42e16eda | justinclark-dev/CSC110 | /code/Chapter-4/spiral_circles.py | 476 | 4.625 | 5 | # This program draws a design using repeated circles.
import turtle
# Named constants
NUM_CIRCLES = 36 # Number of circles to draw
RADIUS = 100 # Radius of each circle
ANGLE = 10 # Angle to turn
ANIMATION_SPEED = 0 # Animation speed
# Set the animation speed.
turtle.speed(ANIMATION_SPEED)
# Draw 36 circles, with the turtle tilted
# by 10 degrees after each circle is drawn.
for x in range(NUM_CIRCLES):
turtle.circle(RADIUS)
turtle.left(ANGLE)
| true |
b4e83529f04bc831ce02e89b28681a9b3e8e11dd | justinclark-dev/CSC110 | /sample-programs/week7/read_numbers.py | 779 | 4.15625 | 4 | # read_numbers.py
#
# Sample program to read numbers from a file, count them and sum them.
# Assumes each line in the file contains a valid number.
# CSC 110
# Winter 2012
# open the file 'numbers.txt' for reading
infile = open('numbers.txt', 'r')
total = 0 # initialization
count = 0 # initialization
line = infile.readline() # read in first line (initialization)
# as long as 'line' isn't an empty string,
# we haven't reached the end of the file
while line != '':
value = float(line) # convert from string to number
print(value)
total += value
count += 1
line = infile.readline() # this is the update -- read another line
infile.close() # close the connection to the file
print('There were ' + str(count) + ' numbers, totaling ' + str(total))
| true |
6b9b30272ef0b9e1741a6e182a9961500cecceca | justinclark-dev/CSC110 | /code/Chapter-8/split_date.py | 394 | 4.59375 | 5 | # This program calls the split method, using the
# '/' character as a separator.
def main():
# Create a string with a date.
date_string = '11/26/2012'
# Split the date.
date_list = date_string.split('/')
# Display each piece of the date.
print('Month:', date_list[0])
print('Day:', date_list[1])
print('Year:', date_list[2])
# Call the main function.
main()
| true |
887d47441759e233f45ddcc1bbf6d72fdd40a79b | justinclark-dev/CSC110 | /code/Chapter-4/squares.py | 319 | 4.21875 | 4 | # This program uses a loop to display a
# table showing the numbers 1 through 10
# and their squares.
# Print the table headings.
print('Number\tSquare')
print('--------------')
# Print the numbers 1 through 10
# and their squares.
for number in range(1, 11):
square = number**2
print(number, '\t', square)
| true |
8a0a76bb8df53578f3c391bd0a149210ecb1dbbf | rds123/python_code_practice | /primenum.py | 501 | 4.1875 | 4 | def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
num = int(input("Enter a number: "))
check_prime = is_prime(num)
if check_prime:
print('Your number is a Prime')
else:
print('Your number is not a Prime')
C:\Users\Rahul\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Rahul/PycharmProjects/pythonProject/primenum.py
Enter a number: 13
Your number is a Prime
Process finished with exit code 0 | true |
3f9bd65c73111bff677c280204bf576ff2dcbb9b | zhangted/trees-graphs-python | /sorting.py | 1,259 | 4.28125 | 4 | #bubble sort
def bubbleSort(array):
#go left to right, switch values if left is < right
#do repeatedly until no swaps made on 1 runthrough
swapped = True
while swapped == True:
swaps = 0
for i in range(len(array)):
if i+1 < len(array):
if array[i] > array[i+1]:
swap(i,i+1,array)
swaps += 1
if swaps > 0:
swapped = True
else:
swapped = False
return array
#insertion sort
def insertionSort(array):
#for every element after first element, push it left if it is greater than current element
for i in range(1,len(array)):
j = i
while j > 0 and array[j] < array[j-1]:
swap(j,j-1,array)
j -= 1
return array
#selection sort
def selectionSort(array):
currentIdx = 0
while currentIdx < len(array):
minIdx = currentIdx
for i in range(currentIdx,len(array)):
if array[i] < array[minIdx]:
minIdx = i
swap(minIdx,currentIdx,array)
currentIdx += 1
return array
def swap(x,y,arr):
arr[x],arr[y] = arr[y],arr[x]
def main():
og = [8,5,2,9,5,6,3]
unsort = [8,5,2,9,5,6,3]
print(og, "-> bubble sort ->", bubbleSort(unsort))
print(og, "-> insertion sort ->", insertionSort(unsort))
print(og, "-> selection sort ->", selectionSort(unsort))
main() | true |
d177804a33ca4990f9aae45192a1cf698dc578c6 | vipulshah31120/PythonClassesByCM | /Homework/04-02-2021/tuple.py | 399 | 4.1875 | 4 | #A tuple consists of a number of values separated by commas
t = 12345, 6789, "vipul"
print (t[0])
print (t[2])
t = (12345, 6789, "vipul")
# Tuples may be nested:
u = t, (1,2,3,4)
print(u)
# Tuples are immutable
#t[0] = 55
print(t) #TypeError: 'tuple' object does not support item assignment
# but they can contain mutable objects:
v = ([1,2,3,4,], [5,6,7,8,9])
print(v)
print(t,v) | true |
c91f58c7408b30a0dabec081672fbe939416e3a2 | Ishan1717/CodingSchool | /calc.py | 2,971 | 4.6875 | 5 | #Overall function that when called actually executes the calculator. This calculator should display a list of options to the user: whether they want to add, multiply, divide, substract a set of numbers. Additionally, the user should have the options to exponentiate a number, take a number to an nth root, or quit the calculator. Each of these options should consist of a different function.
#Requirements for Add/Subtract/Mult/Divide: take in the number of numbers the user wants to calculate, than take in each number. Display the result as follows to the user: [n1] [mathematical operator] [n2] [operator] ... [nf] = [result]
##Exponentiation and nth roots should only take in two numbers
##Quitting should terminate the program
#Once any option other than quitting is complete, ask the user if they would like to continue or quit. If the user chooses to continue, restart the calculator. Otherwise, call your quit function
def calc():
inp = input("Select a function: add, subtract, multiply, divide, exponent, root, or quit")
while(True):
if(inp == "add"):
add()
elif(inp=="subtract"):
subtract()
elif(inp=="multiply"):
multiply()
elif(inp=="divide"):
divide()
elif(inp=="exponent"):
exponent()
elif(inp=="root"):
root()
elif(inp=="quit"):
break
else:
print("Please input valid command")
inp = input("Select a function: add, subtract, multiply, divide, exponent, root, or quit")
def add():
n = int(input("How many addends?"))
total = 0
final = ""
for x in range(0,n):
a = int(input("Type number: "))
final = final + (str(a) + " + ")
total = total + a
final = final[0:(int(len(final))-2)] + "= " + str(total)
print(final)
def subtract():
n = int(input("How many numbers?"))
a = int(input("Type number: "))
total = a
final = str(a) + " - "
for x in range(0,n-1):
a = int(input("Type number: "))
final = final + (str(a) + " - ")
total = total - a
final = final[0:len(final)-2] + "= " + str(total)
print(final)
def multiply():
n = int(input("How many multiplicands?"))
total = 1
final = ""
for x in range(0,n):
a = int(input("Type number: "))
final = final + (str(a) + " * ")
total = total * a
final = final[0:(int(len(final))-2)] + "= " + str(total)
print(final)
def divide():
n = int(input("How many dividends?"))
a = int(input("Type number: "))
total = a
final = str(a) + " / "
for x in range(0,n-1):
a = int(input("Type number: "))
final = final + (str(a) + " / ")
total = total / a
final = final[0:len(final)-2] + "= " + str(total)
print(final)
def exponent():
a = input("Input base: ")
b = input("Input exponent: ")
print(str(a) + "^" + str(b) + " = " + str(int(a)**int(b)))
def root():
a = input("Input number to be rooted: ")
b = input("Input degree of root: ")
print("sqrt_" + str(b) + "(" + str(a) + ") = " + str(int(a)**(1.0/int(b))))
calc()
| true |
f9a6db7ed20a3239f624cebf30eb2953400756f2 | cynthiachuang72/Python-Bootcamp | /Beginner/Pizza_Order/main.py | 798 | 4.1875 | 4 | print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want (S, M, or L)? ")
add_pepperoni = input("Do you want pepperoni (Y or N)? ")
extra_cheese = input("Do you want extra cheese (Y or N)? ")
additional_price = 0
if (extra_cheese == 'Y' or extra_cheese == 'y'):
additional_price += 1
if (size == 'S' or size == 's'):
base_price = 15
if (add_pepperoni == 'Y' or add_pepperoni == 'y'):
additional_price += 2
elif (size == 'M' or size == 'm'):
base_price = 20
if (add_pepperoni == 'Y' or add_pepperoni == 'y'):
additional_price += 3
elif (size == 'L' or size == 'l'):
base_price = 25
if (add_pepperoni == 'Y' or add_pepperoni == 'y'):
additional_price += 3
print("Total price = " + str(base_price + additional_price)) | true |
a3ceeed3025eb5641d7871f23f7d6f7a074765a2 | Dejesusj9863/CTI110 | /M5HW2_DeJesusJose.py | 705 | 4.125 | 4 | # CTI 110
# M5HW2 - Running Total
# Jose De Jesus
# October 12, 2017
# user enters numbers and once the user inputs a negative number
# the program will stop asking and then add the numbers excluding the negative
def main():
# Variables
total = 0
sum = 0
# User input for number
inputnum = float(input("Enter a number? "))
# While loop for inputnum
while inputnum >= 0:
# Sum of all inputs, excluding the negative
sum = sum + inputnum
inputnum = float(input("Enter a number? "))
print()
# Total sum of inputted numbers
print("Total: ", format(sum, ',.2f'))
# Program Start
main()
| true |
2e9927050cf5e54af8575e5d03dd5422ef1dee22 | Dejesusj9863/CTI110 | /M5T1_Turtle_Bonus_DeJesusJose.py | 1,434 | 4.1875 | 4 | # CTI 110
# M5T1 - Bonus
# Jose De Jesus
# October 19, 2017
# Create a snowflake with turtle
import turtle # Allows me to use turtles
wn = turtle.Screen() # Creates a playground for turtles
wn.bgcolor("lightblue") # Set the window background color
wn.title("SI VIS PACEM PARA BELLUM") # set the window title
# (latin: if you want peace, prepare for war)
frank = turtle.Turtle() # Creates turtle named frank
frank.pensize(4) # Pensize increase
frank.color("white") # Changes turtle color to red
frank.shape("turtle") # Changes turtle's shape
numFlakes = int(input("Number of flakes: ")) # Asks the user how many flakes they want
for i in range(numFlakes): # A for loop of how many flakes
for i in range(2): # A for loop for the shape of the flake
frank.forward(100)
frank.right(60)
frank.forward(100)
frank.right(120)
frank.right(360 / numFlakes) # This is so that the angle is consistant
# and makes it go all the way around
wn.exitonclick()
| true |
7127ca22d1fa3d3cd9a40a09bea386e9feb284da | ELKHALOMAR/py_snippets | /exo9.py | 1,003 | 4.15625 | 4 | #Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low, too high,
# or exactly right. (Hint: remember to use the user input lessons from the very first exercise)
#Extras:
#Keep the game going until the user types “exit”
#Keep track of how many guesses the user has taken, and when the game ends, print this out.
import random
z=0
while True:
a = random.randint(1, 9)
user = int(input("enter a number between 1 and 9:"))
if a == user:
print("exact, you guessed well")
elif user > a:
print('to high, The exact number is', a)
else:
print('to low, The exact number is', a)
z += 1
play = input("do you want to replay (y/n):")
if play in ("y", "n"):
if play == "y":
continue
else:
print("you gessed", z, "times")
print("goodbye")
break
else:
print("false entry")
break
| true |
830bc292cfc30261a2a405d9a38a019e2d4b9665 | vini-2002/LeetCode-Solutions | /Array/23.Merge k Sorted Lists/Python Solution/Solution.py | 1,194 | 4.125 | 4 | """
23.Merge k Sorted Lists
Link:- https://leetcode.com/problems/merge-k-sorted-lists/
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] is sorted in ascending order.
The sum of lists[i].length won't exceed 10^4.
"""
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
fi=[]
for i in lists:
t=i
while t!=None:
fi.append(t.val)
t=t.next
fi=sorted(fi)
if len(fi)==0:
return None
p=ListNode(fi.pop(0))
t=p
while len(fi)>0:
p.next=ListNode(fi.pop(0))
p=p.next
return t
| true |
ce6d1668b168f4644dd4103e96ce3b6ddab50aea | anshulrts/pythonconcepts | /05_Functions.py | 880 | 4.375 | 4 | # Functions in Python start with def keyword
# The return value of a Python function can be any object.
# Everything in python is an object. So you functions can return numeric, collections, user
# defined objects, classes, functions even modules & packages.
# They always return a value, even if you don't specify a return statement
# You can omit the return value of a function and use a bare return without a return value.
# You can also omit the entire return statement. In both cases, the return value will be None.
# Returning Multiple Values
# In Python, you can return multiple values. You just need to separate them by comma.
def returnmultiple():
return 1, 2, 3
desc = returnmultiple()
print(desc)
# desc becomes a tuple here storing all 3 values
a, b, c = returnmultiple()
print(a,b,c)
# This concept of unpacking in 3 variables is called a iterable unpacking. | true |
118bd314c9d6bc4e055c9b621617393821438d0f | Ritikajain18/Problem-Solving | /Designer PDF Viewer.py | 960 | 4.125 | 4 | '''
When you select a contiguous block of text in a PDF viewer, the selection is highlighted
with a blue rectangle. In this PDF viewer, each word is highlighted independently.
In this challenge, you will be given a list of letter heights in the alphabet and a string.
Using the letter heights given, determine the area of the rectangle highlight in mm2 assuming
all letters are 1mm wide.
For example, the highlighted word = torn. Assume the heights of the letters are t=2, o=1, r=1, n=1.
The tallest letter is 2 high and there are 4 letters. The hightlighted area will be 2*4=8 mm
so the answer is 8.'''
def get_rect_height(word, height_arr):
height = 0
for c in word:
height = max(height, height_arr[ ord(c) - ord("a") ])
#ord(character) gives the ascii value
return height
heights = [int(x) for x in input().split()] #scan heights
word = input()
print(len(word) * get_rect_height(word, heights))
| true |
394502005f25b506fd08218bbb55dda6894fc110 | Ritikajain18/Problem-Solving | /Grading_Students.py | 1,131 | 4.21875 | 4 | '''
HackerLand University has the following grading policy:
Every student receives a grade in the inclusive range from 0 to 100.
Any grade less than 40 is a failing grade.
Sam is a professor at the university and likes to round each student's grade according to
these rules:
If the difference between the grade and the next multiple of 5 is less than 3, round grade
up to the next multiple of 5.
If the value of grade is less than 38, no rounding occurs as the result will still be a failing
grade.
For example, grade=84 will be rounded to 85 but grade=29 will not be rounded because the rounding would
result in a number that is less than 40 .
Given the initial value of grade for each of Sam's n students, write code to automate the
rounding process.
'''
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
for _ in range(int(input())):
x = int(input())
x = x-x%5+5 if x%5>2 and x>=38 else x
print(x)
| true |
5901182dde67dad51e43cf1118f8da175bab0db5 | Ritikajain18/Problem-Solving | /Staircase.py | 534 | 4.46875 | 4 | '''
Consider a staircase of size n :
#
##
###
####
Observe that its base and height are both equal to n, and the image is
drawn using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n .'''
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(1, n+1): print(str('#' * i).rjust(n))
if __name__ == '__main__':
n = int(input())
staircase(n)
| true |
d7e00d150d41fe04bdf5b18c3a9c285de188d228 | llenroc/facebook-interview-question-data | /python/monotobnic.py | 464 | 4.28125 | 4 | ## Given an array of integers, we would like to determine whether the array is monotonic (non-decreasing/non-increasing) or not.
## https://www.geeksforgeeks.org/python-program-to-check-if-given-array-is-monotonic/ -- One solution available here
# Monotonic -
def isMonotonic(A):
return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or
all(A[i] >= A[i + 1] for i in range(len(A) - 1)))
# Input and Main
A = [1,2,3,4,7,8]
print(isMonotonic(A))
| true |
b4be11ac7af53ac94a422bfba1accbd8557fdc46 | jakehoare/leetcode | /python_1_to_1000/354_Russian_Doll_Envelopes.py | 2,407 | 4.25 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/russian-doll-envelopes/
# You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit
# into another if and only if both the width and height of one envelope is greater than the width and height of the
# other envelope. What is the maximum number of envelopes can you Russian doll? (put one inside other)
# Create nested envelopes by wrapping larger ones around smaller. Sort by increasing width, with ties broken by
# decreasing height. If widths are unique then when envelopes are considered in order we can always wrap the
# next envelope around any previous in the width dimension. If widths are same then largest height first ensures we
# do not put same width envelopes inside each other.
# Maintain a list of the smallest outer envelope height for each number of nested envelopes. For each envelope find the
# longest nested list that can be extended. Update the best extended list with the new envelope if it has smaller
# height, or make a new longest list.
# Time - O(n log n)
# Space - O(n)
class Solution(object):
def maxEnvelopes(self, envelopes):
"""
:type envelopes: List[List[int]]
:rtype: int
"""
# increasing width, ties broken by decreasing height
envelopes.sort(key = lambda x : (x[0], -x[1]))
# nested[i] is smallest height outer envelope for i - 1 in total
nested = []
# find the index of the first number in nested >= target
# i.e. the first nested that can be improved (or stay same) by target
# i.e. index after last nested than target can increase
def bin_search(target):
left, right = 0, len(nested) - 1
while left <= right:
mid = (left + right) // 2
if target > nested[mid]: # first greater than target must be on RHS
left = mid + 1
else: # target <= nested[mid], target cannot fit around nested[mid] so look st LHS
right = mid - 1
return left
for _, h in envelopes:
i = bin_search(h)
if i == len(nested):
nested.append(h)
else:
nested[i] = h # h <= nested[i] so nested[i] can only improve
return len(nested)
| true |
8b9ea814605ce85ab31ea9bd73aca1ddb5e7bad3 | jakehoare/leetcode | /python_1_to_1000/831_Masking_Personal_Information.py | 2,738 | 4.21875 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/masking-personal-information/
# We are given a personal information string S, which may represent either an email address or a phone number.
# We would like to mask this personal information according to the following rules:
# 1. Email address:
# We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z.
# An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.'
# and followed by a name.
# All email addresses are guaranteed to be valid and in the format of "name1@name2.name3".
# To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the
# first name must be replaced by 5 asterisks '*'.
# 2. Phone number:
# A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}.
# You may assume a phone number contains 10 to 13 digits.
# The last 10 digits make up the local number, while the digits before those make up the country code.
# Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits.
# The local number should be formatted and masked as "***-***-1111", where 1 represents the exposed digits.
# To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+***-***-***-1111".
# The '+' sign and the first '-' sign before the local number should only exist if there is a country code.
# For example, a 12 digit phone number mask should start with "+**-".
# Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above
# formatting scheme should be removed.
# Return the correct "mask" of the information provided.
# If S contains "@" it is an email. Split email by "@", amend name to first and last letters.
# If phone, retain all digits and split into country (maybe empty) and local.
# Time - O(n)
# Space - O(n)
class Solution(object):
def maskPII(self, S):
"""
:type S: str
:rtype: str
"""
if "@" in S:
name, address = S.lower().split("@")
return name[0] + "*****" + name[-1] + "@" + address
digits = [c for c in S if "0" <= c <= "9"] # remove all non-digits
country, local = digits[:-10], digits[-10:] # split country and local numbers
result = []
if country:
result = ["+"] + ["*"] * len(country) + ["-"] # masked country with "+" prefix
result += ["***-***-"] + local[-4:] # masked local apart from last 4 digits
return "".join(result)
| true |
a15a9664cfdb3ab2b29be58fa6a81b226fbd5319 | jakehoare/leetcode | /python_1_to_1000/520_Detect_Capital.py | 1,272 | 4.125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/detect-capital/
# Given a word, you need to judge whether the usage of capitals in it is right or not.
# We define the usage of capitals in a word to be right when one of the following cases holds:
# All letters in this word are capitals, like "USA".
# All letters in this word are not capitals, like "leetcode".
# Only the first letter in this word is capital if it has more than one letter, like "Google".
# Otherwise, we define that this word doesn't use capitals in a right way.
# For the first and second letter, the only disallowed combination is lower case then upper case. All letter after
# the second character must be the same case as the second character.
# Time - O(n)
# Space - O(1)
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if len(word) <= 1: # empty string or single letter
return True
first = word[0] <= "Z"
second = word[1] <= "Z"
if not first and second: # first is not capital but second is
return False
for c in word[2:]:
if (c <= "Z") != second:
return False
return True | true |
0eca912eb359b3f343f06bda2874208395d5db17 | jakehoare/leetcode | /python_1_to_1000/678_Valid_Parenthesis_String.py | 1,629 | 4.15625 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/valid-parenthesis-string/
# Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this
# string is valid. We define the validity of a string by these rules:
# 1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# 2. Any right parenthesis ')' must have a corresponding left parenthesis '('.
# 3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
# 4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
# 5. An empty string is also valid.
# Track the range of possible open brackets when iterating over s. If "(" is seen, both bounds of range increase. If
# ")" is seen both bounds decrease subject to the lower bound not becoming negative. If "*" is seen, upper bound
# increase and lower bound decreases, subject to zero. Upper bound can never be less than zero. Lower bound must be
# zero at end of s.
# Time - O(n)
# Space - O(1)
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
min_open, max_open = 0, 0
for c in s:
if c == "(":
min_open += 1
max_open += 1
elif c == ")":
min_open = max(0, min_open - 1)
max_open -= 1
else:
min_open = max(0, min_open - 1)
max_open += 1
if max_open < 0:
return False
return min_open == 0
| true |
0bf9cba8b0bfdc9a5657c4f81fb2a00d4474b074 | jakehoare/leetcode | /python_1_to_1000/147_Insertion_Sort_List.py | 1,268 | 4.125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/insertion-sort-list/
# Sort a linked list using insertion sort.
# Maintain a sorted part of the list. For each next node, find its correct location by iterating along sorted section.
# Time - O(n**2)
# Space - O(1)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
sorted_tail = dummy = ListNode(float('-inf')) # sorted_tail is last node of sorted section
dummy.next = head
while sorted_tail.next:
node = sorted_tail.next
if node.val >= sorted_tail.val: # node already in correct place
sorted_tail = sorted_tail.next
continue
sorted_tail.next = sorted_tail.next.next # cut out node
insertion = dummy
while insertion.next.val <= node.val:
insertion = insertion.next
node.next = insertion.next # put node after insertion
insertion.next = node
return dummy.next
| true |
052eacf4b9b260e9f144446f172b81216946933c | jakehoare/leetcode | /python_1001_to_2000/1213_Intersection_of_Three_Sorted_Arrays.py | 842 | 4.15625 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/intersection-of-three-sorted-arrays/
# Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order,
# return a sorted array of only the integers that appeared in all three arrays.
# Count the frequency across all arrays.
# Return the items that occur 3 times.
# This works because the arrays are strictly increasing, i.e. no duplicates.
# Also works if the arrays are not sorted.
# Time - O(n)
# Space - O(n)
from collections import Counter
class Solution(object):
def arraysIntersection(self, arr1, arr2, arr3):
"""
:type arr1: List[int]
:type arr2: List[int]
:type arr3: List[int]
:rtype: List[int]
"""
return [i for i, count in Counter(arr1 + arr2 + arr3).items() if count == 3]
| true |
1c6284e36e312ce42ee7fc7aa7a19f6e191e6b11 | jakehoare/leetcode | /python_1_to_1000/545_Boundary_of_Binary_Tree.py | 2,267 | 4.125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/boundary-of-binary-tree/
# Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary
# includes left boundary, leaves, and right boundary in order without duplicate nodes.
# Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from
# root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left
# boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.
# The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree
# if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.
# The right-most node is also defined by the same way with left and right exchanged.
# Find left edge until leaf. Inorder traversal to append all leaves. Find right edge and reverse.
# Time - O(n)
# Space - O(n)
class Solution(object):
def boundaryOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def left_side(node):
if not node or (not node.left and not node.right):
return
boundary.append(node.val)
if node.left:
left_side(node.left)
else:
left_side(node.right)
def right_side(node):
if not node or (not node.left and not node.right):
return
right_edge.append(node.val)
if node.right:
right_side(node.right)
else:
right_side(node.left)
def inorder(node):
if not node:
return
inorder(node.left)
if not node.left and not node.right:
boundary.append(node.val)
inorder(node.right)
if not root:
return []
boundary, right_edge = [root.val], []
# ignore root
left_side(root.left)
inorder(root.left)
inorder(root.right)
right_side(root.right)
return boundary + right_edge[::-1] | true |
30ff3d4d8f4a67a2520ada5f65fbba374bcbc995 | jakehoare/leetcode | /python_1_to_1000/101_Symmetric_Tree.py | 1,208 | 4.15625 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/symmetric-tree/
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
# Check if left and right subtrees are both present or not, then if root values are equal. Then recurse on their
# subtrees being mirrors - left/left of right/right and left/right of right/left
# Time - O(n)
# Space - O(n)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.is_mirror(root.left, root.right)
def is_mirror(self, left_node, right_node):
if not left_node and not right_node:
return True
if not left_node or not right_node:
return False
if left_node.val != right_node.val:
return False
return self.is_mirror(right_node.right, left_node.left) and \
self.is_mirror(left_node.right, right_node.left) | true |
85c4ba76b35aaeaef8c0a5b8e2a17cc17f4c279f | jakehoare/leetcode | /python_1_to_1000/284_Peeking_Iterator.py | 1,234 | 4.125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/peeking-iterator/
# Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that
# supports the peek() operation -- i.e. returns the element that will be returned by the next call to next().
# Store the next iterator result and return it when peeking.
# Time - O(1)
# Space - O(1)
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.front = None
self.it = iterator
if self.it.hasNext():
self.front = self.it.next()
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.front # None if not iterator.hasNext()
def next(self):
"""
:rtype: int
"""
temp = self.front
self.front = None
if self.it.hasNext(): # replace front
self.front = self.it.next()
return temp
def hasNext(self):
"""
:rtype: bool
"""
return bool(self.front)
| true |
bbe3bfbeac20116cecb0b9736753ec1a8a1b216a | jakehoare/leetcode | /python_1_to_1000/885_Spiral_Matrix_III.py | 2,281 | 4.3125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/spiral-matrix-iii/
# On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.
# Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the
# grid is at the last row and column.
# Now, we walk in a clockwise spiral shape to visit every position in this grid.
# Whenever we would move outside the boundary of the grid, we continue our walk outside the grid
# (but may return to the grid boundary later.)
# Eventually, we reach all R * C spaces of the grid.
# Return a list of coordinates representing the positions of the grid in the order they were visited.
# Move in a spiral until all cells of the grid have been visited. Step along each side, then turn to next direction.
# Each cell visited within the grid is appended to the result. Spiral has two sides of the same length, then two sides
# of length + 1, etc.
# Time - O(max(m, n)**2)
# Space - O(mn)
class Solution(object):
def spiralMatrixIII(self, R, C, r0, c0):
"""
:type R: int
:type C: int
:type r0: int
:type c0: int
:rtype: List[List[int]]
"""
moves = [[0, 1], [1, 0], [0, -1], [-1, 0]] # change in r and c foa move in each direction
r, c = r0, c0
direction = 0
result = [[r0, c0]]
side = 1 # current length of side of spiral
while len(result) < R * C:
dr, dc = moves[direction]
for _ in range(side): # step along the side
r += dr
c += dc
if 0 <= r < R and 0 <= c < C: # append to result if within bounds of grid
result.append([r, c])
direction = (direction + 1) % 4 # next direction
dr, dc = moves[direction]
for _ in range(side):
r += dr
c += dc
if 0 <= r < R and 0 <= c < C:
result.append([r, c])
direction = (direction + 1) % 4
side += 1 # after 2 sides of spiral, increase side length
return result | true |
e9be4b70f91f85c2deed3a16283ed3de7871a295 | Davin-Rousseau/ICS3U-Assignment-4-Python | /question_12.py | 861 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: Davin Rousseau
# Created on October 2019
# This program asks user to enter classes held and attended
# and tells them if they can write an exam or not
def main():
# This function calculates if student can write exam
# input
number = input("Enter number of classes held: ")
number2 = input("Enter number of classes attended: ")
print("")
# process
try:
classes_held = int(number)
classes_attended = int(number2)
percentage = (classes_attended / classes_held) * 100
print("The percentage of attendance is: {}%".format(percentage))
if (percentage >= 75.0):
print("You may take the exam.")
else:
print("You may not take the exam.")
except ValueError:
print("Invalid input.")
if __name__ == "__main__":
main()
| true |
6641466adb3ad7ec5d7c19691f3598a91465d092 | fantian669/web | /python/painting.py | 1,273 | 4.5 | 4 | # 转载于 http://www.kidscoderepo.com/python.html
#"Recursive Star"
# in Python you have to pay attention to the indentions as they are regrouping blocks of code!
import turtle
def star(turtle, n,r):
# draw a star with n branches of length d
for k in range(0,n):
turtle.pendown()
turtle.forward(r)
turtle.penup()
turtle.backward(r)
turtle.left(360/n)
def recursive_star(turtle, n, r, depth, f):
# At each point of a star, draw another (smaller) star, and repeat this depth times
if depth == 0:
star(turtle, n, f*4)
else:
for k in range(0,n):
turtle.pendown()
turtle.forward(r)
recursive_star(turtle, n, f*r, depth - 1,f)
turtle.penup()
turtle.backward(r)
turtle.left(360/n)
# This is the actual code of the main loop
fred = turtle.Turtle()
fred.speed("fastest")
recursive_star(fred, 5 , 150, 4, 0.4)
# "A black and red triangle"
# turtle.color("red", "black")
# turtle.begin_fill()
# for _ in range(3):
# turtle.forward(100)
# turtle.left(120)
# turtle.end_fill()
# # "A spiral out of squares"
# import turtle
# size=1
# while (True):
# turtle.forward(size)
# turtle.right(91)
# size = size + 1 | true |
29f0dded2b2b061bd3792dbeefa614a8aaa5a076 | KFOAS/automate-the-boring-stuff | /find_files_by_size/find_files_by_size.py | 1,412 | 4.25 | 4 | #! /usr/bin/env python3
# find_files_by_size.py - finds files along a specified path larger than
# a specified threshold in size
import os
def find_large_files(path, threshold):
"""
Finds all files whose size is greater than or equal to threshold and
prints their absolute path and size to the console
:param str path: path to directory to search
:param int threshold: size threshold in bytes
"""
path = os.path.abspath(path)
print(f'Searching for contents above the size: {threshold / 1_000_000:,.3f} MB'
f'\n\tSearching {path}\n')
for content in os.listdir(path):
filepath = os.path.join(path, content)
if os.path.isdir(filepath):
size = get_dir_size(path=filepath)
else:
size = os.path.getsize(filepath)
if size >= threshold:
print(f'{filepath}: {size / 1_000_000:,.3f} MB')
def get_dir_size(path):
"""
Get's the cumulative size of a directory and all of it's contents
:param str path: absolute path to directory
:return: int cumulative size of directory
"""
size = 0
for root, _, files in os.walk(path):
for file in files:
filepath = os.path.join(root, file)
size += os.path.getsize(filepath)
return size
if __name__ == '__main__':
find_large_files(path=os.path.join('..', '..', '..'), threshold=1_000_000)
| true |
1b6d6d4a9fc4c1aa3be7f9cea43c10171e76130f | HarrisonBacordo/MegaProject | /Text/Palindrome Checker.py | 498 | 4.34375 | 4 | string_to_reverse = input("Welcome to the palindrome checker! Type in any length of string, and I'll"
" check if it's a palindrome\n")
reverse = []
is_palindrome = True
for i in range(len(string_to_reverse), 0, -1):
reverse.extend(string_to_reverse[i-1])
for i in range(len(string_to_reverse)):
if reverse[i] != string_to_reverse[i]:
is_palindrome = False
print("NOT A PALINDROME")
break
if is_palindrome:
print("IT IS A PALINDROME")
| true |
4f02c2a17a40e4ec3fdc3031fa67e05fb57c9c54 | jmstudyacc/Cisco_DevNet | /devasc/DevNet_Fundamentals/APIs/http_post_urllib.py | 1,983 | 4.21875 | 4 | """
A virtual library exists.
You need query what the books are in the virtual library
You've queried the books, but now it's time to ADD a book, how do?
"""
# Perhaps you cannot download other libraries and only have the standard Python library
# You should then use the 'urllib' library that is native to Python
import urllib.request
import json
# Define the URL variable which will be used to hold the target server
url = "http://localhost:8080/v1/books" # Note this is a STRING
"""
Adding a book is harder than just getting a book
You need to know the required fields and how these are formatted
That can usually be found out by consulting the documentation for the API
In this case the following is needed:
- Book name e.g. 'The Art of Computer Programming'
- Book author e.g. 'Donald Knuth'
- Publish Date e.g. 1968
- Book ISBN e.g. "0-201-03801-3"
The above details builds the minium for a book in the virtual library
As we are using JSON, we will represent this information in a dictionary
N.B. Pay close attention to the data types represented, we have Strings of Letters, Integers and Strings of Numbers - If you use an incorrect data type the POST request will ultimately fail!
"""
book = { # Think of this book as an object we are creating and defining
'name': 'The Art of Computer Programming',
'authors': 'Donald Knuth',
'date': 1968,
'isbn': '0-201-03801-3'
}
# This all looks pretty similar to the 'requests' library, but here is where things change
payload = json.dumps(book).encode('utf8')
request = urllib.request.Request(url, data=payload, headers={'Content-Type': 'application/json'})
response = urllib.request.urlopen(request)
print(response.status)
# As you can see there is a lot more configuration on your behalf with the urllib library
# In fact, that neat autopopulate of the 'Content-Type' header is lost when using urllib
# There is more syntax and some of it is less intuitive than the 'requests' library | true |
e8f5519ad7b100d6e096dc33e58f8bf7bac2956f | jmstudyacc/Cisco_DevNet | /devasc/3_designing_software/singleton_example.py | 1,302 | 4.15625 | 4 | """
Singleton patterns are useful as they enable global access to an object, without creating a global variable.
Globals may seem a neat way to resolve the issue, but they run the significant threat of being overridden.
Other content may be erroneously stored in the GLOBAL variable causing unknown amounts of damage. The Singleton
pattern provides similar capability but protects the object from being overwritten.
This protection comes in the form:
- Making the class constructor private
- Creation of static method that returns the original instance to the caller
Class DataAccess() can only be instantiated once. The __init__() constructor first checks if an object instance
already exists and if it does an error is raised. If there is a requirement to access the object it should retrive
the instance by using get_instance()
"""
class DataAccess:
__instance = None
@staticmethod
def get_instance(): # this line defines the client access method
if DataAccess.__instance is None:
DataAccess()
return DataAccess.__instance
def __init__(self):
if DataAccess.__instance is not None: # this line is used in preventing new object creation
raise Exception("Instance exists")
else:
DataAccess.__instance = self
| true |
9a7b75c650843ab4bf99a528c8588afac5a06f2f | rohitpawar4507/Zensar_Python | /File_Handling/Files.py | 731 | 4.5 | 4 | print("Creating a file for the first time.")
#If you open a file in mode x , the file is created and opened for writing – but only if it doesn't already exist
'''f1 = open("file1.txt","x") # create a new file
print(f1)
if f1:
print("File created Successfully")
else:
print("The file is not created")
'''
# Create file in write mode -> if file already present
# it does give error
'''f1 = open("file2.txt","w") # create a new file
print(f1)
if f1:
print("File created Successfully")
else:
print("The file is not created")
'''
# Create file in append mode
f1 = open("file2.txt","r") # create a new file
print(f1)
if f1:
print("File created Successfully")
else:
print("The file is not created") | true |
10754746c14c3fce54d95a4b5e75cf81e457c1c7 | rohitpawar4507/Zensar_Python | /Dicitionary.py | 2,195 | 4.1875 | 4 | ''' Dictionary :: Collection of different element in key value pairs enclosed in {} seprated by comas
It is mutable object .
# Key -- value pair -- Both number and string are used for key as well as value
'''
# Create a dicitionary
print("The Program for Dictionary!!!")
print("Creating a dictionary and adding element on it..")
d1={1:'Nashik',2:"Pune",3:"Aurangabad"}
print("The Dict is :",d1)
print("Adding element to the dict..")
d1['Nsk']=101
d1['Aug']=108
d1['Pun']=103
print("The dictiionary is ",d1)
print("The element is ",d1[1])
print("The element is ",d1[2])
print("The element is ",d1[3])
d1[4]="Khalapur"
print("The updated dict is..",d1)
print("Creating an empty dictionary..")
d2={}
d2[0]=100
d2[1]=102
print("The Dict is..",d2)
a=d2.get(1)
print(a)
d2[1]=105
print(d2[1])
d1[4]="Jamkhed"
d1[5]="Goa"
print(d1)
#Deleting element from dict
print("Delecting the element in the dictionary")
print("THe original dict is..",d1)
d1.pop(3) # atleast one argument required
print("The dictionary is ",d1)
# Deleting all element in the dictionary / clear()
d3={1:'Rohit',2:"Om",3:"Rahul"}
d3.clear()
print("The dictionary is..",d3)
# Delete the dict by using del()
'''print("Deleting a Dictionary!!!")
d4={1:'Rohan',2:"Omkar",3:"Raj"}
print(d4)
del d4
print("The dictionary is..",d4)
'''
# Iterate a Dicitionary
print("Iterating the Dictionary")
print("Printing the keys using for loop")
for x in d1: # Printing the keys
print(x,end=' ,')
print("\nPrinting the Values using for loop")
for x in d1.values(): # Printing the values
print(x,end=' ,')
print("\nPrinting the values using for loop")
for x in d1: # printing the values
print(d1[x],end=',')
print("\nPrinting the Values and Keys using for loop")
for x,y in d1.items(): # printing the key and value
print("Key = ",x," Value = ",y)
### Assignment ###
#4. convert tuple into dictionary
#8. Return a element with key 101 from student dict
#7. Delete one element from student dict
#9. print only keys from dict student
#10. print only value from dict student
#11. creat a dict employee with ename as key and salary as value.
#12. print the employee dict
#13. delete the employee with salary -10000 | true |
da0210641908a142375622b05233274c8d90926c | rohitpawar4507/Zensar_Python | /OOPS/Circele_method.py | 681 | 4.1875 | 4 | # Methods : It is regular function
# Self : similar to this keyword in java. -> reference to the current object
print("Creating a circle class..!")
class Circle:
def __init__(self):
self.radius =1
def area(self):
return 2*3.14*self.radius
print("Creating the object...")
c=Circle()
print("Radius is: ",c.radius)
print("Area of Circle is :",c.area())
c.radius=3
print("Radius is: ",c.radius)
print("Area of Circle is :",c.area())
# 1 - Self is set to the newly created instance when __init__ is run.
# 2 - We create Circle instance object
# 3 - Radius is already initailized
# 4 - We override the radius field
# __init__ -> Nothing but constructor
| true |
490a3d103acac647eefc9d1a7a115266fd906a93 | rohitpawar4507/Zensar_Python | /Exception_Handling/Exception2.py | 936 | 4.28125 | 4 | #finally block
'''
try
except
finally
first except block execute and then finally executed
'''
try:
print('Inside try block ')
try:
a = int(input('Enter no :'))
b = int(input('Enter b :'))
c = a / b
print('a/b=%d' % c)
except NameError:
print('Except for inner try ')
finally: # it will exceute no matter error hai ya nahi hai AS many try those many finally can take
print('Inner Finally Block -Executed')
except ZeroDivisionError:
print('Inside Except Block for ZeroDivisionError of outer try')
print('The value of b cannot be zero')
except NameError:
print('Inside except block for NameError for outer try' )
print('Some variable may not definied ')
except: # handle another exception other than above 3
print('Inside except block for all other Exception for outer try')
finally:
print('THIS IS OUTER FINALLY BLOCK ')
print('Code Complete') | true |
5fb3169cff2fa78c90a8bb0ad0ac8ba23b21e689 | tri2sing/PyFP | /higher_order_functions/min_max.py | 1,362 | 4.3125 | 4 | '''
Created on Dec 19, 2015
@author: Sameer Adhikari
'''
# Examples demonstrating the use of max and min as a higher-order function.
def getx(point):
x, y, z = point
return x
def gety(point):
x, y, z = point
return y
def getz(point):
x, y, z = point
return z
# The pattern in these points is to get distinct answers for max and min in each dimension
points3D = [(1, 5, 9), (4, 8, 3), (7, 2, 6)]
print('Points = {}'.format(points3D))
print(64*'-')
print('Defined function used in key')
print('Point max x = {}'.format(max(points3D, key=getx)))
print('Point max y = {}'.format(max(points3D, key=gety)))
print('Point max z = {}'.format(max(points3D, key=getz)))
print('Point min x = {}'.format(min(points3D, key=getx)))
print('Point min y = {}'.format(min(points3D, key=gety)))
print('Point min z = {}'.format(min(points3D, key=getz)))
print(64*'-')
print('Lambda form used in key')
print('Point max x = {}'.format(max(points3D, key=lambda point: point[0])))
print('Point max y = {}'.format(max(points3D, key=lambda point: point[1])))
print('Point max y = {}'.format(max(points3D, key=lambda point: point[2])))
print('Point min x = {}'.format(min(points3D, key=lambda point: point[0])))
print('Point min y = {}'.format(min(points3D, key=lambda point: point[1])))
print('Point min y = {}'.format(min(points3D, key=lambda point: point[2])))
| true |
08cd6a1815bd9cc6557500934ea1c85af609aa29 | RawnaKirahs/InternShip | /Day5_Tasks.py | 772 | 4.34375 | 4 | TASKS :
1)Create a function getting two integer inputs from user. & print the following:
Addition of two numbers is +value
Subtraction of two numbers is +value
Division of two numbers is +value
Multiplication of two numbers is +value
2. Create a function covid( ) & it should accept patient name, and body temperature, by default the body temperature should be 98 degree
TASK#1 :
def arithmetic(a,b):
print("Addition = ",a+b)
print("Subtraction = ",a-b)
print("Multiplication = ",a*b)
print("Division = ",a/b)
x=int(input("First Num = "))
y=int(input("Second Num = "))
arithmetic(x,y)
TASK#2
def covid(name,temp=98):
print("Patient Name : ",name)
print("Temperature : ",temp)
a=input("Enter the patient's name : ")
covid(a)
| true |
63cbbb1bc4da7e3bdd972e3ed32030e42af5875f | HariKumarValluru/Python | /ContinueBreakElse/continueBreak.py | 955 | 4.25 | 4 | # Continue example
# shoppingList = ['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice']
# for item in shoppingList:
# if item == 'spam':
# continue
# print('Buy '+item)
# Break example 1
#
# shoppingList = ['milk', 'pasta', 'eggs', 'spam', 'bread', 'rice']
# for item in shoppingList:
# if item == 'spam':
# break
# print('Buy '+item)
# Break example 2
# meal = ['egg', 'backon', 'spam', 'sausages']
# nastyFoodItem = ""
# for item in meal:
# if item == 'spam':
# nasty_item = item
# break
# if nasty_item:
# print("Can't I have anything without spam in it")
# else example (else will be used in for loops)
meal = ['egg', 'beckon', 'beans', 'sausages']
nasty_food_item = ""
for item in meal:
if item == 'spam':
nasty_food_item = item
break
else:
print("I will have plate of them, then, please")
if nasty_food_item:
print("Can't I have anything without spam in it")
| true |
dc4f94d6ca74c5501bb2abacbcd74db10633c54d | PauliSpin/HintsAndTips | /unpack.py | 743 | 4.65625 | 5 | x = [1, 2, 3, 4, 5]
print(*x) # prints 1 2 3 4 5
# * is theunpack operator and print(*x) prints unpack and prints out the elements of the list
# This is used in arguments to functions and can be used
# to pass an unlimited number of arguments
def func(*args):
print(args)
func(2, 3) # prints the tuple (2, 3)
func(8, 7, 6, 5, 3) # prints the tuple (8, 7, 6, 5, 3)
# This operator work ondictionaries as well:
def func2(*args, **kwargs):
# this has taken a dictionary and uses the key as the name and the value as the value of the argument
print(args, kwargs)
print(type(args), type(kwargs))
func2(2, 3, k=0, x=8, hey=10)
# prints
# (2, 3) {'k': 0, 'x': 8, 'hey': 10}
# <class 'tuple'> <class 'dict'>
| true |
22a55344060e289a52f60efbc46a30c83d2c8dbf | patelrohan750/python_tutorials_codewithharry | /python_tutorials_code/tut11_example_Apni_dictonary.py | 279 | 4.25 | 4 | # Exrersice:1
# create a dictionary and take input from user and return the meaning of taht word in dictonary
dict = {"A": "Apple", "B": "Ball", "C": "Cat", "D": "Dog", "E": "Elephant"}
search = input("Enter Word: ")
print(f'your word meaning is: {dict[search.upper()]}')
| true |
12d4951b82f2b1abac1ccfd9d88f7486fb9f29be | a-falcone/puzzles | /adventofcode/2021/05a.py | 2,580 | 4.40625 | 4 | #!/usr/bin/env python3
"""
--- Day 5: Hydrothermal Venture ---
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible.
They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example:
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1,y1 are the coordinates of one end the line segment and x2,y2 are the coordinates of the other end. These line segments include the points at both ends. In other words:
An entry like 1,1 -> 1,3 covers points 1,1, 1,2, and 1,3.
An entry like 9,7 -> 7,7 covers points 9,7, 8,7, and 7,7.
For now, only consider horizontal and vertical lines: lines where either x1 = x2 or y1 = y2.
So, the horizontal and vertical lines from the above list would produce the following diagram:
.......1..
..1....1..
..1....1..
.......1..
.112111211
..........
..........
..........
..........
222111....
In this diagram, the top left corner is 0,0 and the bottom right corner is 9,9. Each position is shown as the number of lines which cover that point or . if no line covers that point. The top-left pair of 1s, for example, comes from 2,2 -> 2,1; the very bottom row is formed by the overlapping lines 0,9 -> 5,9 and 0,9 -> 2,9.
To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points.
Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
"""
def load_data(filename):
data = []
with open(filename, "r") as f:
for line in f:
line = line.strip().split(" -> ")
data.append((list(map(int,(line[0].split(",")))),list(map(int,(line[1].split(","))))))
return data
if __name__ == "__main__":
data = load_data("05.data")
field = {}
for line in data:
if line[0][0] == line[1][0] or line[0][1] == line[1][1]:
maxx, minx = max(line[0][0], line[1][0]), min(line[0][0], line[1][0])
maxy, miny = max(line[0][1], line[1][1]), min(line[0][1], line[1][1])
for x in range(minx, maxx + 1):
for y in range(miny, maxy + 1):
field[(x,y)] = field.get((x,y),0) + 1
print(len([v for v in field.values() if v > 1]))
| true |
aa46d0f91d883a1b316a74b286ff256b2a0a0dba | a-falcone/puzzles | /adventofcode/2019/04b.py | 1,781 | 4.21875 | 4 | #!/usr/bin/env python3
"""
You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.
However, they do remember a few key facts about the password:
It is a six-digit number.
The value is within the range given in your puzzle input.
Two adjacent digits are the same (like 22 in 122345).
Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
Other than the range rule, the following are true:
111111 meets these criteria (double 11, never decreases).
223450 does not meet these criteria (decreasing pair of digits 50).
123789 does not meet these criteria (no double).
How many different passwords within the range given in your puzzle input meet these criteria?
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following are now true:
112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.
123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22).
How many different passwords within the range given in your puzzle input meet all of the criteria?
"""
import re
c = 0
for i in range(265275,781584+1):
matches = False
s = str(i)
if re.search(r"^1*2*3*4*5*6*7*8*9*$", s):
groups = re.findall(r"(.)\1", s)
for g in groups:
if not re.search(re.escape(g) + r"{3}", s):
matches = True
if matches:
c += 1
print(c)
| true |
9fcd0c3e42f5301f69993e2530065e2dda9722d4 | rawg/levis | /levis/util/hilbert.py | 2,251 | 4.125 | 4 | """
Utilities to map between a 1D Hilbert curve and 2D Euclidian space.
See also:
- https://en.wikipedia.org/wiki/Hilbert_curve
- https://people.sc.fsu.edu/~jburkardt/py_src/hilbert_curve/hilbert_curve.html
- https://en.wikipedia.org/wiki/Moore_curve
"""
from __future__ import division
#from builtins import object
import math
def rotate(s, x, y, rx, ry):
"""Rotate a point."""
if ry is 0:
if rx is 1:
x = s - 1 - x
y = s - 1 - y
x, y = y, x
return (x, y)
def next_power_of_2(i):
"""Get the next power of 2 after ``i``."""
return int(math.pow(2, math.floor(math.log(i, 2)) + 1))
class HilbertCurve(object):
"""Translates two dimensional points to a Hilbert curve and back."""
def __init__(self, width):
if width <= 0:
raise ValueError("Width must be a positive integer")
if width & (width - 1) != 0:
width = next_power_of_2(width)
self.width = width
self.length = width ** 2 - 1
def to_1d(self, pointOrX, y=None):
"""Convert a 2D point to a location on a Hilbert Curve.
Returns:
Int: the location along a Hilbert Curve that matches the point.
"""
if y is None:
x, y = pointOrX
else:
x = pointOrX
rx = ry = d = 0
s = old_div(self.width, 2)
while s > 0:
rx = int((x & s) > 0)
ry = int((y & s) > 0)
d = d + s * s * ((3 * rx) ^ ry)
x, y = rotate(s, x, y, rx, ry)
s = int(old_div(s, 2))
return d
def to_2d(self, d):
"""Convert a 1D location along a Hilbert Curve to a 2D point.
Args:
d (Int): The location along a Hilbert Curve
Returns:
(Int, Int): The corresponding 2D point in Euclidian space.
"""
t = d
x = y = 0
s = 1
while s < self.width:
rx = (old_div(t, 2)) % 2
if rx is 0:
ry = t % 2
else:
ry = (t ^ rx) % 2
x, y = rotate(s, x, y, rx, ry)
x = x + s * rx
y = y + s * ry
t = t / 4
s = s * 2
return (x, y)
| true |
a2ef075616b8bad4f60045ddda5e00e65161e4c6 | vdduong/numerical-computation | /maze_walk.py | 1,197 | 4.40625 | 4 | # maze walking
# 0: empty cell
# 1: unreacheable cell e.g. wall
# 2: ending cell
# 3: visited cell
grid = [[0, 0, 0, 0, 0, 1],\
[1, 1, 0, 0, 0, 1],\
[0, 0, 0, 1, 0, 0],\
[0, 1, 1, 0, 0, 1],\
[0, 1, 0, 0, 1, 0],\
[0, 1, 0, 0, 0, 2]]
# the search function accepts the coordinates of a cell to explore.
# if it is the ending cell, it returns True
# if it is a wall or an already visited cell, it returns False
# if the neighboring cells are explored recursively and if nothing is found at the end, it returns False
# so it backtracks to explore new paths.
# we start at cell x=0, y=0
def search(x,y):
if grid[x][y]==2:
print 'found at %d, %d'%(x,y)
return True
elif grid[x][y]==1:
print 'wall at %d, %d'%(x,y)
return False
elif grid[x][y]==3:
print 'wall at %d, %d'%(x,y)
return False
print 'visiting %d, %d'%(x,y)
# mark as visited
grid[x][y] = 3
# explore neighbors clockwise starting by the one on the right
if ((x<len(grid)-1 and search(x+1,y)) or (y>0 and search(x,y-1)) or (x>0 and search(x-1,y)) or \
(y<len(grid)-1 and search(x,y+1))):
return True
return False
search(0,0)
| true |
5ad8073abbff41b8a0f8611b5eb937dc132bafa5 | cmaliwal/encryption-In-Python | /encrption_using_ord_and_char.py | 249 | 4.28125 | 4 | #encryption using ord() and char()
message = raw_input ("Enter a message to encrypt: ").upper()
encrypted = ""
for letter in message :
if letter == " ":
encrypted += " "
else:
encrypted += chr(ord(letter)+5)
print (encrypted) | true |
30448a7b4f868d52f1cb67b668d55bb1a1cc77f3 | bpandey-CS/Algorithm | /problem-solving7.py | 529 | 4.1875 | 4 | # For a given sentence, return the average word length.
# Note: Remember to remove punctuation first.
def average_word_length(sentence: str):
# remove the punctuation fromt he sentences
unlikable_chars = ['!','.','?', "'", ",", ";", "."]
for uc in unlikable_chars:
sentence.replace(uc,'')
len_of_words = [len(word) for word in sentence.split()]
return sum(len_of_words)/len(len_of_words)
if __name__ == "__main__":
sentence = "This is a test sentence."
print(average_word_length(sentence))
| true |
038fdd194d209b5c867b3388536d9f4db73b34b8 | valmsmith39a/u-data-structures-algorithms | /tries.py | 2,188 | 4.125 | 4 | """
Trie: Type of Tree
Spell check: word is valid or not
One solution is hashmap of all known words
O(1) to see if the word exists,
but O(n * m) space
n: number of words
m: length of the word
Trie: decrease memory usage, improve time performance
"""
basic_trie = {
'a': {
'd': {
'd': {
'word_end': True
},
'word_end': False
},
'word_end': True
}
}
# print(basic_trie)
# print('Is "a" a word: {}'.format(basic_trie['a']['word_end']))
# print('Is "add" a word: {}'.format(basic_trie['a']['d']['d']['word_end']))
def is_word(word):
current_node = basic_trie
for char in word:
if char not in current_node:
return False
current_node = current_node[char]
return current_node['word_end']
# print(is_word('a')) # True
# print(is_word('ad')) # False
# print(is_word('add')) # True
class TrieNode(object):
def __init__(self):
self.is_word = False
self.children = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def add(self, word):
current_node = self.root
for char in word:
if char not in current_node.children:
current_node.children[char] = TrieNode()
current_node = current_node.children[char]
current_node.is_word = True
def exists(self, word):
current_node = self.root
for char in word:
if char not in current_node.children:
return False
current_node = current_node.children[char]
return current_node.is_word
# Test simple case
word_trie = Trie()
word_trie.add('the')
# print(word_trie.exists('the')) # True
# print(word_trie.exists('that')) # False
valid_words = ['apple', 'bear', 'goo', 'good',
'goodbye', 'goods', 'goodwill', 'gooses', 'zebra']
word_trie = Trie()
for valid_word in valid_words:
word_trie.add(valid_word)
test_words = ['bear', 'goo', 'good', 'goos']
for word in test_words:
if word_trie.exists(word):
print('"{} is a word'.format(word))
else:
print('"{}" is not a word'.format(word))
| true |
f6dd1a7f7b90b36406d9d136279d50b3fa93575f | liumengjun/script-exercise | /py/random_red_package.py | 1,136 | 4.125 | 4 | import random
'''
# 微信或支付宝,随机红包(拼手气红包)算法
'''
def random_red_package(total: float, num: int):
if total * 100 < num:
raise Exception("total is too small")
if num == 1:
yield total
else:
# total * 100, unit is fen of RMB。each one has 1 fen at least
rest = total * 100
for i in range(0, num - 1):
t = rest * 2 / (num - i) * random.random()
f = int(t) or 1
yield f / 100
rest -= f
yield rest / 100
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("Please input params: total and count")
exit(-1)
total = float(sys.argv[1])
num = int(sys.argv[2])
if total <= 0 or num <= 0:
print("Please input total (>=0.01) and count (>1)")
exit(-2)
total_fen = int(total * 100)
if total_fen < num:
print("The total at least may be %.2f" % (num / 100,))
exit(-3)
total = total_fen / 100
print("total = %.2f, count = %d" % (total, num))
for f in random_red_package(total, num):
print(f)
| true |
a0fa4727e2731b7374341473531b3ed1f5f8e4d0 | Shaunwei/hysteria_mode | /leetcode/LinkedList/Reverse Linked List II.py | 768 | 4.34375 | 4 | '''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
'''
from utils import *
def reverse_btw(head, m, n):
prev = dummy = Node(-1)
dummy.next = head
for _ in range(m - 1):
prev = prev.next
tail = curt = prev.next
for _ in range(n - m + 1):
tail = tail.next
prev.next = tail
while curt is not tail:
temp = curt.next
curt.next = prev.next
prev.next = curt
curt = temp
return dummy.next
if __name__ == '__main__':
head = build_ll([1, 2, 3, 4, 5])
print_ll(reverse_btw(head, 2, 4)) | true |
ba35d814e24e21dc83c304a35933b79f35f77ff9 | howardc72150/programming_assessment | /04_ask_area_perimeter.py | 1,011 | 4.3125 | 4 | # Component 3
# Asks the user if they want the program to calculate
# the area or perimeter of the shape.
# Initialize variables
accepted_inputs = ['perimeter', 'area']
# Check if user input is a valid method.
def check_input(question):
error = "Please enter either area or perimeter."
valid = False
while not valid:
response = input(question)
has_errors = ""
# Checks if the user input is not an acceptable method from
# the `accepted_inputs` variable.
if response.lower() not in accepted_inputs:
has_errors = "yes"
if has_errors != "":
print(error)
continue
else:
return response
# Prints the list of available methods.
print("Available forms of calculation: Area or Perimeter.")
print("")
# Asks the user for which method they want to use.
calculation_method = check_input("Which calculation method would you like to use? ")
print("You selected {}!".format(calculation_method.lower())) | true |
8bbcda0b8746baa03ea6d967bae2be5b0853fb12 | JessicaDeMota/CSCI-135 | /5 whole integers.py | 593 | 4.21875 | 4 | #Jessica De Mota Munoz
#jessica.demotamunoz86@myhunter.cuny.edu
#October,3rd,2019
#import a turtle to be able to draw and do a graphic
#get user input
#ask user for 5 whole integers
#for each number turn the turtle left and the turtle move toward 100
import turtle
jd = turtle.Turtle()
#we have to create a for loop that allows our turtle to be able to turn left and go forward
#we want this to run 5 times because it is 5 different numbers
#we must turn jdm left because we are taking whatever our input is and making it turn left
for i in range(5) :
jdm = int(input(" Enter 5 whole numbers:"))
jd.left(jdm)
jd.forward(100)
| true |
7f23b5c699cad4f4a7f30661ea327d0201a9dfe6 | damiansp/completePython | /bee/01basics/basics.py | 689 | 4.34375 | 4 | #!/usr/bin/env python3
import cmath # complex math
# Getting Input from User
meaning = input('The meaning of life: ')
print('%s, is it?' %meaning)
x = int(input('x: ')) # 3 only?
y = int(input('y: '))
print('xy = %d' %(x * y))
# cmath and Complex Numbers
print(cmath.sqrt(-1))
print((1 + 3j) * (9 + 4j))
#name = raw_input('What is your name? > ') # 2 only
#print('Why, hello, ' + name, + '!')
# String Representations
print("Hello, world!")
print(repr("Hello, world!"))
#print(str(10000L)) # error in 3
#print(repr(10000L)) # error in 3
temp = 42
print('The temperature is ' + str(temp))
# print('The temperature is ' + `temp`) # 2 only
print('The temperature is ' + repr(temp))
| true |
acd235819785d72bdc6a4e2ea94a0517094b0ddd | WayneZhao1/MyApps | /TicTacToe/tic_tac_toe.py | 2,875 | 4.21875 | 4 | '''
Author: Wayne Zhao
This is a Tic Toc game. Requirements:
. 2 players should be able to play the game (both sitting at the same computer)
. The board should be printed out every time a player makes a move
. You should be able to accept input of the player position and then place a symbol on the board
'''
#initialize the board
board=[' ']*10
board[0]=''
#current player: 0 or 1
player=['', '']
# total steps before game ends
steps = 0
# print board
def display_board(board):
print(board[7]+'|'+board[8]+'|'+board[9])
print('-|-|-')
print(board[4]+'|'+board[5]+'|'+board[6])
print('-|-|-')
print(board[1]+'|'+board[2]+'|'+board[3])
# Check if there is a winner
def winner(board):
if board[7] == board[8] == board[9] != ' ' or board[4] == board[5] == board[6] != ' ' or board[1] == board[2] == board[3] != ' ' or \
board[1] == board[4] == board[7] != ' ' or board[2] == board[5] == board[8] != ' ' or board[3] == board[6] == board[9] != ' ' or \
board[1] == board[5] == board[9] != ' ' or board[7] == board[5] == board[3] != ' ' :
return True
else:
return False
# Check if it is a tie
def is_tie(board):
for char in board:
if char == ' ':
return False
return True
# Start the game
def game_on(board, player, steps):
# the first player picks letter 'X' or 'O'
while True:
mychar = input("Please pick 'X' or 'O' to start: ")
mychar=mychar.upper()
if mychar not in ['X', 'O']:
print("It has to be 'X' or 'O'. Please pick again!")
else:
print(f"Great, you picked {mychar}. Let's start!")
if mychar == 'X':
player=['X','O']
else:
player=['O','X']
break
# Start the game until a player wins
while True:
try:
position=int(input(f"Player {steps%2+1} with '{player[steps%2]}', please choose a position [1-9]: "))
if position < 1 or position > 9:
print("Please choose a number between 1 and 9!")
continue
else:
if board[position] in ['X', 'O']:
print("Spot already taken!")
continue
else:
board[position]=player[steps%2]
display_board(board)
if winner(board):
print(f"Player {steps%2 + 1} with '{player[steps%2]}' wins!!!")
break
elif is_tie(board):
print("Game over. It is a tie!")
break
else:
steps +=1
continue
except:
print("Please choose a number between 1 and 9!")
game_on(board, player, steps) | true |
d840f131cf9d99f52824192c557b9fdf88d9ab68 | RokonUZ/Python_OOPS | /class_and_instance_variable.py | 2,472 | 4.8125 | 5 | # instance variables are different for different objects
# that is they can be assigned different values for different objects
# and if we change one object it is not going to change the other object
# but if we want a variable in such a way that if we change it's value then
# it should be changed for all other variables then these type of variables are called class varibles
# if we have a variable inside the init then it becomes the instance variable
# but if we have variable outside the init but inside the class then it becomes the class variable
class Car:
# here wheels is the class variable and it is same for all the objects that are created based on this class
wheels = 4
def __init__(self):
# these are the instance variables
self.mileage = 10
self.company = "BMW"
car1 = Car()
car2 = Car()
print("mileage of car 1 is ", car1.mileage, " and company is ", car1.company, " and it has ", car1.wheels, " wheels")
print("mileage of car 2 is ", car2.mileage, " and company is ", car2.company, " and it has ", car2.wheels, " wheels")
# we call also call the wheels by using the class itself
print("checking wheels value using the class name", Car.wheels)
print()
# if we want to change class variable of only one object then we can do it in following way
car1.wheels = 10
print("car1 wheels changed to ", car1.wheels)
print("wheels value in Car class", Car.wheels)
# but if we want to change for all the objects then we have to use class name to do it
Car.wheels = 20
# note that even after using the class name the output of car1.wheels is still 10
print()
print("after changing wheels value using the class name")
print("car1 wheel value is not changed", car1.wheels)
print("but car2 wheels changed",car2.wheels)
# but if we create a new object of class car and say it car3 then its wheel value will be changed
car3 = Car()
print("similarily after creating the new object car3 its value too changed",car3.wheels)
Car.company = "check"
print()
print("after changing the instance value using class name")
print("name of company called using the class is changed", Car.company)
print("but the object value is still the same")
print(car1.company)
print(car2.company)
print(car3.company)
# observe here that if we try to change the value of instance variable using the class name
# then it not going to effect the other object value
# even after changing the company to check the value of car1,car2 and car3 is still BMW | true |
c8e2bb2b63a655bba28bf757482ba6a59d610a29 | RokonUZ/Python_OOPS | /basics.py | 1,114 | 4.53125 | 5 | # working on basics of the python OOP's concepts
class Computer:
def __init__(self, cpu, ram):
# this is the constructor in python
# generally we use this for initializing the variables because thats what the
# constructor does
# main advantage or we can say that the behaviour of the constructor is that we need not call the
# constructor or this method explicitly it gets called automatically every time we create a object
# print("This is the constructor")
self.cpu = cpu
self.ram = ram
def configuration(self):
# print("Hello I am a Lenovo idea pad with i5 chipset and 8 Gigs of RAM")
print("Your system configuration is ", self.cpu, " and ", self.ram, " ram ")
computer_1 = Computer('i5', 16)
# below is how you call the method inside a specific class using that class and passing the instance3
# of the class as a parameter
# Computer.configuration(computer_1)
# you can also call the same method in the following way
computer_1.configuration()
computer_2 = Computer('AMD Ryzer 5', 32)
computer_2.configuration()
| true |
ec8a469ced63be5ab90e41aadae2849d5cd04bfd | sjethi/Email-Demo | /EmailDemo.py | 1,866 | 4.15625 | 4 | #! /usr/bin/python
# this is a python email sending demo
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
print("composing!")
print("Welcome to Your name's email system!")
you = input("Please input recipient's address:\n")
# me == my email address
# you == recipient's email address
me = "saarthi.jethi@gmail.com" # change this to your email address
psw = input(print("Please input your password!\n")) # skip this part
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Hello"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version). Change this part
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi! <br>
How are you? I am using a Python Email Sending Module writting to you!<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587) # change the SMTP server for other email servers
mail.ehlo() # Please Google the difference between HELO and EHLO
mail.starttls() # take an existing insecure connection and upgrade it to a secure connection using SSL/TLS
# this will be your email login information
mail.login('sjethi', 'password') # you need to chang here
mail.sendmail(me, you, msg.as_string())
print("Email sent!")
mail.quit()
| true |
7f32e5b9b10dc2808100d1375870e20a731584c4 | yyogeshchaudhary/PYTHON | /4oct/defaultArrgumet.py | 557 | 4.25 | 4 | # /usr/bin/python
'''
Default Arrgument:
def functionName(var1, var2, var3=10)
var3=10 : is called as default arrgument and we can call function with 2 or 3 parameters
if we call the function with 3 parameter then it will override the value of var3 with given value
every default parameter should be trailing param not at middle of function param
'''
def defaultArrgument(strVar, x, y=10):
print("String is : "+strVar)
print("X value is : "+str(x))
print("Y value is : "+str(y))
defaultArrgument('Hello',10)
defaultArrgument('Yogesh', 20,30)
| true |
6470c1ac40bdb0694f525f3796da2cd29e6f0950 | yunusarli/Quiz | /questions.py | 1,717 | 4.21875 | 4 | #import sqlite3 module to keep questions in a database.
import sqlite3
# Questions class
class Questions(object):
def __init__(self,question,answer,options=tuple()):
self.question = question
self.answer = answer
self.options = options
def save_question_and_answer(self):
""" save the question and answer that given by user"""
conn = sqlite3.connect("q_and_a.db")
cur = conn.cursor()
table = """ CREATE TABLE IF NOT EXISTS question (
question text NOT NULL,
answer text NOT NULL
); """
values = """INSERT INTO question VALUES ('{}','{}') """.format(self.question,self.answer)
cur.execute(table)
cur.execute(values)
conn.commit()
conn.close()
def save_options(self):
""" save the options that given by user """
conn = sqlite3.connect("q_and_a.db")
cur = conn.cursor()
table = """ CREATE TABLE IF NOT EXISTS options (
option1 text NOT NULL,
option2 text NOT NULL,
option3 text NOT NULL,
option4 text NOT NULL
); """
values = """ INSERT INTO options VALUES (?,?,?,?) """
cur.execute(table)
cur.execute(values,self.options)
conn.commit()
conn.close()
if __name__ == "__main__":
question = Questions("Who is the creator of python","guido van rosum",("melezeki","guido van rosum","mehmet toner","albert einstein"))
question.save_question_and_answer()
question.save_options() | true |
30ed215f931ffdcde9dc2e8853f15a00a66b6e00 | Wajahat-Ahmed-NED/WajahatAhmed | /harry diction quiz.py | 253 | 4.1875 | 4 | dict1={"set":"It is a collection of well defined objects",
"fetch":"To bring something",
"frail":"weak",
"mutable":"changeable thing"}
ans=input("Enter any word to find its meaning")
print("The meaning of ",ans,"is",dict1[ans]) | true |
fd38fc531606f37eb343d17e9ddf100667ea508c | Reena-Kumari20/Dictionary | /w3schoolaccessing_items.py | 870 | 4.28125 | 4 | #creating a dictionary
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(thisdict["brand"])
print(thisdict.get("brand"))
#dictionary_length
#to determine how many items a dictinary has,use the len()function.
print(len(thisdict))
#dictionary items-data types
thisdict={
"brand":"ford",
"electric":False,
"year":1964,
"colors":["red","while","blue"]
}
print(type(thisdict))
#accessing items
d={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=d["model"]
print(x)
a=d.get("model")
print(a)
print(d["model"])
print(d.get("model"))
#get keys
print(d.keys())
print(d.values())
#add a new items
car={
"brand":"ford",
"model":"mustang",
"year":1964
}
car["color"]="write"
print(car)
#get values
print(car.values())
print(car.items())
if "model" in car:
print("Yes,'model' is one of the keys in the car dictionary")
| true |
3044aa9396d2a3481d652a64f99db78253d88d71 | KrShivanshu/264136_Python_Daily | /Collatz'sHypothesis.py | 420 | 4.125 | 4 | """ Write a program which reads one natural number and executes
the above steps as long as c0 remains different from 1.
We also want you to count the steps needed to achieve the goal.
Your code should output all the intermediate values of c0, too.
"""
c0 = int(input("Enter a number: "))
step = 0
while c0!=1:
if c0%2==1:
c0=3*c0+1
else:
c0=c0/2
print(int(c0))
step=step+1
print(step) | true |
0f46661eb4208c064f2badee1a0322bae583b6fa | johnsogg/play | /py/tree.py | 1,997 | 4.34375 | 4 | class Tree:
"""A basic binary tree"""
def __init__(self):
self.root = None
def insert(self, node):
if (self.root == None):
self.root = node
else:
self.root.insert(node)
def bulk_insert(self, numbers):
for i in numbers:
n = Node(i)
self.insert(n)
def report(self):
if (self.root != None):
self.root.report()
else:
print "No data"
def contains(self, number):
if (self.root != None):
return self.root.contains(number)
else:
return false
class Node:
"""A node in the basic binary tree"""
def __init__ (self, data):
"""Create a node"""
self.data = data
self.left = None
self.right = None
def insert(self, node):
if (self.data > node.data):
if (self.left == None):
self.left = node
else:
self.left.insert(node)
else:
if (self.right == None):
self.right = node
else:
self.right.insert(node)
def report(self):
if (self.left != None):
self.left.report()
print str(self.data)
if (self.right != None):
self.right.report()
def contains(self, number):
if (self.data == number):
return True
else:
if (self.data > number):
if (self.left != None):
return self.left.contains(number)
else:
return False
else:
if (self.right != None):
return self.right.contains(number)
else:
return False
if __name__ == '__main__':
tree = Tree()
tree.bulk_insert([4, 3, 6, 9, 13, 2, 3, 8, 3, 8, 4])
tree.report()
for i in range(1, 15):
print str(i) + ": " + str(tree.contains(i))
| true |
53b033db25faa95074a34e44b1fc095a5abd7824 | ltoshea/py-puzzles | /lowestprod.py | 805 | 4.1875 | 4 | """Create a function that returns the lowest product of 4 consecutive numbers in a given string of numbers
This should only work is the number has 4 digits of more. If not, return "Number is too small".
lowest_product("123456789")--> 24 (1x2x3x4)
lowest_product("35") --> "Number is too small"
lowest_product("1234111")--> 4 (4x1x1x1)"""
def lowest_product(input):
if len(input) < 4:
return 'Number is too small'
else:
smallest = int(input[0])*int(input[1])*int(input[2])*int(input[3])
for i in range(0,len(input)-3):
total = 1
for j in range(i,i+4):
total = total * int(input[j])
if total < smallest:
smallest = total
return smallest
if __name__ == "__main__":
print lowest_product("1234") | true |
625b5c1642c07a17d591b3af07c99cb65ab2070c | DipanshKhandelwal/Unique-Python | /PythonTurtle/turtle_circle/turtle_circle.py | 1,053 | 4.3125 | 4 | import turtle
''' this moves turtle to make a square
even tells us how to configure our turtle like changing its speed ,color
shape etc'''
def turtle_circle():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
''' Inputs be like :
turtle.shape() { gives classic shape }
turtle.shape("turtle") { arrow, turtle, circle,
square, triangle, classic }'''
brad.color("yellow")
'''input formats for turtle.shape:-
fillcolor()
fillcolor(colorstring) { like "red", "yellow", or "#33cc8c" }
fillcolor((r, g, b))'''
brad.speed(1)
'''If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues as follows:
fastest: 0
fast: 10
normal: 6
slow: 3
slowest: 1 '''
brad.circle(120)
window.exitonclick()
turtle_circle()
| true |
ac0b9c7cbd00ba13b6f5409556cafaf60460ba96 | Tabsdrisbidmamul/PythonBasic | /Chapter_9_classes/02 three_restaurant.py | 1,260 | 4.40625 | 4 | class Restaurant:
"""a simple to stimulate a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""will define what the restaurant is"""
print(self.restaurant_name.title() + ' is a 5 star restaurant.')
print(self.restaurant_name.title() + ' is open 6 times a day.\n')
def open_restaurant(self):
"""stimulate that the restaurant is open"""
print(self.restaurant_name.title() + ' is open!')
# create an instance or set of instructions and store into variable restaurant
# create three different instance
restaurant = Restaurant('Le de familie', 'french')
restaurant_1 = Restaurant('taste of hong kong', 'chinese')
restaurant_2 = Restaurant('Days', 'buffet')
print(restaurant.restaurant_name.title() + ' is really good.')
print('They serve ' + restaurant.cuisine_type.title() + '.')
print()
# call the two methods
restaurant.describe_restaurant()
restaurant.open_restaurant()
print()
# call the three instances, call call method describe_restaurant() for each one
restaurant.describe_restaurant()
restaurant_1.describe_restaurant()
restaurant_2.describe_restaurant()
| true |
35d6f1f370cdf61b6bf1f496e08d0ea329d64995 | Tabsdrisbidmamul/PythonBasic | /Chapter_8_functions/15 import_modules.py | 301 | 4.1875 | 4 | import math as maths # import maths module
def area_of_a_circle(radius):
"""finds area of a circle, argument is radius"""
area = round(pi * radius, 2)
return area
pi = maths.pi
# call function, which will give me the area of a circle
circle_0 = area_of_a_circle(50)
print(circle_0)
| true |
c17a03c48b288270bf1bb671f8dca1fa6fbace24 | Tabsdrisbidmamul/PythonBasic | /Chapter_10_files_and_exceptions/01 learning_python.py | 766 | 4.34375 | 4 | # variable to hold file name
file = 'learning_python.txt'
# use open function to open file, and print the contents three times
with open(file) as file_object:
content = file_object.read()
print(content, '\n')
print(content, '\n')
print(content, '\n')
print('indent\n')
# open the file and read through each line and print it
with open(file) as file_object_2:
for line in file_object_2:
print(line, end="")
# open the file, read and store each line into a list, hold this list in lines
# iterate through lines appending it to indent_string to differentiate it
# from the previous work
with open(file) as file_object_3:
lines = file_object_3.readlines()
print()
print()
indent_string = '(indent) '
for line in lines:
print(indent_string + line, end='')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.