blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f221d6ad22ba981add9a739fd9d4bb80ac926e1c | jhgerescher98/PythonSummerClass | /class1/vowel.py | 221 | 4.3125 | 4 | ch = input("Enter a letter: ")
if (ch== 'A' or ch== 'a' or ch== 'E' or ch == 'e' or ch== 'I' or ch== 'i' or ch== 'O' or ch== 'o' or ch== 'U' or ch== 'u'):
print(ch, "is a Vowel")
else:
print(ch, "is not a vowel") | false |
45f4ad29116227cfdd7143ce48fc4cc4a63aa8ec | mjferna/Lab-Notes | /wordcount.py | 1,031 | 4.21875 | 4 | ##An attempt at a word count application via terminal
import os
name = raw_input('Hey there! What\'s your name?\n')
print 'Nice to meet you, {0}.'.format(name)
print 'Welcome to TextsCount!'
print 'This program counts the number of words, lines, and sentences in a given text file.'
lines, blanklines, sentences, words = 0, 0, 0, 0
print '-' * 50
filename = raw_input('Choose a file by typing its path!\n')
try:
textf = open('{0}'.format(filename), 'r')
except IOError:
print 'Cannot open file %s for reading' % filename
import sys
sys.exit(0)
for line in textf:
print line,
lines += 1
if line.startswith('\n'):
blanklines += 1
else:
sentences += line.count('.') + line.count('!') + line.count('?')
tempwords = line.split(None)
print tempwords
words += len(tempwords)
textf.close()
os.system('clear')
print 'Here you are, {0}!'.format(name)
print '-' * 50
print "Lines : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words : ", words
| true |
c7a9d822c2d0e51df6f854d00c9f295648316283 | doratiotto/Hi-Bunny | /Curso em Video/Aula 15_1 - Break.py | 319 | 4.125 | 4 | num1 = 10.5555
num2 = 10.5549
num3 = 10.5555
print(f'O número é: {num1 :20}')
print(f'O número é: {num1 :.2f}')
print(f'O número é: {num1 :^20}')
print(f'O número é: {num1 :&^20}')
print(f'O número é: {num1 :->20}')
print(f'O número é: {num1 :-<20}')
print('O número é: {:.2f}' .format(num1)) | false |
9703369767ae4a28bcc4372957284ba392675fab | brandonriis/Draft-of-a-barge | /Draft_of_a_barge.py | 1,428 | 4.5 | 4 | #201358937 Tonge_Brandon-CA01.py
#October 2018
#This program accepts the users imputs regarding the specification of a barge
#and then uses these inputs to calculate the draft of said barge. This
#calculation is made assuming the barge is constructed using iron. The
#program will then output each of the calculated values for the user.
print("This program will calculate the draft of an iron barge using the \ninputed user values.")
print()
#User inputs
length = float(input("Please enter the length of the barge in metres: "))
height = float(input("Please enter the height of the barge in metres: "))
breadth = float(input("Please enter the breadth of the barge in metres: "))
#Set the value for the weight of iron
weight_of_iron = 1.06
#Calculations for the draft
area_of_barge = (2*height)*(length+breadth)+(length*breadth)
mass_of_barge = area_of_barge*weight_of_iron
draft_of_barge = mass_of_barge/(length*breadth)
#User Outputs
print("")
print("The length is: {0:.2f}" .format(length) + "m")
print("The height is: {0:.2f}" .format(height) + "m")
print("The breadth is: {0:.2f}" .format(breadth) + "m")
print("The draft of the barge is: {0:.3f}" .format(draft_of_barge) + "m")
#Test outputs
#print("The weight of iron is: " + str(weight_of_iron) + "kg per square meter")
#print("The area of the barge is: " + str(area_of_barge) + " meters squared")
#print("The mass of the barge is: " + str(mass_of_barge) + "kg")
| true |
2b17dd4018eff956b587bee57743e3fa2115f0d4 | andersonmoura87/aulas_python | /Testes/extra.py | 848 | 4.15625 | 4 | """
num1 = int(input("Número um: "))
num2 = int(input("Número dois: "))
num3 = int(input("Número três: "))
if num1 > num2 and num3:
print ("Número um é o maior numero!")
elif num2 > num1 and num3:
print ("Número dois é o maior numero")
elif num3 > num1 and num2:
print ("Número três é o maior numero")
maior = 5
menor = 10
print ('Maior: %d ' %maior)
print ('Menor: %d ' %menor)
"""
from tkinter import *
root = Tk()
root.geometry("500x400")
a = Label(root, text ="Digite o seu email")
b = Button(root, text="ENTRAR")
e = Entry(root)
a.pack()
b.pack()
e.pack()
root.mainloop()
# Python tkinter hello world program
from tkinter import *
root = Tk()
root.geometry("500x400")
a = Label(root, text ="Digite o seu email")
b = Button(root, text="ENTRAR")
e = Entry(root)
a.pack()
e.pack()
b.pack()
root.mainloop()
| false |
d5a29c1b0b14c9ed8cd3d52286ef2842054b0c27 | n-pochet/python-training-exercises | /tests/caesar_cipher/example.py | 814 | 4.40625 | 4 | def encrypt(message):
"""Encrypt the given message
Arguments:
message {str} -- Message to encrypt
Returns:
str -- The encrypted string
"""
if message:
enc_message = list(map(encrypt_letter, message))
enc_message = "".join(enc_message)
return enc_message
else:
return ""
def encrypt_letter(letter):
"""Encrypt a single letter
Arguments:
letter {char} -- The character to encrypt
Returns:
char -- The encrypted character
"""
inc_ord_char = ord(letter) + 3
if letter.isupper():
if inc_ord_char > 90:
inc_ord_char = inc_ord_char % 90 + 64
else:
if inc_ord_char > 122:
inc_ord_char = inc_ord_char % 122 + 96
return chr(inc_ord_char)
| true |
db5ea1abcdb78ab856c855935e1856f7659f20b7 | n-pochet/python-training-exercises | /classes/line/example.py | 729 | 4.25 | 4 | from math import pow, sqrt
class Point():
"""Point class
"""
def __init__(self, x, y):
self.x = x
self.y = y
class Line():
"""Line class
Raises:
TypeError -- Raises if p1 or p2 is not an instance of Point
"""
def __init__(self, p1, p2):
if not isinstance(p1, Point) or not isinstance(p2, Point):
raise TypeError
self.p1 = p1
self.p2 = p2
def length(self):
"""Length of the line
Returns:
float -- Length of the line
"""
x1 = self.p1.x
x2 = self.p2.x
y1 = self.p1.y
y2 = self.p2.y
l = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
return l | true |
b557358fa21ab920c49f91ebec570c10aa4643e4 | X3llus/CompSci12 | /bug/debug.py | 973 | 4.125 | 4 | # Cass Smith
# 11 February 2019
# Loop.py: loops and control structures demo
from random import randint
def getInput():
while True:
try:
x = integer(input("Enter a guess:\n>> "))
if x < 1 and x > 10:
raise Exception("Invalid input")
else:
break
except:
print("Your guess should be a number between 1 and 10.")
return x
def ternary(number):
if(num == 1):
return "try"
else:
return "tries"
def main():
print("Guess the number!")
myNumber = randint(0, 11)
print("Ok, I've picked a number between 1 and 10.")
print("Let's see how many tries you'll need to guess it!")
guesses = 0
while True:
guesses += 1
guess = int(input("Guess the number"))
if guess == myNumber:
break
else:
print("Nope, guess again!")
print("You got it in {} guesses!".format(guesses))
main()
| true |
6f9b2e8ba337763321b79be93c45244d3eaf3070 | aouellette77/Learning-Python | /PracticePython/Exercise5.py | 971 | 4.15625 | 4 | # Take two lists, say for example these two:
#
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that contains only the elements that are common between the
# lists (without duplicates). Make sure your program works on two lists of different sizes.
#
# Extras:
#
# Randomly generate two lists to test this
# Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
# Adam Ouellette
# Exercise 4 http://www.practicepython.org
# June 13 2019
List1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
List2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
DupList = []
# Single line not working. Need to check more into this.
# print([number for number in List1 if List2])
for number in List1:
if number in List2:
# print("yes", number)
DupList.append(number)
# else:
# print("no", number)
print(DupList)
| true |
4670f6265068fe20fee2fecfc1c4e162944d2ae4 | Bhavya-Agrawal/Py_Projects | /numpy_ass.py | 2,371 | 4.28125 | 4 | #!/usr/bin/python3
##run this file as python3 file_name
import numpy as np
global count
count = 0 #for counting no of inputs
valid_input = 1 #for getting inputs until q is reached
print("enter the values and press q: to stop as any further input")
even=0
user_input = input()
list_elements=[] #to check count of no of elements entered
list_factors=[] #to keep count of no of factors
list_elements.append(user_input)
## to compare strings in python function used is str1.equals(str2) ##
while valid_input != 0:
if user_input != "q":
user_input = input()
if user_input != "q":
list_elements.append(user_input)
count+=1
else:
break
print("list formed==>"+str(list_elements))
print("count==>"+str(count))
def count_factors(count1):
count_no = count1
global count ##for declaring global variables##
global even
for i in range(2,count_no//2+1):
if count%i==0:
print ("matrix can be formed from them")
l1=count//i
if i in list_factors and l1 in list_factors:
print("nothing to be added else in factors list")
else:
list_factors.append(i)
list_factors.append(l1)
list_factors.append(l1)
list_factors.append(i)
even = 1
elif(i==count_no//2 and even!=1):
print("enter one more number")
user_input = input()
list_elements.append(user_input)
count+=1
list_factors.append(2)
list_factors.append(count//2)
list_factors.append(count//2)
list_factors.append(2)
counter = count_factors(count)
counter
else:
continue
counter = count_factors(count)
counter
print("list_factors==>"+str(list_factors))
print(" you have entered "+str(count)+" elements ")
print ("enter the prefered size of the matrix you want from the input")
row = int(input())
column = int(input())
length = len(list_factors)
if row in list_factors:
row1 = row
column1 = count//row1
np1=np.array(list_elements)
print(np1.reshape(row1,column1))
else:
if (row*column == count and (row!=1 or column!=1) and (row!=0 or column!=0)):
print ("matrix can be formed with this size")
np1=np.array(list_elements)
print(np1.reshape(row1,column1))
else:
print("sorry not a valid size for forming the matrix with the given input of size count")
np1=np.array(list_elements)
print(np1.reshape(row1,column1))
## to search item at a specific location in list use method listname.index(element)
| true |
a93acff0f927a281308d2422c207eab1aeb0244d | ekkys/day-1-3-exercise-restart | /main.py | 209 | 4.25 | 4 | #Write your code below this line 👇
# For input name
name = input("Whats your name?\n")
# Print how long the character with len()
print(len(name))
# One line program
print(len(input("What's your name?")))
| true |
314ed1a4fb3ddf52ebcfb092a10552befb2785f7 | elmanko/python101 | /examples/leap.py | 493 | 4.25 | 4 | # fist value is a placeholder, number of days per month
month_days = [0, 31, 28, 31 ,30, 31, 30 ,31, 31, 30, 31, 30, 31]
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
if not 1 <= month <= 12:
return 'Invalid month'
if month == 2 and is_leap(year):
return 29
return month_days[month]
# print(is_leap(2020)) # True
# print(is_leap(2017)) # False
print(days_in_month(2018, 2)) # 28 | true |
3a4539df2818b9a3dad27c430001be4ded2dc4df | narayanants/complete-python-bootcamp | /5 Object Oriented Programming/homework.py | 1,707 | 4.15625 | 4 | # Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
class Line(object):
def __init__(self, c1, c2):
self.c1 = c1
self.c2 = c2
def distance(self):
x1, y1 = self.c1
x2, y2 = self.c2
return ((x2-x1)**2 + (y2-y1)**2)**0.5
def slope(self):
x1, y1 = self.c1
x2, y2 = self.c2
return (y2-y1)/(x2-x1)
coordinate1 = (3, 2)
coordinate2 = (8, 10)
li = Line(coordinate1, coordinate2)
print(li.distance())
print(li.slope())
# Problem 2: Fill in the class
class Cylinder:
pi = 3.14
def __init__(self, height=1, radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.height * self.pi * (self.radius) ** 2
def surface_area(self):
top = self.pi * (self.radius) ** 2
return (2*top) + (2*3.14*self.radius*self.height)
c = Cylinder(2, 3)
print(c.volume())
print(c.surface_area())
# Challenge Problem:
class Account():
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, dept_amt):
self.balance += dept_amt
print('Added {} to the balance'.format(dept_amt))
def withdrawl(self, wd_amt):
if self.balance >= wd_amt:
self.balance -= wd_amt
print('Withdrawl accepted')
else:
print('Sorry not enough funds!!')
def __str__(self):
return "Owner is {} \n Balance is {}".format(self.owner, self.balance)
a = Account('Sam', 500)
print(a.owner)
print(a.balance)
print(a.deposit(100))
print(a.withdrawl(600))
print(a.withdrawl(100))
| true |
7882414085cfc4a1680a23e18b61e550df0494d4 | MelissaYates/web-caesar | /caesar.py | 782 | 4.15625 | 4 | from helpers import alphabet_position, rotate_character
def rotate_string(rot, text):
new_natos = ""
natos = "abcdefghijklmnopqrstuvwxyz"
upper_natos = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for nato in text:
if (nato in upper_natos) or (nato in natos):
new_nato = rotate_character(nato, rot)
new_natos = new_natos + new_nato
else:
new_natos = new_natos + nato
return new_natos
def main():
#from sys import argv
#print("argv: ",argv)
string = input("Type a message: \n")
# print()
# print(string)
rotate = int(input("Rotate by: \n"))
# print(rotate)
#print(encrypt(string, int(argv[1])))
print(rotate_string( rotate,string))
if __name__ == "__main__":
main() | false |
a8c185d5ccf54b785aa9b5492e186d91661e9576 | TemistoclesZwang/Algoritmo_IFPI_2020 | /exerciciosComCondicionais/A_CONDICIONAIS/02A_EX20.py | 612 | 4.1875 | 4 | #20. Leia a medida de um ângulo (entre 0 e 360°) e escreva o quadrante (primeiro, segundo, terceiro ou
#quarto) em que o ângulo se localiza.
def main():
angulo = int(input("Angulo: "))
quadrante (angulo)
def quadrante (angulo):
if angulo >= 0 and angulo < 90:
print('1º quadrante')
elif angulo >= 90 and angulo < 180:
print('2º quadrante')
elif angulo >= 180 and angulo < 270:
print('3º quadrante')
elif angulo >= 270 and angulo < 360:
print('4º qudrante')
else:
print('Erro. Insira um ângulo entre 0 e 360')
main()
| false |
2706007dea4aa46bf09ae80b7a33fc232995302a | JamesonDavis/CS0008-f2016 | /Chapter 3/Ch3Ex1.py | 365 | 4.125 | 4 | day = input('Input a number 1-7')
day = int(day)
if day == 1:
print ('Monday')
elif day == 2:
print ('Tuesday')
elif day == 3:
print ('Wednesday')
elif day == 4:
print ('Thursday')
elif day == 5:
print ('Friday')
elif day == 6:
print ('Saturday')
elif day == 7:
print ('Sunday')
else:
print ('Please choose a number between 1 and 7') | true |
6acd8018441c4927d42a334435221b1d25d1adf8 | JamesonDavis/CS0008-f2016 | /f2016_cs8_JPD59_a1/f2016_cs8_JPD59_a1.py | 2,181 | 4.5625 | 5 | #First ask user to input unit system preference
#Input 'USC' or 'metric'
unit = input('Choose either USC or metric:')
#Ask for distance driven and how much gas was used. Use if-elif statement to properly follow user's unit system choice
#Define variables based on unit system used
#else statement placed at the end in case user inputs something other than USC or metric
if unit == 'USC':
USC_distance = int(input('Enter number of miles travelled:'))
USC_gas = int(input('Enter number of gallons of gas used:'))
elif unit == 'metric':
metric_distance = int(input('Enter number of km travelled:'))
metric_gas = int(input('Enter number of liters of gas used:'))
else:
print('Error')
#Next if-elif statments used to convert unit system based on initial unit system choice
if unit == 'USC':
metric_distance = USC_distance * 0.621371
metric_gas = USC_gas * 0.264172
elif unit == 'metric':
USC_distance = metric_distance * 1.60934
USC_gas = metric_gas * 3.78541
else:
print('Error')
#Now that four variables are defined at this point, we can calculate the gas consumption
USC_consumption = USC_distance // USC_gas
metric_consumption = (100 * metric_gas) // metric_distance
#Gas consumption rating can now be defined by using if-elif statements
if metric_consumption > 20:
Gas_rating = 'Extremely poor'
elif metric_consumption <= 20 and metric_consumption > 15:
Gas_rating = 'Poor'
elif metric_consumption <= 15 and metric_consumption > 10:
Gas_rating = 'Average'
elif metric_consumption <= 10 and metric_consumption > 8:
Gas_rating = 'Good'
elif metric_consumption <= 8:
Gas_rating = 'Excellent'
else:
print('Error')
#With all variables defined, we can now print out a results table
#table is formatted to have each value be rounded to three digits
print('USC', 'metric',)
print('Distance_____:', format(USC_distance, '.3f'), 'miles', format(metric_distance, '.3f'), 'km')
print('Gas__________:', format(USC_gas, '.3f'), 'gallons', format(metric_gas, '.3f'), 'liters')
print('Consumption__:', format(USC_consumption, '.3f'), 'mpg', format(metric_consumption, '.3f'), '1/100 km')
print('Gas Consumption Rating:', Gas_rating) | true |
13424cb336d1569a795ebcaf8294487bafab3a86 | Sallison24/Personal-Projects | /Programming/Python/Strings and Conditionals.py | 893 | 4.40625 | 4 | """
1.
Write a function called contains that takes two arguments, big_string and little_string and returns True if big_string contains little_string.
For example contains("watermelon", "melon") should return True and contains("watermelon", "berry") should return False.
2.
Write a function called common_letters that takes two arguments, string_one and string_two and then returns a list with all of the letters they have in common.
The letters in the returned list should be unique. For example,
common_letters("banana", "cream")
should return ['a'].
below are the answeres.
"""
def contains(big_string, little_string):
return little_string in big_string
def common_letters(string_one, string_two):
common = []
for letter in string_one:
if (letter in string_two) and not (letter in common):
common.append(letter)
return common
| true |
4a59baae50b86797be6f2a98c30cbe2ee3ea58ce | dvncan/python_fun | /Basics/stringtype.py | 592 | 4.15625 | 4 | s=" you are awesome! "
print(s)
s1 = """you are
the creator
of your destiny"""
print(s1)
#indexing
print(s[2])
#repition
print(s*3)
print(len(s1))
print(len(s))
#slicing
print(s[0:5])
print(s[0:])
print(s[:8])
#-1 is the last element
print(s[-3:-1])
#step of 2 now.
print(s[0:9:2])
#-1 is the reverse order when stepping through
print(s[15::-1])
print(s[::-1])
print(s.strip())
print(s.lstrip())
print(s.rstrip())
print(s.find("awe",0,8))
print(s.find("awe",0,len(s)))
print(s.count("a"))
print(s.replace("awesome", "super"))
print(s.upper())
print(s.lower())
print(s.title())
| true |
85353fd1e62d0247bbb96d34339ebad0a3507bd0 | Princecodes4115/myalgorithms | /hackerrank/arraysum.py | 765 | 4.34375 | 4 | # Given an array of integers, can you find the sum of its elements?
# Input Format
# The first line contains an integer, , denoting the size of the array.
# The second line contains space-separated integers representing the array's elements.
# Output Format
# Print the sum of the array's elements as a single integer.
# Sample Input
# 6
# 1 2 3 4 10 11
# Sample Output
# 31
# Explanation
# We print the sum of the array's elements, which is: .
#!/bin/python3
import sys
def simpleArraySum(n, ar):
# Complete this function
thesum = 0
for i in ar:
thesum += i
return thesum
# n = int(input().strip())
# ar = list(map(int, input().strip().split(' ')))
n = 6
ar = [1, 2, 3, 4, 10, 11]
result = simpleArraySum(n, ar)
print(result) | true |
1cda947ebf281b62305687e2424219685e45f3dc | kusejiubei/Python_study | /01_Python基础/类与对象/hm_59_eval.py | 310 | 4.15625 | 4 | # eval函数:将字符串 当成一个 有效表达式来求值 并返回计算结果
print(eval("1+2")) # 解析为相加
print(eval("1==1")) # 判断
print(eval("'*'*10")) # 复制
print(eval("{1,2,3,4,}")) # {}
print(eval("(1,2,)")) # ()
instr= input("请输入一个算术题:")
print(eval(instr)) | false |
74b8c46672d8d9b5f6815cdf06c79c7a5cdfbc43 | NLucuab/pre-ada-exercises | /Ada Build/Rock_Paper_Scissors_Game.py | 984 | 4.1875 | 4 | print("Enter a choice for Player 1!")
print("rock, paper, or scissors!")
Player1 = input()
print("Enter a choice for Player 2!")
print("rock, paper, or scissors!")
Player2 = input()
print("Let's see who wins~~")
if Player1 == Player2:
print("It's a tie!")
elif Player1 == "rock":
if Player2 == "paper":
print("Player 2 wins!")
elif Player2 == "scissors":
print("Player 1 wins!")
else:
print("You can only pick rock, paper, or scissors! Try again!")
elif Player1 == "paper":
if Player2 == "scissors":
print("Player 2 wins!")
elif Player2 == "rock":
print("Player 1 wins!")
else:
print("You can only pick rock, paper, or scissors! Try again!")
elif Player1 == "scissors":
if Player2 == "rock":
print("Player 2 wins!")
elif Player2 == "paper":
print("Player 1 wins!")
else:
print("You can only pick rock, paper, or scissors! Try again!")
else:
print("You can only pick rock, paper, or scissors! Try again!") | true |
1513ba808d4b029d331995ef638983f9037ff380 | ludoro/King_card_game | /StartingInformation.py | 2,394 | 4.125 | 4 | def starting_info():
print('-'*10 + "KING" + "-"*10)
print("Welcome! We are going to play King.")
print("Do you know how to play? Y or N?")
user_input = input(">")
if user_input == "Y":
print("Nice, you already know the rules.")
elif user_input == "N":
print("Alright, here is a short summary of the rules.")
print("The game is played by four people. Your goal changes depending on"
+ "the hand you are currently playing.")
print("There is a total of 12 hands to play:")
print("1) No King No Jack -2pt each")
print("2) No Queen -3pt each")
print("3) No 8 of Diamonds -8pt")
print("4) No King of Hearts -8pt")
print("5) No Hearts -1pt each, but if you take all 13 Hearts, you go +13pt")
print("6) No last two -4pt each")
print("7) No taking -1pt each")
print("8) Briscola #1 +1pt each")
print("9) Briscola #2 +1pt each")
print("10) Briscola #3 +1pt each")
print("11) Briscola #4 +1pt each")
print("12) Final Briscola +2pt each")
print("Remark: The hand Domino has been skipped, because in the future"+
" an AI will be implemented. The training in the Domino hand is"+
" hard to be implemented in parallel with the other hands.")
print("OK. We know the different hands, but how is the game actually implemented?")
print("One player start by selecting a card to play. Then, every player" +
" must answer with the same suit as the first card played. The h"+
"ighest card wins and the player takes all card in the pit.")
print("What if a player cannot respond with the suit being played?")
print("Well, this is actually great news! If that is the case, the player" +
"can play whatever he wants, and he is never going to take the pit")
print("There is one more thing you need to know. In the briscola hands,"+
"you need to take as many pits as you can. The briscola suit beats"+
"every other suit")
print("Great, you are all ready to play! For more info, consult the Wikipedia page of King.")
print('-'*10 + "The game is now starting." + "-"*10)
else:
print("Ops, you need to answer either with Y or N.")
print("By default, you are going to be Player_1")
| true |
ce849d264a36a39de92a82c9b7ee9da2ca8e7329 | ZayaanHaider/Roulette | /Roulette.py | 1,924 | 4.25 | 4 | import random
# Game Intro
print("Welcome to Roulette")
print("Roulette starts with players making bets.")
print("The croupier (or dealer) throws a ball into the spinning roulette wheel. Players can still makes bets within the process.")
print("While the ball is rolling at the roulette wheel, the croupier/dealer announces: \"No more bets.\" At that point players are NOT allowed making bets The ball lands on a number IN the roulette wheel. If there are winners who bet the number, section OR color, they will be rewarded according of their betting odds.")
# Main Game Loop
keep_running = "yes"
while keep_running == "yes":
# Ball Lands On...
'''
x = random.randint(0, 1)
if x == 0:
ball = "red"
elif x == 1:
ball = "black"
'''
# Zayaan, we will probably need to make a list
# which will
x = random.randint(0, 37)
pocket = [
"0",
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36"
]
# TODO: Match Numbers & Colors in List Below
color = [
"green",
"green",
]
# Player Bets On...
player_selection = input("Red or black?: ")
# Display Outcome
if ball == player_selection:
print("You win!!!!!")
else:
print("YOU LOSE")
# Keep Playing?
keep_running = input("Would you like to continue? Enter 'yes' for yes, 'no' for no: ")
# Say Goodbye
if keep_running != "yes":
print("Thanks for playing. Goodbye!")
| true |
d769a1ad8ca4fe8aa90ff0a57ad63cdb0a40741c | sachag678/100DaysofCode | /algorithms/number_swapper.py | 736 | 4.25 | 4 | # Write a function to swap a number in place (that is without temporary variables.)
# hint 1: Try picturing the two numbers, a and b on a number line.
# hint 2: Let diff be the difference between a and b. Can you use the diff in some way? Then can you get rid of this
# temporary variable
# hint 3: You could also try using XOR
def swap_pythonic(a, b):
a, b = b, a
return a, b
def swap_with_temp(a, b):
"""With temp variable"""
temp = a
a = b
b = temp
return a, b
def swap(a, b):
"""Replace temp variable with a function."""
b = b - diff(a, b)
a = a + diff(a, b)
return a, b
def diff(a, b):
return b - a
print(swap(4, 5))
# XOR
# IN, IN, OUT
# 0, 0, 0
# 0, 1, 1
# 1, 0, 1
# 1, 1, 0
| true |
bb143d8b44eec8318bcaf0b585cbcc6568e111ea | Mahajan09/Hacktoberfest-Python | /armstrong_number.py | 371 | 4.1875 | 4 | import math
def isArmstrong(num):
no_of_digits = math.floor(math.log10(num)) + 1
safe = num
res = 0
while(num != 0):
res += pow((num % 10), no_of_digits)
num //= 10
return res == safe
try:
num = int(input("Enter a number:"))
print(isArmstrong(num))
except ValueError:
print("Please enter a non-negative number!")
| false |
f5337debdcbaaea09988bc34146be8c76434d15a | Esquire-gh/MontyHallSimulation | /montygame.py | 2,859 | 4.125 | 4 | import random
class MontyHallGame:
'''
This is code that simulates the monty hall problem
Author: Esquire_gh
'''
def __init__(self):
self.option = [1,2,3]
self.prize = ['goat', 'goat', 'car']
self.host_options = []
print("Starting New Game: ")
#method that shuffles the doors and the prizes behind them
def get_choices(self):
for i in range(len(self.option)):
random.shuffle(self.option)
random.shuffle(self.prize)
choices = {}
for index in range(len(self.option)):
choices[str(self.option[index])] = self.prize[index]
return choices
#Checking the door which has the main prize(car)
def check_car_prize(self, choices):
for key,value in choices.items():
if choices[str(key)] == 'car':
prize = key
else:
pass
return int(prize)
# Ask the User for an Input
def take_input(self):
user_input = int(input('Please Choose Btwn Doors 1, 2, and 3: '))
if user_input < 0 or user_input > 3:
print('Wrong Input')
user_input = int(input('Please Choose Btwn Doors 1, 2, and 3: '))
else:
user_input = user_input
return user_input
# Function that simulate the game host choosing a fake door
def hosts_dummy_choice(self, user_input, car_index, choices):
for key,value in choices.items():
if int(key) == user_input or int(key) == car_index:
pass
else:
self.host_options.append(int(key))
for i in range(len(self.host_options)):
if self.host_options[i] == car_index:
pass
else:
return self.host_options[i]
# Get the final anser from the user
def get_confirmation(self, user_input):
confirm = str(input("Will you like to change your choice: (y/n)"))
if confirm == 'n':
final_user_input = user_input
elif confirm == 'y':
final_user_input = int(input("What input will you choose now: "))
else:
print("Wrong input, Play Again!")
return final_user_input
#Check win/Lose method
def check_results(self, confirmation, car_index):
# Checking for winner or Loser
if confirmation == car_index:
print("YOU WON!!!!!")
else:
print("YOU LOSE!!!!")
def main():
#instance of newGame
newGame = MontyHallGame()
#generating choices for user
choices = newGame.get_choices()
#print("you have the following choices: ")
#print(choices)
#tracking index of main prize(car)
car_index = newGame.check_car_prize(choices)
#print("the car is in door: ", car_index)
#getting uer input
user_input = newGame.take_input()
print("You have chosen door: ", user_input)
#host opens a dummy door
host_option = newGame.hosts_dummy_choice(user_input, car_index, choices)
print("The host opens door: ",host_option)
#Host aks for user final confirmation
confirmation = newGame.get_confirmation(user_input)
print('Your final choise is: ', confirmation)
newGame.check_results(confirmation, car_index)
if __name__ == '__main__':
main() | true |
1bc3a658f23ba61759b807d45398705391a451d9 | jbacos7/C- | /secondDojo answers1/Python/Python Week 1/mathdojoAM.py | 870 | 4.125 | 4 | # HINT: To do this exercise, you will probably have to use 'return self'. If the method returns itself (an instance of itself), we can chain methods.
# Create a Python class called MathDojo that has the methods add and subtract. Have these 2 functions take at least 1 parameter.
# # Then create a new instance called md. It should be able to do the following task:
# x = md.add(2).add(2,5,1).subtract(3,2).result
# print(x) # should print 5
# Cant have methods and attributes with the same name!!!
class MathDojo:
def __init__(self):
self.result = 0
def plus (self, *nums):
for num in nums:
self.result= num + self.result
return self
def minus (self, *nums):
for num in nums:
self.result= self.result - num
return self
md = MathDojo()
md.plus(2). plus(2,5,1).minus(3,2)
print(md.result) | true |
a60b27884d13fe9daebfec9d2795c05de65bb4b3 | Mike46604/RPS | /RPS.py | 2,546 | 4.28125 | 4 | import random
yourscore = 0
computerscore = 0
#Gives a value of zero to yourscore and computerscore
def game():
global yourscore
global computerscore
#Brings the values yourscore and computerscore into the function.
player = input("Enter your choice (rock/paper/scissors):")
#Allows the player to put input and informs them of their choices.
while (player != "rock" and player != "paper" and player != "scissors"):
print(player)
player = input("Invalid Input. Enter your choice (rock/paper/scissors): ")
#If input not rock, paper, or scissors, tells you the value is invalid until you put in a valid value
computer = random.randint(0, 2)
if (computer == 0):
computer = "rock"
elif (computer == 1):
computer = "paper"
elif (computer == 2):
computer = "scissors"
#Assigns a number to a position and randomly picks from those numbers.
if (player == computer):
print("Draw!")
print("Your Score:", yourscore, "Computer Score:", computerscore)
elif (player == "rock"):
if (computer == "paper"):
print("Computer wins!")
computerscore = computerscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
else:
print("You win!")
yourscore = yourscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
elif (player == "paper"):
if (computer == "rock"):
print("You win!")
yourscore = yourscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
else:
print("Computer wins!")
computerscore = computerscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
elif (player == "scissors"):
if (computer == "rock"):
print("Computer wins!")
computerscore = computerscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
else:
print("You win!")
yourscore = yourscore + 1
print("Your Score:", yourscore, "Computer Score:", computerscore)
print("Your choice: " + player + "\nComputer choice: " + computer + "\nThank you for playing!")
input("Press Enter to play again")
#Prints your choice, the computer's choice, states Thank you for playing, and gives you the option to play again.
while True:
game()
#loops the function so that it can be played again
| true |
961846d35c605c77d6c122cb4a2d8845d8555fa9 | flaith-nycd/python-samples | /conteneur_00.py | 1,422 | 4.1875 | 4 | class Personne:
"""Classe représentant une personne"""
def __init__(self, nom, prenom):
"""Constructeur de notre classe"""
self.nom = nom
self.prenom = prenom
self.age = 33
def __repr__(self):
"""Quand on entre notre objet dans l'interpréteur"""
return "Personne: nom({}), prénom({}), âge({})".format(
self.nom, self.prenom, self.age)
def __str__(self):
"""Méthode permettant d'afficher plus joliment notre objet"""
return "{} {}, âgé de {} ans".format(
self.prenom, self.nom, self.age)
def __getattr__(self, nom):
"""Si Python ne trouve pas l'attribut nommé nom, il appelle
cette méthode. On affiche une alerte"""
print("Alerte ! Il n'y a pas d'attribut {} ici !".format(nom))
def __setattr__(self, nom_attr, val_attr):
"""Méthode appelée quand on fait objet.nom_attr = val_attr.
On se charge d'enregistrer l'objet"""
object.__setattr__(self, nom_attr, val_attr)
"""
>>> from conteneur_00 import Personne
>>> p = Personne('Doe','John')
>>> p
Personne: nom(Doe), prénom(John), âge(33)
>>> print(p)
John Doe, âgé de 33 ans
>>> p.age
33
>>> p.ville
Alerte ! Il n'y a pas d'attribut ville ici !
ma_liste = [1, 2, 3, 4, 5]
8 in ma_liste # Revient au même que ...
ma_liste.__contains__(8)
""" | false |
c1429f921b7486337918a2ec12d73fdd3e7f0df9 | flaith-nycd/python-samples | /yield_explanation.py | 1,954 | 4.21875 | 4 | """
http://khmel.org/?p=1151
https://www.quora.com/What-does-the-%E2%80%9Cyield%E2%80%9D-keyword-do-in-Python
https://docs.python.org/3.6/library/itertools.html
"""
"""
Short explanation: Yield can pause a function and return current result.
So yield works almost as return in the function. How to get value and resume function? First way to get current value
and resume function by for loop:
"""
print('--- Example #1')
def characters():
yield 'a' # pause the function and return result
yield 'b' # pause the function and return result
yield 'c' # pause the function and return result
yield 'd' # pause the function and return result
yield 'e' # pause the function and return result
for item in characters(): # get current value and resume function
print(item)
"""
Second example how to continue paused function by next() method. next() method returns value as well:
"""
print('--- Example #2')
def characters():
abc = ['a', 'b', 'c', 'd', 'e']
for x in abc:
yield x # pause the function and return result
generator = characters() # assign generator
print(next(generator)) # get current value and resume function
print(next(generator)) # get current value and resume function
print(next(generator)) # get current value and resume function
"""
Each next(generator) returns value and resume function until next yield.
Can you do the same without yield?
Yes
Why I need yield?
* Another way to write simple and efficient code (no extra objects).
* Getting data from infinite loops.
Understanding of Iterators (https://wiki.python.org/moin/Iterator) and
Generators (https://wiki.python.org/moin/Generators) is needed to understand how yield working.
"""
print('--- Example #3')
def f(val):
return "Hi"
x = [1, 2, 3]
yield_list = list(f((yield a)) for a in x)
print(yield_list) # [1, 'Hi', 2, 'Hi', 3, 'Hi']
| true |
6c12c1fc13ef8e78407fe24470bde3a2461a958f | badilet/Task24 | /Task24.py | 343 | 4.3125 | 4 | # Напишите функцию которая будет определять полигдром ли введенная строка. Если да 2
# то печатать “True”, если нет “False”.
str = input("Enter a word:")
if str == str[::-1]:
print("It is polindrom!")
else:
print("It is not polindrom! :(")
| false |
fb1f5711fb9b15bc442fede8a02dbe79d242084d | kjng/python-playground | /python-crash-course/Chapters1_10/chapter_8.py | 2,017 | 4.4375 | 4 | def display_message():
print('I am learning about defining functions in Python!')
display_message()
def favorite_book(title):
print('One of my favorite books is ' + title.title() + '.')
favorite_book('the hobbit')
def make_shirt(size='large', message='I love Python'):
print('You ordered a t-shirt size of ' + size + ' with a message of ' + message + '!')
make_shirt('small', 'Hello World')
make_shirt(message='Hello World', size='small')
make_shirt()
make_shirt('medium')
make_shirt(message='Hey there')
def city_country(city, country):
return city.title() + ', ' + country.title()
print(city_country('santiago', 'chile'))
print(city_country('new jersey', 'united states'))
print(city_country('london', 'england'))
magicians = ['houdini', 'idk', 'bob']
def show_magicians(magicians):
for magician in magicians:
print(magician.title())
show_magicians(magicians)
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = 'Great ' + magicians[i]
return magicians
great_magicians = make_great(magicians[:])
show_magicians(magicians)
show_magicians(great_magicians)
def order_sandwich(*ingredients):
order = "Making a sandwich with the following toppings: " + ", ".join(ingredients)
return order
print(order_sandwich('ham'))
print(order_sandwich('ham', 'turkey', 'bacon', 'lettuce'))
print(order_sandwich('peanut butter', 'jelly'))
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
print(build_profile('Kevin', 'Jang', age=23, hometown='Edison', hobby='piano'))
def make_car(manufacturer, model, **optional_features):
car = {
'manufacturer': manufacturer,
'model': model
}
for key, value in optional_features.items():
car[key] = value
return car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
| false |
9938275ebbf06e6978d4a84ac51222bfab0b04a1 | MmtrPentest/PythonCourses | /12. Classes/class_dog_05_setget.py | 1,260 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Инкапсуляция
'''
class Dog: # класс
def __init__(self, name, head, body, legs, tail): # конструктор класса
self.name = name
self.legs = legs
self.head = head
self.body = body
self.tail = tail
if self.tail:
self.tail_str = 'с хвостом'
else:
self.tail_str = 'без хвоста'
print('На свет появился {} c {} ногами и {}'.format(self.name, self.legs, self.tail_str))
def set_legs(self, legs):
if 0<=legs<=4:
self.legs = legs
else:
print('Ног должно быть от 0 до 4')
def get_legs(self):
return self.legs
def set_tail(self, tail):
self.tail = tail
if self.tail:
self.tail_str = 'с хвостом'
else:
self.tail_str = 'без хвоста'
dog1 = Dog('Шарик', 1, 1, 4, True)
dog2 = Dog('Барбос', 1, 1, 3, False)
dog2.set_legs(4)
dog2.set_tail(True)
print('Собаку по кличке {} прооперировали и теперь он c {} ногами и {}'.format(dog2.name, dog2.legs, dog2.tail_str))
| false |
e983c211719f99741d3604e6c0247d3205587b1c | marvinesu/python-course | /data-type.py | 2,432 | 4.40625 | 4 | #Variable
counter = 100
miles = 1000.0
name = "John"
print (counter)
print (miles)
print (name)
#Multiples assigment
a=b=c=1
#Python allows you to assign a single value to several variables.
print(a, b, c)
d,e,f= "Liam","Marvin","Jaz"
#Multiple Assignment
print(d,e,f)
#Python Numbers
var1 = 1
var2 = 2
print(var1, var2)
del var2
#Python String
str = 'Hello World!'
print (str)
print (str[0])
print (str[2:5])
print (str[2:])
print (str * 2)
print (str + "TEST")
#Python List
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list)
print (list[0])
print (list[1:3])
print (list[2:])
print (tinylist * 2)
print (list + tinylist)
#Python Tuple
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple)
print (tuple[0])
print (tuple[1:3])
print (tuple[2:])
print (tinytuple * 2)
print (tuple + tinytuple)
'''
The following code is invalid with tuple,
because we attempted to update a tuple, which is not allowed
tuple[2] = 1000
list[2] = 1000
print (tuple)
'''
#Python Dictionary
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one'])
print (dict[2])
print (tinydict)
print (tinydict.keys())
print (tinydict.values())
'''
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type-name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
int(x [,base]): Converts x to an integer. The base specifies the base if x is a string.
float(x): Converts x to a floating-point number.
complex(real [,imag]) : Creates a complex number.
str(x) : Converts object x to a string representation.
repr(x) : Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) : Converts s to a tuple.
list(s) : Converts s to a list.
set(s) : Converts s to a set.
dict(d) : Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) : Converts s to a frozen set.
chr(x) : Converts an integer to a character.
unichr(x) : Converts an integer to a Unicode character.
ord(x) : Converts a single character to its integer value.
hex(x) : Converts an integer to a hexadecimal string.
oct(x) : Converts an integer to an octal string.
''' | false |
b845ad0bda65047e046e15b02354c6ec7905563b | rafiramadhana/oop-python | /youtube/Corey_Schafer/Python_OOP_Tutorial/02_class_variables.py | 1,186 | 4.40625 | 4 | class Employee:
# class variables
num_of_employees = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
# instance variables
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@company.com"
Employee.num_of_employees += 1
def fullname(self):
return f"{self.first} {self.last}"
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
print(Employee.num_of_employees)
emp_1 = Employee("Corey", "Schafer", 100)
emp_2 = Employee("Anton", "Michael", 100)
# NOTE: Number of employees will be increased by +2.
print(Employee.num_of_employees)
# NOTE: What happened in background is:
# Check if instance has corresponding attribute. Else,
# check if class has corresponding attribute.
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
# NOTE: As you can see, no .raise_amount is shown in emp_1 and
# emp_2. Previously, we are using class' .raise_amount attribute.
print(Employee.__dict__)
print(emp_1.__dict__)
print(emp_2.__dict__)
# NOTE: Here, we are adding a new instance attribute.
emp_1.raise_amount = 2.00
print(emp_1.__dict__)
| true |
29fd5d9ba31f79c08409bc6fb0eb966a1aa350b3 | kath-k3/kath_python_core | /week_02/k3_solutions/4_loops_ex5.py | 577 | 4.25 | 4 | #Take two numbers from the user, an upper and lower bound. Using a loop, calculate the sum
#of numbers from the lower bound to the upper bound. Also, calculate the average of numbers.
#Print the results to the console.
lower_input = int(input("Please give me a number "))
higher_input = int(input("Please give me a higher number "))
print (f"The numbers you provided are {lower_input} and {higher_input}")
my_sum = higher_input
while lower_input < higher_input:
my_sum += lower_input
print(my_sum)
lower_input += 1
print(f"The sum of the numbers is {my_sum}")
| true |
6d994f34fa91bda2bfef378808e6157d2414bb99 | nabaz/python-experiments | /top-100-liked-questions/spiral-order.py | 428 | 4.375 | 4 | '''
Given a matrix of m x n elements (m rows, n columns),
return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
def spiral_order(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
return matrix and matrix.pop(0) + spiral_order([list(x) for x in zip(*matrix)][::-1])
| true |
08db32d40f3bbf606aef9f20fc5bebf2c519ef40 | Jarquevious/Tweet-Generator | /histogram.py | 2,211 | 4.25 | 4 | import string
from time import time
# A histogram() function which takes a source_text argument (can be either a filename
# or the contents of the file as a string, your choice) and return a histogram data structure
# that stores each unique word along with the number of times the word appears in the source text.
# A unique_words() function that takes a histogram argument and returns the total count of
# unique words in the histogram. For example, when given the histogram for
# The Adventures of Sherlock Holmes, it returns the integer 8475.
# A frequency() function that takes a word and histogram argument
# and returns the number of times that word appears in a text. For example,
# when given the word "mystery" and the Holmes histogram, it will return the integer 20.
# What is the least/most frequent word(s)?
# How many different words are used?
# What is the average (mean/median/mode) frequency of words in the text?
# word_histogram = {}
# '''Create function that takes a source text as params and creates a
# dictionary representing a histogram of words in a list'''
#sample data
# sample_string = 'run love May'
def histogram(lines):
#empty dictionery
word_histogram = {}
#lower casing all words and spliting the from inviduals strings
for line in lines:
words = line.rstrip('\n').split()
for word in words:
word_count = word_histogram.get(word, 0) + 1
word_histogram[word] = word_count
return word_histogram
def unique_words(word_histogram):
return len(word_histogram.keys())
# A frequency() function that takes a word and histogram argument and returns the number of times that word appears in a text.
def frequency(hist):
# Takes in user input
user_input = input('enter a word: ')
# If user input not in dictionary raise value error
if user_input not in hist: raise ValueError('That word is not hist')
# Return value from key
return hist[user_input]
if __name__ == '__main__':
filename = "/Users/jarqueviousnelson/Projects/CS-2-Tweet-Generator/source/adamsmith.txt"
file = open(filename, "r")
lines = file.readlines()
hist = histogram(lines)
print(hist)
print(unique_words(hist))
print (frequency(hist))
| true |
b266f0292f2c11532825da0f377d89484e23b9e6 | jwesleylima/Bin2Dec-Python | /bin2dec.py | 1,006 | 4.1875 | 4 | """Module written on 08/22/2021 by JWesleyLima.
Visit my profile: https://github.com/jwesleylima."""
def bin2dec(*, binary_digits: str) -> int:
"""Converts binary digits into decimal numbers.
- Keyword Parameters:
binary_digits: Binary digits as a string.
- Return:
int: Decimal number
- Usage Example:
some_decimal = bin2dec(binary_digits='0101')
"""
binary_digits = binary_digits.replace(' ', '')
VALID_BINARY_DIGITS = ('0', '1')
if not isinstance(binary_digits, str):
raise TypeError('Binary digits must be of type \'str\'')
elif len(binary_digits) == 0:
raise ValueError('An empty string was entered')
elif not str(binary_digits).isnumeric() or not \
all(d in VALID_BINARY_DIGITS for d in binary_digits):
raise ValueError(f'Only binary digits (0 and 1) are allowed: "{binary_digits}" entered')
# Convert
decimal_number = 0
for i, digit in enumerate(binary_digits[::-1]):
decimal_number += (int(digit) * 2 ** i)
return decimal_number
| true |
d9183f0d33ae32910adb2e795365672536a25173 | refrain62/python_study | /004_simple_output/simple_output.py | 213 | 4.3125 | 4 | # Python 3: Simple output (with Unicode)
print("Hello, I'm Python!")
#Hello, I'm Python!
# Input, assignment
name = input('What is your name?\n')
print('Hi, %s.' % name)
#What is your name?
#Python
#Hi, Python.
| true |
135e93398eaa8cdc7be235c11759085dd8c8d2ae | absentee-neptune/Personal-Projects | /Python/PycharmProjects_1718/Week 3 Programming Assignment/Functions.py | 2,469 | 4.1875 | 4 | #Week 3 Programming Assignment - Functions
import math
def miles_to_kilometers(length_in_miles):
# This function converts a number from miles to kilometers
# Arguments:
# length_in_miles(float): The length to convert
# Returns:
# float: The length in kilometers
# Assumptions:
# Assumes that the length in miles is a float
return (length_in_miles * 1.609)
miles_input = float(input("Enter the length in Miles: "))
result_kilometer = miles_to_kilometers(miles_input)
print(result_kilometer)
def pounds_to_grams(weight_in_pounds):
# This function converts a number from pounds to pounds to grams
#
# Arguments:
# weight_in_pounds(float): The weight to convert
#
# Returns:
# float: The weight in grams
#
# Assumptions:
# Assumes that the weight in pounds is a float
return (weight_in_pounds * 453.592)
pounds_input = float(input("Enter the weight in Pounds: "))
result_grams = pounds_to_grams(pounds_input)
print(result_grams)
def britishGallon_to_americanGallon(volume_in_britishGallon):
# This function converts a number from British Gallons to U.S. Gallons
#
# Arguments:
# volume_in_britishGallon(float): The volume to convert
#
# Returns:
# float: The volume in U.S. Gallons
#
# Assumptions:
# Assumes that the volume in British Gallons is a float
return (volume_in_britishGallon * 1.201)
britishGallon_input = float(input("Enter the volume in British Gallons: "))
result_americanGallon = britishGallon_to_americanGallon(britishGallon_input)
print(result_americanGallon)
def power_formula(work, time):
# This function figures the amount of Power in Watts used by using two numerical inputs, Work and Time
# Power = Work / time
#
# Arguments:
# work (float): The force to be divided (in Joules)
# time (float): The amount of time to divide by (in seconds)
#
# Returns:
# float: The amount of Power in Joules per second
#
# Assumptions:
# Assumes the amount of Work is a float
# Assumes that the amount of Time is a float
return (work / time)
work_input = float(input("Enter the amount of Work in Joules: "))
time_input = float(input("Enter the amount of Time in seconds: "))
result_power = power_formula(work_input, time_input)
print(result_power)
| true |
79c24a570d9b9870ad58b844a77ee418c5a800f4 | baothais/Practice_Python | /if_else.py | 922 | 4.28125 | 4 | a = 20
b = 30
c = 40
if a > b:
print("a > b")
elif a < b:
print("a < b")
else:
print("a=b")
# One line if statement
if a==b: print("a=b")
# One line if else statement
print(a) if a < b else print(b)
# One line if else statement, with 3 conditions
print(a) if a > b else print(b) if a < b else print(a, b)
# The and keyword is a logical operator, and is used to combine conditional statements
print(c) if (a < b and a < c) else print(b) if (a > b and a > c) else print(a)
# The or keyword is a logical operator, and is used to combine conditional statements
if a < b or a > c: print(c)
# You can have if statements inside if statements, this is called nested if statements
if a < b:
if a > c:
print(a)
else:
print(b)
# if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
if a > b:
pass
| true |
0146fdf72ef8fdf9b290f6392d86e376baccc97d | suhas-arun/Google-Code-In | /Two-Circles/main.py | 2,479 | 4.25 | 4 | """App that shows the state of two circles"""
import sys
import pygame
def identify_circles(radius1, radius2):
"""Returns which circle is bigger and which is smaller"""
if radius1 > radius2:
bigger, smaller = radius1, radius2
else:
bigger, smaller = radius2, radius1
return (bigger, smaller)
def get_state(bigger, smaller, distance):
"""Identifies the state of the two circles"""
edge_distance = distance - bigger - smaller
if distance == 0:
if bigger == smaller:
return "The circles are the same"
return "The circles are concentric"
if edge_distance in (0, -2 * smaller):
return "The circles have one point of intersection"
if edge_distance > 0 or edge_distance < -2 * smaller:
return "The circles have no points of intersection"
return "The circles have two points of intersection"
def draw_circles(bigger, smaller, distance, state):
"""Draws the circles to the pygame display"""
centre1 = 100 + bigger
centre2 = centre1 + distance
y_pos = 50 + bigger
pygame.draw.circle(SCREEN, (255, 0, 0), (centre1, y_pos), bigger, 1)
pygame.draw.circle(SCREEN, (0, 255, 0), (centre2, y_pos), smaller, 1)
state_font = pygame.font.SysFont("Helvetica", 18)
textsurface = state_font.render(state, False, (0, 0, 0))
SCREEN.blit(textsurface, (WIDTH / 2 - textsurface.get_width() / 2, HEIGHT - 35))
if __name__ == "__main__":
radius1 = int(input("Enter the radius of the first circle: "))
radius2 = int(input("Enter the radius of the second circle: "))
distance = int(input("Enter the distance between the two circles: "))
bigger, smaller = identify_circles(radius1, radius2)
scale_factor = int(50 / bigger)
bigger *= scale_factor
smaller *= scale_factor
distance *= scale_factor
pygame.init()
pygame.font.init()
if smaller + distance > bigger:
WIDTH = 100 + 2 * (bigger + smaller) + distance
else:
WIDTH = 200 + 2 * bigger
HEIGHT = 200
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
SCREEN.fill((255, 255, 255))
pygame.display.set_caption("State of two circles")
state = get_state(bigger, smaller, distance)
draw_circles(bigger, smaller, distance, state)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
pygame.display.update()
| true |
147afd241ab4af3ac02fbff8724fb7746ed3a62e | madhavms/Python_Digital_Programs | /longestsubstring.py | 853 | 4.3125 | 4 | """
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
"""
def longestUniqueSubsttr(string):
seen = {}
max_length = 0
start = 0
for end, c in enumerate(string):
if c in seen:
start = max(start, seen[c] + 1)
seen[c] = end
max_length = max(max_length, end - start + 1)
return max_length
a = "abcabcbb"
print(longestUniqueSubsttr(a))
| true |
f13e23cc3c37254a88a9f3c0fe5834b0f7af0ee8 | cosmos-nefeli/practice_python | /stacks.py | 708 | 4.1875 | 4 | class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
#Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
#use peek to look at the top of the stack
def peek(self):
return self.stack[-1]
# Use elist method to remove element
def remove(self):
if len(self.stack) <= 0:
return ("No element in the stack")
else:
return self.stack.pop()
aStack = Stack()
aStack.add("Mon")
aStack.add("Tue")
aStack.add("Wed")
print(aStack.stack)
print("#Remove the top most element")
print(aStack.remove()) | true |
f6f6db3976318c379c60a3df2cd7bc3cf2d1ce1c | z-memar/PigLatinLanguage | /TranslatingToPiglatinLanguage.py | 1,701 | 4.28125 | 4 | print(" Zahra Memar",'\n',"Homework#3",'\n',"September 25,2019")
print("")
import string
VOWEL=['a','e','i','o','u']
piglet_vowel='hay'
piglet_constant='ay'
def AskUserForSentences():
while True:
try:
sentence= str(input('''Please input a sentence that contains three words
and spaces, Or type "Quit" to exist the program: '''))
if sentence=='Quit':
break
sentence_lowercase = LowercaseSentence(sentence)
split_sentence=SplitSentenceIntoList(sentence_lowercase)
if len(split_sentence)==3:
piglatin_word=ConvertWrodToPigLatin(split_sentence)
PrintThreeWordPhrase(piglatin_word)
else:
print('''Error!, your sentence
includes less or more than three words. ''')
except ValueError:
print("Error!your input is not a string sentence.")
def LowercaseSentence(sentence):
sentence_lowercase = sentence.lower()
print(sentence_lowercase)
return sentence_lowercase
def SplitSentenceIntoList(sentence_lowercase):
split_sentence = (sentence_lowercase).split()
print(split_sentence)
return split_sentence
def ConvertWrodToPigLatin(split_sentence):
piglatin_word=[]
for x in range(3):
word=split_sentence[x]
letter=word[0]
if letter in VOWEL:
piglatin_word.append(word[:] + piglet_vowel)
else:
piglatin_word.append(word[1:]+word[0]+piglet_constant)
return piglatin_word
def PrintThreeWordPhrase(piglatin_word):
print(piglatin_word[0],piglatin_word[1],piglatin_word[2])
print("***")
AskUserForSentences()
| true |
68628d5be0224de8f091379a95c6e795bba26478 | allybrannon/week1_friday | /sean_replace_2.py | 415 | 4.15625 | 4 | # working on removing names from a list and replacing with another name
staff_list = ["Sean", "David", "Mary Ella", "Liz", "Natalie", "Tasha", "Jake", "Max"]
print(staff_list)
staff_list[staff_list.index("Sean")] = "Ranger"
print(staff_list)
if "David" in staff_list:
indexofDavid = staff_list.index("David")
staff_list.insert(indexofDavid, "Not David")
staff_list.remove("David")
print(staff_list)
| true |
62d2e18572025024c6eb278852524bf98658756e | JWLee89/python-study | /src/property/factory.py | 1,784 | 4.21875 | 4 | import typing as t
class Dummy:
"""
Used as dummy to prove that property
is a class. Note that both classes and
functions are similar in the fact that
both are "callable" objects
"""
def __init__(self):
self.a = 10
print(f"function callable: {callable(print)}, "
f"Class callable: {callable(Dummy)}")
def quantity(name: str):
"""
Create a quantity property, which by definition is:
1. A positive Integer (>= 0)
Args:
name (str): The name of the property
Returns:
"""
def getter(instance: t.Any) -> int:
"""
Get the item from the instance
"""
return instance.__dict__[name]
def setter(instance, new_value: int):
"""
Setter for newly-created property
Args:
instance (t.Any): The instance to attach property to
new_value (int): The new value to assign
"""
if not isinstance(new_value, int):
raise TypeError("New value must be an integer")
if new_value < 0:
raise ValueError("'new_value' must be greater than "
"or equal to 0")
instance.__dict__[name] = new_value
# Note also that surprisingly,
# @property is a class
print(f"property is: {type(property)}, "
f"print is type: {type(print)}, "
f"StoreItem is type: {type(Dummy)}")
return property(getter, setter)
class StoreItem:
qty = quantity('quantity')
def __init__(self, item_count):
self.qty = item_count
if __name__ == "__main__":
Dummy()
item = StoreItem(10)
try:
error_item = StoreItem(10.5)
except TypeError as ex:
print("New value is a float ... ")
print(ex)
| true |
895420a6cb856322be1e37686e80882adf090de0 | estraviz/Python_Design_Patterns_Lynda | /Behavioral_Patterns/visitor.py | 1,848 | 4.25 | 4 | class House(object):
""" The class being visited """
def accept(self, visitor):
""" Interface to accept a visitor """
# Triggers the visiting operation!
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
# We have a reference to the HVAC (Heating, ventilation and air conditioning) specialist object in the House object
print(self, "worked on by", hvac_specialist)
def work_on_electricity(self, electrician):
# We now have a reference to the electrician object in the House object
print(self, "worked on by", electrician)
def __str__(self):
""" Return the class name when the House object is printed """
return self.__class__.__name__
class Visitor(object):
""" Abstract visitor """
def __str__(self):
""" Return the class name when the Visitor object is printed """
return self.__class__.__name__
class HvacSpecialist(Visitor):
""" Concrete visitor: HVAC specialist. Inherits from the parent class, Visitor """
def visit(self, house):
# The visitor now has a reference to the House object
house.work_on_hvac(self)
class Electrician(Visitor):
""" Concrete visitor: electrician. Inherits from the parent class, Visitor """
def visit(self, house):
# The visitor now has a reference to the House object
house.work_on_electricity(self)
# Create an HVAC specialist
one_hvac_specialist = HvacSpecialist()
# Create an electrician
one_electrician = Electrician()
# Creat a house
one_house = House()
# Let the house accept the HVAC specialist and work on the house by invoking the visit() method
one_house.accept(one_hvac_specialist)
# Let the house accept the electrician and work on the house by invoking the visit() method
one_house.accept(one_electrician)
| true |
69afd27c2ec7497e863f50cf9753472366a39b51 | garvitsaxena06/Python-learning | /27.py | 285 | 4.15625 | 4 | #building a translator
def translator(string):
translate = ''
for letter in string:
if letter in "AEIOUaeiou":
translate += 'g'
else:
translate += letter
return translate
string = input("Enter a string: ")
print(translator(string))
| false |
72543c8b0fbed2dcd0d5cc2eac9a86dd91338fef | Rvelchuri/OO-Melons | /melons.py | 1,885 | 4.125 | 4 | """Classes for melon orders."""
class AbstractMelonOrder():
"""A melon order within the USA."""
def __init__(self, species, qty, tax):
"""Initialize melon order attributes."""
self.species = species
self.qty = qty
self.shipped = False
self.tax = tax
def get_total(self):
"""Calculate price, including tax."""
base_price = 5 * 1.5
total = (1 + self.tax) * self.qty * base_price
return total
def mark_shipped(self):
"""Record the fact than an order has been shipped."""
self.shipped = True
class DomesticMelonOrder(AbstractMelonOrder):
"""A melon order within the USA."""
order_type = "domestic"
def __init__(self, species, qty, tax):
"""Initialize melon order attributes."""
super().__init__(species, qty, tax)
class InternationalMelonOrder(AbstractMelonOrder):
"""An international (non-US) melon order."""
order_type = "international"
def __init__(self, species, qty, tax, country_code):
"""Initialize melon order attributes."""
super().__init__(species,qty, tax)
self.country_code = country_code
def get_total(self):
if self.qty < 10:
return super().get_total() + 3
return super().get_total()
def get_country_code(self):
"""Return the country code."""
return self.country_code
order0 = InternationalMelonOrder("watermelon",6, .17, "AUS")
x = order0.get_total()
print(x)
order0 = InternationalMelonOrder("watermelon",10, .17, "AUS")
x = order0.get_total()
print(x)
order0 = InternationalMelonOrder("watermelon",16, .17, "AUS")
x = order0.get_total()
print(x)
code = order0.get_country_code()
print(f"country code {code}")
order1 = DomesticMelonOrder("cantaloupe",8 , .08)
y = order1.get_total()
print(y)
| true |
06b23e46c8862a2a3ab779c2dfd4b094a8b55540 | hashansl/dash-plotly-training | /Python OOP/innerclass.py | 729 | 4.65625 | 5 | #6
# you can create object of inner class inside the outer class
#OR
# you can create object of inner class outside the outer class provided you use outer class name to call it
class Student:
#Outer class
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
self.lap = self.Laptop()
def show(self):
print(self.name, self.rollno)
self.lap.show()
class Laptop:
#inner Class
def __init__(self):
self.brand = 'HP'
self.cpu = 'i5'
self.ram = 8
def show(self):
print(self.brand,self.cpu,self.ram)
s1 = Student('Hashan',2)
s2 = Student('Dananjaya',3)
s1.show()
lap1 = Student.Laptop()
| false |
386baf28ebba3261b361c17db314ae03ac67a426 | hashansl/dash-plotly-training | /Python OOP/method_init.py | 495 | 4.125 | 4 | #2
class Computer:
#Basically we use inti to initialize variables
#We are actually passing 3 arguments here (com1,cpu,ram) ---> com1 passes automatically
def __init__(self,cpu,ram):
self.cpu = cpu;
self.ram= ram;
def config(self):
print("Config is ",self.cpu,self.ram)
#when we creating a object init method will run automatically (for every object it will call once)
com1 = Computer('i5',16)
com2 = Computer('Ryzen 3',8)
com1.config()
com2.config()
| true |
047de24233a89b6340204c64fa8ffd7348e1ac34 | meeree/Python-stuff | /math/knights_problem.py | 409 | 4.25 | 4 | #Every time that a y value is changed: call a function that checks if any x values are below it and, if so, sends them through all possible ys. Method to change the current position of a number
import numpy as np
my_list = [i for i in range(1, 9)]
print(my_list)
board = np.zeros((7,8))
print(board)
board = np.insert(board, 0, np.ones(8), axis = 0)
print(board)
#for y in range(8):
# for x in range(8):
| true |
56cda6705a18ea62cb451c82902b2e55ea1b8aba | vishuwishsingh/py-code | /The_Basics/The_Basics_Operations_with_Data_Types | 1,153 | 4.59375 | 5 | Lists, strings, and tuples have a positive index system:
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
0 1 2 3 4 5 6
And a negative index system:
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-7 -6 -5 -4 -3 -2 -1
In a list, the 2nd, 3rd, and 4th items can be accessed with:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[1:4]
Output: ['Tue', 'Wed', 'Thu']
First three items of a list:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:3]
Output:['Mon', 'Tue', 'Wed']
Last three items of a list:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[-3:]
Output: ['Fri', 'Sat', 'Sun']
Everything but the last:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:-1]
Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
Everything but the last two:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:-2]
Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
A single in a dictionary can be accessed using its key:
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
phone_numbers["Marry Simpsons"]
Output: '+423998200919' | false |
28b6fc79bbc16a20bacde899f43a76a665676c5d | AFresnedo/computer-science-theory | /graphs/python/bfs.py | 1,734 | 4.125 | 4 | # Current version is flimsy & unrefactored code to practice algorithm design
# Lists do not dequeue effeciently (requires position updates)
from collections import deque
# Graph is implemented using an adjacency list (instead of adj matrix)
class Graph:
def __init__(self):
self.adj_list = {}
def add_edge(self, start, end):
if start in self.adj_list:
self.adj_list[start].append(end)
else:
self.adj_list[start] = [end]
# Print nodes using a bfs, starting from s
# s is the index of the node in adj_list
def print_bfs(self, s = 0):
# Discovered is a list tracking if nodes have been explored
discovered = [False] * len(self.adj_list)
# Create to-explore queue with starting node
queue = deque([s])
# Continue exploring until to-explore queue is empty
while len(queue) > 0:
# Get next node to explore in this layer
explore = queue.popleft()
# Mark node as explored so it is not re-entered into the queue
discovered[explore] = True
print('exploring: ' + str(explore))
# Add all unexplored adj nodes for discovery in next layer
for adj in self.adj_list[explore]:
if (discovered[adj] == False):
queue.append(adj)
print('---FIRST TEST---')
first = Graph()
first.add_edge(0, 1)
first.add_edge(1, 0)
first.add_edge(1, 2)
first.add_edge(2, 1)
first.add_edge(2, 3)
first.add_edge(3, 2)
first.print_bfs()
print('---SECOND TEST---')
second = Graph()
second.add_edge(0, 1)
second.add_edge(0, 2)
second.add_edge(1, 2)
second.add_edge(2, 0)
second.add_edge(2, 3)
second.add_edge(3, 3)
second.print_bfs(2)
| true |
3be1451c533dc8121e909b7f40def217dcf7f4a6 | AishwaryaBhaskaran/261644_Daily-commits-Python | /str.py | 470 | 4.25 | 4 | #Write a python program to check the user input abbreviation.If the user enters "lol", print "laughing out loud".If the user enters "rofl", print "rolling on the floor laughing".If the user enters "lmk", print "let me know".If the user enters "smh", print "shaking my head"
str=input()
if str=="lol":
print("laughing out loud")
elif str=="rofl":
print("rolling on the floor laughing")
elif str=="lmk":
print("let me know")
else:
print("shaking my head")
| true |
1b6ebe3c39ee3a64f8f49b5df8c074c1ef5c5310 | ilyaostapchenko/ostapchenko | /homework/lesson_18_Ostapchenko_I/task_4_lesson_18_Ostapchenko_I.py | 510 | 4.1875 | 4 | def readlines(filename):
with open(filename, "r") as file:
lines = file.readlines()
return lines
def get_longest_line(lines):
lst = [item.strip() for item in lines]
longest_line = lst
for item in lst:
if len(item) > len(longest_line):
longest_line = item
return len(longest_line)
if __name__ == '__main__':
filename = "file_directory/testing_file.txt"
lines = readlines(filename)
print(f"Longest string length: {get_longest_line(lines)}") | true |
75fa6d7f1227ab82c188ed5a4a6586ff54bd8637 | ilyaostapchenko/ostapchenko | /homework/lesson_14_HW_Ostapchenko_I.py | 1,985 | 4.1875 | 4 | # The same tuples for all tasks
t1 = (1, 4, 8, 3, 5)
t2 = (1, 6, 7, 3)
t3 = (1, 4, 2, 3, 8, 7)
print(f"Tuple 1: {t1}\nTuple 2: {t2}\nTuple 3: {t3}")
# Задание 1
# Есть три кортежа целых чисел необходимо найти
# элементы, которые есть во всех кортежах.
def same_elements(t1, t2, t3):
""" returns the same elements """
same_numbers = []
for i in tuple(t1):
if i in t2 and i in t3:
if i not in same_numbers:
same_numbers.append(i)
return tuple(same_numbers)
print("\nTask 1:", same_elements(t1, t2, t3), sep='\n')
# Задание 2
# Есть три кортежа целых чисел необходимо найти
# элементы, которые уникальны для каждого списка.
def unique_elements(t1, t2, t3):
""" Returns unique elements """
unique_numbers = []
for i, j, k in zip(t1, t2, t3):
if i not in t2 and i not in t3:
if i not in unique_numbers:
unique_numbers.append(i)
if j not in t1 and j not in t3:
if j not in unique_numbers:
unique_numbers.append(j)
if k not in t1 and k not in t2:
if k not in unique_numbers:
unique_numbers.append(k)
return tuple(unique_numbers)
print("\nTask 2:", unique_elements(t1, t2, t3), sep='\n')
# Задание 3
# Есть три кортежа целых чисел необходимо найти элементы, которые есть в каждом из кортежей и находятся
# в каждом из кортежей на той же позиции.
def same_index(t1, t2, t3):
"""Returns the same index of numbers with the same number"""
for i in range(len(t1) - 1):
if t1[i] == t2[i] == t3[i]:
print(f"The index of number ({t1[i]}) is {i}")
print("\nTask 3:")
same_index(t1, t2, t3) | false |
65f64d86216cde918859971002929114c26ade99 | ilyaostapchenko/ostapchenko | /homework/lesson_4_Ostapchenko_I.py | 2,951 | 4.3125 | 4 | """Завдання 1
Користувач вводить 3 числа. Далі в залежності від вибору користувача потрібно знайти суму або добуток цих чисел.
(Тобто програма запитує в користувача, що потрібно зробити)
"""
print("Write me three numbers, and I will refund you the sum or multiplication of these numbers.")
a = input("a: ")
b = input("b: ")
c = input("c: ")
operation = input('What to do with them? ("+", "*"): ')
if "+" in operation:
sum = int(a) + int(b) + int(c)
print("Sum: " + str(sum))
else:
mult = int(a) * int(b) * int(c)
print("Multiplication: " + str(mult))
# """
# Завдання 2
# Користувач вводить 3 числа. Далі в залежності від вибору користувача потрібно знайти найбільше з 3-х,
# найменше, або середнє арифметичне.
# (Подібно до 1-го)
# """
# print("Write me three numbers, and I will find the largest of the 3 numbers,"
# + " the smallest or arithmetic mean.")
# a = int(input("a: "))
# b = int(input("b: "))
# c = int(input("c: "))
# operation = input("What number to find? (largest, smallest, or arithmetic mean): ")
# if "min" in operation:
# m = a
# if m > b:
# m = b
# if m > c:
# m = c
# print('min: ' + str(m))
# # print(min(a, b, c))
# elif "max" in operation:
# if a > b > c:
# print("max: ", str(a))
# elif b > a > c:
# print("max: ", str(b))
# else:
# print("max: ", str(c))
# # m = a
# # if m < b:
# # m = b
# # if m < c:
# # m = c
# # print("max: ", str(m))
# # print(max(a, b, c))
# else:
# list = [a, b, c]
# print("arithmetic mean: " + str(sum(list) / len(list)) )
# """
# Завдання 3
# Користувач вводить з клавіатури кількість метрів. В залежності від вибору -
# програма конвертує їх в сантиметри, міліметри, або кілометри.
# """
# m = int(input("Enter the number of meters or kilometers: "))
# operation = input("Convert them to centimeters, millimeters or kilometers?: ")
# if "mm" in operation:
# if m == 1:
# meter = "meter"
# else:
# meter = "meters"
# mm = m / 0.001
# print(str(m) + " " + meter + " equal to " + str(mm) + " millimeters.")
# elif "cm" in operation:
# if m == 1:
# meter = "meter"
# else:
# meter = "meters"
# cm = m / 0.01
# print(str(m) + " " + meter + " equal to " + str(cm) + " centimeters.")
# elif "km" in operation:
# if m == 1:
# meter = "meter"
# else:
# meter = "meters"
# km = m / 1000
# print(str(m) + " " + meter + " equal to " + str(km) + " kilometers.")
| false |
fe53e538ec7b04245b3d419c10b0e05aa8bd88db | PGYangel/python_test | /sentence/for.py | 1,365 | 4.15625 | 4 | '''
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的语法格式如下:
for iterating_var in sequence:
statements(s)
实例:
for letter in 'Python': # 第一个实例
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print '当前水果 :', fruit
另外一种执行循环的遍历方式是通过索引,如下实例:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。
在 python 中,for … else 表示这样的意思,
for 中的语句和普通的没有区别,
else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,
while … else 也是一样。
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print '%d 等于 %d * %d' % (num,i,j)
break # 跳出当前循环
else: # 循环的 else 部分
print num, '是一个质数'
'''
| false |
f28a05d73ae8a1ac6e1245ce3be387e815ddb76d | PGYangel/python_test | /operator/member.py | 1,019 | 4.15625 | 4 | '''
成员运算符:
Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组
运算符 描述 实例
in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
'''
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print("1 - 变量 a 在给定的列表中 list 中")
else:
print("1 - 变量 a 不在给定的列表中 list 中")
if (b not in list):
print("2 - 变量 b 不在给定的列表中 list 中")
else:
print("2 - 变量 b 在给定的列表中 list 中")
# 修改变量 a 的值
a = 2
if (a in list):
print("3 - 变量 a 在给定的列表中 list 中")
else:
print("3 - 变量 a 不在给定的列表中 list 中")
| false |
80e1ae34715b2e23c5b2b262edf05abaf1c33959 | soura49/Python | /IntroductionToPython/function_param.py | 269 | 4.28125 | 4 | def print_max(a,b):
if a>b:
print a, 'is max'
elif a==b:
print a, 'is equal to',b
else:
print b, 'is max'
number1 = int(raw_input('enter the number:'))
number2 = int(raw_input('enter the other number:'))
print_max(number1,number2)
| false |
f49be953a520cb36bb7f984a8b3bc0cb841a3d39 | Alirezak2n/Python-Tutorials | /9-Generators.py | 1,252 | 4.15625 | 4 | # Generators
range(100) # it is a generator too
# all generators like range are iterables but not are iterables like list are generator
def generator_func(num):
for i in range(num):
yield i # it pause function and comes back later, if we use return it is not a generator
for item in generator_func(1000):
print(item) # here it print only one number each time
print(generator_func(10))
ge=generator_func(10)
next(ge) # with next it goes to next number
print(next(ge))
def our_for(iterable): # how for loops work
iterator = iter(iterable)
while True:
try:
print(iterator)
print(next(iterator)*2)
except StopIteration:
break
our_for([1,2,3])
class MyGen(): # how range work
current = 0
def __init__(self,first,last): # a class with the option of first and last
self.first = first
self.last = last
def __iter__(self): # make the class iterable
return self
def __next__(self):
if MyGen.current < self.last:
num = MyGen.current
MyGen.current +=1
return num
raise StopIteration
gen = MyGen(0,100)
for i in gen:
print(i)
| true |
2ee8cef2fc2bf83fca3a4e709f0d9e3dbef404d1 | Sarswatshray/Calculator-from-Object-Oriented-Programming | /Calculator_from_object_oriented_programming.py | 1,443 | 4.21875 | 4 | class cal:
def __init__(self, num1, num2, operator):
self.num1 = num1
self.num2 = num2
self.operator = operator
if self.operator == "+":
print(f"The sum of {self.num1} and {self.num2} is {self.num1 + self.num2}")
elif self.operator == "-":
print(f"The difference between {self.num1} and {self.num2} is {self.num1 - self.num2}")
elif self.operator == "*":
print(f"The product of {self.num1} and {self.num2} is {self.num1 * self.num2}")
elif self.operator == "**":
print(f"The result when the power of {self.num1} is {self.num2} is {self.num1 ** self.num2}")
elif self.operator == "/":
print(f"The quotient when {self.num1} is divided by {self.num2} is {self.num1 / self.num2}")
elif self.operator == "//":
print(f"The nearest number which can divide {self.num1} with {self.num2} is {self.num1 // self.num2}")
elif self.operator == "%":
print(f"The remainder when {self.num1} is divided by {self.num2} is {self.num1 % self.num2}")
else:
print("Please select one from these given operators: +, -, *, **, /, //, % \n")
op = input("Enter a operator here to choose what you want to do, the options are: +, -, *, **, /, //, % \n")
a = int(input("Enter a number here\n"))
b = int(input("Enter another number here\n"))
e = cal(a, b, op) | false |
f962e824ac6e7d2ea2022009231548a833355d29 | CodevEnsenada/actividades | /alumnos/Luis Omar/Actividad 03/Actividad-2.py | 417 | 4.125 | 4 | #act.2
num1=float(input("Ingresa el primer numero\n"))
if (num1<0):
print("Valor incorrecto")
elif(num1>0):
num2=float(input("Ingresa el segundo numero\n"))
if(num2<0):
print("Valor incorrecto")
elif(num2>0):
num3=float(input("Ingresa el tercer numero\n"))
if(num3<0):
print("Valor incorrecto,no se puede calcular el promedio")
else:
promedio=(num1+num2+num3)/3
print("El promedio es:"+ str(promedio)) | false |
ad040c6e7c8227334ae22e9e32438076f8255409 | Jeff-Hill/Python-Intro | /exercises/tuples/zoo.py | 1,672 | 4.5625 | 5 | # Create a tuple named zoo that contains 10 of your favorite animals.
# Find one of your animals using the tuple.index(value) syntax on the tuple.
zoo = ("gorilla", "zebra", "giraffe", "lion", "tiger", "parrot", "snake", "elephant", "rhino", "monkey")
print(zoo.index("gorilla"))
# Determine if an animal is in your tuple by using value in tuple syntax.
animal_to_find = "giraffe"
if animal_to_find in zoo:
# Print that the animal was found
print("Animal is in your zoo")
else:
print("Animal is not in your zoo")
# You can reverse engineer (unpack) a tuple into another tuple
# with the following syntax.
children = ("Sally", "Hansel", "Gretel", "Svetlana")
(first_child, second_child, third_child, fourth_child) = children
print(first_child) # Output is "Sally"
print(second_child) # Output is "Hansel"
print(third_child) # Output is "Gretel"
print(fourth_child) # Output is "Svetlana"
# Create a variable for the animals in your zoo tuple,
# and print them to the console.
print("assign zoo to variable and print", zoo)
(a, b, c, d, e, f, g, h, i, j) = zoo
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
print(i)
print(j)
# Convert your tuple into a list.
zoo_list = list(zoo)
print("convert tuple to a list", zoo_list)
# Use extend() to add three more animals to your zoo.
zoo_list.extend(["lizard"])
zoo_list.extend(["ostrich"])
zoo_list.extend(["alligator"])
print("zoo with 3 new animals", zoo_list)
# OR us append to add 3 animals using only a string
zoo_list.append("fish")
zoo_list.append("otter")
zoo_list.append("kangaroo")
# Convert the list back into a tuple.
zoo_tuple = tuple(zoo_list)
print("zoo tuple", zoo_tuple)
| true |
8344db2a7dd3c4b57d532d75de75c4eba89463ab | nephewtom/hacker-rank | /day1/plus-minus.py | 894 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def plusMinus(arr):
# Write your code here
zeroes = 0
positives = 0
negatives = 0
for x in arr:
if x > 100 or x < -100:
print("Elements can not be outside [-100, 100] range")
return
if x == 0:
zeroes += 1
elif x > 0:
positives += 1
else:
negatives += 1
size = len(arr)
print("%.6f\n%.6f\n%.6f\n" % (positives/size, negatives/size, zeroes/size))
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
if len(arr) == 0 or len(arr) > 100:
print("Array can not be greater than 100 elements")
else:
plusMinus(arr)
| true |
4d590a8ae0c1d5982bf638b39d4dd3d6104a778a | MeCBing/Algorithms | /hw1_sol/solutions/qsort.py | 1,131 | 4.125 | 4 | #!/usr/bin/env python3
import sys
def sort(a):
if a == []:
return []
pivot = a[0]
left = [x for x in a if x < pivot]
right = [x for x in a[1:] if x >= pivot]
return [sort(left)] + [pivot] + [sort(right)]
def sorted(tree):
return [] if tree == [] else sorted(tree[0]) + [tree[1]] + sorted(tree[2])
def _search(tree, x):
if tree == [] or tree[1] == x:
return tree
return _search(tree[0], x) if x < tree[1] else _search(tree[2], x)
def search(tree, x):
return _search(tree,x) != []
def insert(tree, x):
r = _search(tree, x)
if r == []:
r += [[], x, []]
if __name__ == '__main__':
tree = sort([4,2,6,3,5,7,1,9])
print(tree)
t1 = sorted(tree)
print(t1)
print(search(tree,6))
print(search(tree,6.5))
insert(tree,6.5)
print(tree)
insert(tree,3)
print(tree)
tree = sort([4,2,6,3,5,7,1,9]) # starting from the initial tree
print(_search(tree, 3))
print(_search(tree, 0))
print(_search(tree, 6.5))
print(_search(tree, 0) is _search(tree, 6.5))
print(_search(tree, 0) == _search(tree, 6.5))
| false |
3eeb6da03607d75a10acc793b18b47036d592da7 | khatriamit/HackerRankPythonTest | /task17.py | 1,061 | 4.125 | 4 | """
You are given an HTML code snippet of lines.
Your task is to print the single-line comments, multi-line comments and the data.
Print the result in the following format:
Sample Input
4
<!--[if IE 9]>IE9-specific content
<![endif]-->
<div> Welcome to HackerRank</div>
<!--[if IE 9]>IE9-specific content<![endif]-->
Sample Output
>>> Multi-line Comment
[if IE 9]>IE9-specific content
<![endif]
>>> Data
Welcome to HackerRank
>>> Single-line Comment
[if IE 9]>IE9-specific content<![endif]
Current Buffer (saved locally, editable)
"""
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_comment(self, data):
if "\n" not in data:
print(">>> Single-line Comment")
print(data)
elif "\n" in data:
print(">>> Multi-line Comment")
print(data)
def handle_data(self, data):
if data != "\n":
print(">>> Data")
print(data)
html = ""
for i in range(int(input())):
html += input()
parser = MyHTMLParser()
parser.feed(html)
| true |
360fba7d84412af9c4c5198b56f9abbf529dd8dd | james-soohyun/CS61A_old | /Guerilla/guerilla02.py | 2,281 | 4.25 | 4 | # Question 1
def make_skipper(n):
"""Return a function that takes int x as an input and prints all numbers between 0 and x, skipping every nth number (meaning skip any value that is a multiple of n).
Args:
n (int): Multiple that must be skipped when printing
x (int): Upper limit of numbers that must be printed by the inner function.
Return:
function: make_skipper returns a function that prints and has no return.
>>> a = make_skipper(2)
>>> a(5)
1
3
5
"""
def print_range(x, print_this=1):
if print_this <= x:
if print_this % n != 0:
print(print_this)
print_range(x, print_this+1)
return print_range
# EXTRA: Question 2
def make_alternator(f, g):
"""Return a function that takes in an int x and prints all the numbers between 1 and x, applying function f to every odd-indexed number and g to every even_indexed number before printing.
Args:
x (int): Upper range of index numbers to be printed.
f (function): Function that is to be applied to every odd-indexed number before printing.
g (function): Function that is to be applied to every even_indexed number before printing.
Return:
function: make_alternator returns a function that prints integers and has no return.
>>> a = make_alternator(lambda x: x * x, lambda x: x + 4)
>>> a(5)
1
6
9
8
25
>>> b = make_alternator(lambda x: x * 2, lambda x: x + 2)
>>> b(4)
2
4
6
6
"""
def printer(x, index=1):
if index <= x:
if index % 2 == 1:
print(f(index))
elif index % 2 == 0:
print(g(index))
printer(x, index+1)
return printer
# Recursion
# Question 1a
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
# Question 1c
def mystery(n):
# Recursive summation function
if n == 0:
return 0
else:
return n + mystery(n-1)
def foo(n):
# Fake Fibonacci sequence, only return 0
if n < 0:
return 0
return foo(n - 2) + foo(n - 1)
def fooply(n):
if n < 0:
return 0
return foo(n) + fooply(n-1)
| true |
d3e1094c8c96b361ffcc1cfe5b75987dec14f112 | sangeethadhanasekar/new_python | /palindrome.py | 258 | 4.46875 | 4 | print("***program_to_find_a_number_as_palindrome_or_not***")
a=input("enter a number: ")
for i in a :
reverse=a[::-1]
if reverse==a:
print("the given number",a,"is a palindrome")
else:
print("the given number",a,"is not a palindrome")
| false |
5769647cf9002a2f50c3a3f32d482e4a7091f8a0 | YichaoLeoLi/CS550 | /Fall term/homework /userinput.py | 438 | 4.125 | 4 | #Leo Li
#09/27/18
#Description: Create a list of 15 random numbers from 0-100. Ask the user for one input from 0-100. Append this input to the list. Sort the list into descending order.
import random
x = []
y = 0
while y<15:#take 15 random numbers
x.append(random.randint(0,100))
y+=1
z = int(input("\nplease enter a number between 0-100\n\n>>"))
x.append(z)
x.sort(reverse=True)#take the useer input and then reverse sort it.
print(x) | true |
612a375cdfc326c9049eddf86ac1ebf9a5da9621 | adambatchelor2/python | /codewars_test.py | 447 | 4.15625 | 4 |
# The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
#
# What if the string is empty? Then the result should be empty object literal, {}.
strIn = "asdasda"
listIn = list(strIn)
listIn.sort()
dict = {}
for x in listIn:
if x in dict:
dict[x] += 1
else:
dict[x] = 1
print(dict)
# for x,i in dict.items():
# print(x + str(i)) | true |
64e0285214f7485ff5c17158419f98c40d79c795 | adambatchelor2/python | /Edabit_27122019_IterateSum.py | 323 | 4.25 | 4 | #Create a function that takes a number as an argument. Add up all the numbers from
#1 to the number you passed to the function. For example, if the input is 4 then your
#function should return 10 because 1 + 2 + 3 + 4 = 10.
def add_up(num):
y = 0
for x in range(1,num+1):
y = y + x
return y
print (add_up(11)) | true |
83fc3d2c61d962bfee3dcfbd1368c45e48f5f1b9 | bayliewarrick/python101 | /11-11/application_activity.py | 672 | 4.125 | 4 | """
persons = []
while True:
first = input("Enter first name: ")
last = input("Enter last name: ")
age = int(input("Enter age: "))
person = {
'firstname': first,
'lastname': last,
'age': age
}
persons.append(person)
choice = input("Enter q to quit or any other key to continue")
if(choice == "q"):
break
print(persons)
"""
car_dealership = {
"name":"Dealership 1",
"cars": [{
"make": "honda"
"model": "accord"
}]
}
person = {
"name": "John Doe",
"age": 34,
"address": {
"street":"1200 Richmond Ave",
"city":"Houston"
"state":"TX"
}
} | false |
84d2195b0617ece5fde3b1b813bb104e60570e3c | bayliewarrick/python101 | /11-13/lecture_notes.py | 1,186 | 4.1875 | 4 | """
#open file in write mode
file_object = open('todo.txt','w')
file_object.write('hello, python!')
file_object.close()
#better way to write to file, will automatically close for you.
with open('todo.txt', 'w') as file_object:
file_object.write("Hello world!!!")
#read text from file:
with open('MyTasks.txt') as file_object:
contents = file_object.read()
print(contents) # or print(contents.rstrip())
#json
{
'name':john #valid json
}
#json 2
invalid json:
{
'name': 'john'
}
{
'name':'mary'
}
"""
import json
class Customer:
def __init__(self,name):
self.name = name
def to_dictionary(self):
return self.__dict__
def create_customer_from_dict(dictionary):
return Customer(dictionary['name'])
customer = Customer("john doe")
"""
with open('customers.json','w') as file_object:
json.dump(customer.to_dictionary(), file_object)
"""
#reading back an object from json
with open('customers.json') as file_object:
customer_dictionary = json.load(file_object)
print(customer_dictionary)
customer = create_customer_from_dict(customer_dictionary)
print(customer)
print(customer.name)
| true |
d6c85e4d25a4f4ea40ecbe9b5e6a348c85e4ca6d | feliciahsieh/holbertonschool-webstack_basics | /0x01-python_basics/13-add_integer.py | 777 | 4.5 | 4 | #!/usr/bin/python3
""" 13-add_integer.py - adds 2 integers with type checking
"""
def add_integer(a, b):
"""
add_integer - adds 2 integers with type checking
Arguments:
a: operand 1
b: operand 2
Returns: raises an rror with a message
"""
# Check for Infinite number
if a == float('inf') or a == -float('inf'):
return float('inf')
if b == float('inf') or b == -float('inf'):
return float('inf')
# Check for NaN
if a != a or b != b:
return float('nan')
if type(a) is int or type(a) is float:
if type(b) is int or type(b) is float:
return int(a) + int(b)
else:
raise TypeError("b must be an integer")
else:
raise TypeError("a must be an integer")
| true |
8c53e36527e8c53096172ad852e06a0996aa215e | feliciahsieh/holbertonschool-webstack_basics | /0x01-python_basics/10-simple_delete.py | 486 | 4.125 | 4 | #!/usr/bin/python3
""" 10-simple_delete.py - delete a dictionary entry with given key
"""
def simple_delete(my_dict, key=""):
"""
simple_delete() - delete a dictionary entry with given key
Arguments:
my_dict: dictionary to check
key: key in dictionary to delete
Returns: original my_dict if key not found or modified my_dict
"""
if type(my_dict) is dict and type(key) is str:
if key in my_dict:
del my_dict[key]
return my_dict
| true |
3cfe97a1adc044e64c44cd9dc6a591acafa08943 | Caioleto10/python_turtle_exemplos | /exemplo14.py | 588 | 4.125 | 4 | '''
Exemplo de interação com a tela
com uso do teclado
'''
from turtle import *
def up():
setheading(90)
forward(100)
def down():
setheading(270)
forward(100)
def left():
setheading(180)
forward(100)
def right():
setheading(0)
forward(100)
#o listen ativa o modo 'escuta' para levar em consideração os comandos
listen()
#onkey dispara uma função depois de digitado uma determinada tela
onkey(up, 'Up')
onkey(down, 'Down')
onkey(left, 'Left')
onkey(right, 'Right')
onkey(up, 'w')
onkey(down, 's')
onkey(left, 'a')
onkey(right, 'd')
done() | false |
540c011658d3bcc053c051e012dc4d62e11746fe | sukhadagholba/Sprint-Challenge--Intro-Python | /src/cityreader.py | 2,695 | 4.3125 | 4 | # Create a class to hold a city location. Call the class "City". It should have
# fields for name, latitude, and longitude.
import csv
# TODO
class City():
def __init__(self, name, latitude, longitude):
self.name=name
self.latitude=latitude
self.longitude=longitude
# We have a collection of US cities with population over 750,000 stored in the
# file "cities.csv". (CSV stands for "comma-separated values".)
#
# Use Python's built-in "csv" module to read this file so that each record is
# imported into a City instance. (You're free to add more attributes to the City
# class if you wish, but this is not necessary.) Google "python 3 csv" for
# references and use your Google-fu for other examples.
#
# Store the instances in the "cities" list, below.
#
# Note that the first line of the CSV is header that describes the fields--this
# should not be loaded into a City object.
cities = []
f = open('cities.csv')
city_file = csv.reader(f)
citiesAll=[City(row[0], row[3], row[4]) for row in city_file]
cities=citiesAll[2:]
# TODO
# Print the list of cities (name, lat, lon), 1 record per line.
print('\nList of cities:')
for c in cities:
print(f'name:{c.name},lat:{c.latitude},lon:{c.longitude}')
# TODO
# *** STRETCH GOAL! ***
#
# Allow the user to input two points, each specified by latitude and longitude.
# These points form the corners of a lat/lon square. Output the cities that fall
# within this square.
#
# Be aware that the user could specify either a lower-left/upper-right pair of
# coordinates, or an upper-left/lower-right pair of coordinates. Hint: normalize
# the input data so that it's always one or the other (what is latMin, latMax?)
# then search for cities.
#
# Example I/O:
#
# Enter lat1,lon1: 45,-100
# Enter lat2,lon2: 32,-120
# Albuquerque: (35.1055,-106.6476)
# Riverside: (33.9382,-117.3949)
# San Diego: (32.8312,-117.1225)
# Los Angeles: (34.114,-118.4068)
# Las Vegas: (36.2288,-115.2603)
# Denver: (39.7621,-104.8759)
# Phoenix: (33.5722,-112.0891)
# Tucson: (32.1558,-110.8777)
# Salt Lake City: (40.7774,-111.9301)
# TODO
input1=input('\nEnter lat1, lon1 separated by comma:').split(",")
input2=input('\nEnter lat2, lon2 separated by comma:').split(",")
if len(input1) ==1 and len(input2)==1:
print('\n input values should be separated by a comma')
else:
lat=[int(input1[0]),int(input2[0])]
lon=[int(input1[1]),int(input2[1])]
lat.sort()
lon.sort()
result=[f'{c.name}: ({c.latitude}, {c.longitude})' for c in cities if float(c.latitude) > lat[0] and float(c.latitude) < lat[1] and float(c.longitude) > lon[0] and float(c.longitude) < lon[1]]
for row in result:
print(row)
| true |
bf054145a75bac5cbc073d4d4e9f58a72a06cf1c | pavanghuge/Training | /BasicExercise1/six.py | 237 | 4.21875 | 4 | #Exercise 6: Given a list of numbers, Iterate it and print only those numbers which are divisible of 5
inputList = [10, 20, 33, 46, 55]
print("Divisible by 5 in a list")
for num in inputList:
if(num%5==0):
print(num)
| true |
2ad53a615af98e54fbc2a56da0ca7ed691cb88c9 | pavanghuge/Training | /taskFive.py | 2,341 | 4.21875 | 4 | #1. Write a program in Python to allow the error of syntax to be handled using
# exception handling.HINT: Use SyntaxError
try:
b = 10
print(b)
eval('a === 10')
except SyntaxError:
print("Caught syntax error")
print("You can only catch SyntaxError if it's thrown out of an eval, exec, or import operation.")
#2. Write a program in Python to allow the user to open a file by using the argv module.
# If the entered name is incorrect throw an exception and
# ask them to enter the name again. Make sureto use read only mode.
import sys
try:
filename = sys.argv[1]
f = open('filename','r')
print("File opened. Ready to write.")
f.close()
except IndexError:
print("Enter filename after program filename.")
except IOError:
print("File not found")
#3. Write a program to handle an error if the user entered a number more than four digits it should
# return “The length is too short/long !!! Please provide only four digits”
try :
input = int(input("Enter a four digit number: "))
if input < 1000 or input > 9999:
raise ValueError
except ValueError:
print("The length is too short/long !!! Please provide only four digits.")
#4.Create a login page backend to ask users to enter the username and password.
# Make sure toask for a Re-Type Password and if the password is incorrect give
# chance to enter it again but it should not be more than 3 times.
print("\nUser Authentication:")
userName = input("\nEnter username:")
pass_word = input("\nEnter password:")
try:
trials = 0
while (userName != "pavan" and pass_word != "ghuge" ):
print("\nUser Authentication:")
userName = input("\nEnter username:")
pass_word = input("\nEnter password:")
trials += 1
if trials == 2:
raise ValueError
break
except ValueError:
print("\nSorry you have exceeded 3 attempts to login.")
print("\nLogin Unsuccessful!!! ")
#6.Read doc.txt file using Python File handling concept and r
# eturn only the even length string from the file. Consider the content of doc.txt as given below:
import sys
fileName = open("doc.txt","r")
for line in fileName.readlines():
words = line.split(" ")
for word in words:
if len(word)%2 ==0:
print(word)
fileName.close()
| true |
0bc8367d52d1cb2d76b50b4493899ea23e49105a | Jager-Master/Calculator | /practice calculator.py | 978 | 4.25 | 4 | #Calculator App
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation from 1/2/3/4: ")
print
print("1. Addition")
print("2. Subtraction")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice (1/2/3/4): ")
if choice in("1", "2", "3", "4"):
num1 = float(input("Please enter first number: "))
num2 = float(input("Please enter second number: "))
if choice == "1":
print(num1, "+ ", num2, "= ", add(num1, num2))
elif choice == "2":
print(num1, "- ", num2, "= ", subtract(num1, num2))
elif choice == "3":
print(num1, "* ", num2, "= ", multiply(num1, num2))
elif choice == "4":
print(num1, "/ ", num2, "= ", divide(num1, num2))
break
else:
print("Input invalid")
| false |
32c5b2e324eb5f1b1084cf8547b6dff7aa683207 | RandomUser256/Coding-Basics | /Basics python/Programa2.py | 491 | 4.15625 | 4 | #Esto es un comentario
print("Este comando sirve para escribir un mensaje")
print("Este comando "+"Sirve para escribir "+"Un mensaje")
print("Este comando me permite agregar el numero ", 5)
print ("Puedo colocar el numero aqui ",5," y si quiero ",10," puedo poner la cantidad que quiera")
#Command Input
Nombre = input("Agrega nombre: ")
print ("El nombre registrado es ",Nombre)
print ("Buenos dias ",Nombre," espero que estes bien")
input("")
#Comando Print/Comando Input
| false |
2e9f12d27784c83c3de54c29bee6037a089d4263 | mlawan252/testrepo | /firstpython.py | 270 | 4.4375 | 4 | #Display the output
print("New python File")
# program that print out the factors of a given integer
number = int(input("Enter a positive integer "))
for i in range(1,number + 1):
if number % i == 0:
print(f"{i} is a factor of {number}")
| true |
f091fc940499f8393f3fa3fd3e4335285184216a | jdputsch/WPE | /J18_10/multiziperator.py | 999 | 4.28125 | 4 | #!/bin/env python
def multiziperator(*args):
"""Return elements of iterable inputs one at a time.
Args:
*args: One or more iterables
Yields:
Return elements of each input, interleaved, one at a time.
Example:
Given:
letters = 'abcde'
numbers = [1,2,3,4,5]
symbols = '!@#$%'
for one_item in multiziperator(letters, numbers, symbols):
print(one_item)
Returns:
a
1
!
etc.
"""
item_index = 0
while True:
for args_index in range(0, len(args)):
try:
yield args[args_index][item_index]
except IndexError:
raise StopIteration
item_index += 1
def main():
letters = 'abcde'
numbers = [1,2,3,4,5]
symbols = '!@#$%'
for one_item in multiziperator(letters, numbers, symbols):
print(one_item)
if __name__ == '__main__':
main() | true |
035dc42fcb766d9139c64aefe3bdd44fd43b3e50 | LuisTheDeveloper/Python-DataStructures | /HashTables/Hashtable1.py | 967 | 4.3125 | 4 | fruits = [
{'name' : 'apple', 'price' : 20},
{'name' : 'avocado', 'price' : 25},
{'name' : 'banana', 'price' : 22}
]
fruit_names = []
#for fruit in fruits:
# fruit_names.append(fruit['name'])
#print(fruit_names)
#for price in fruits:
# fruit_names.append(price['price'])
#print(fruit_names)
for fruit in fruits:
fruit_names.append(fruit['name'])
fruit_names.append(fruit['price'])
print(fruit_names)
meats = [
{'name' : 'cow', 'price' : 20},
{'name' : 'pork', 'price' : 25},
{'name' : 'chicken', 'price' : 22}
]
# printing the list with only print
print(
[meat['name'] for meat in meats]
)
# conditional printing
print(
[meat['name'] for meat in meats if meat['name'][1] == 'o']
)
fishes = [
{'name' : 'codfish', 'price' : 25},
{'name' : 'Salmon', 'price' : 35},
{'name' : 'haddock', 'price' : 15}
]
# alternative way using dictionary
print(
{fish['name']: fish['price'] for fish in fishes}
) | false |
ffbc2a77cd0d3ce5d482f2554add6603942e4527 | jlameiro87/cs50 | /mario-more.py | 739 | 4.1875 | 4 | from cs50 import get_int
# main function
def main():
# initialize height in 0 to emulates the do while
height = 0
# keep asking a valid height value to the customer until type something valid between 1 and 8
while height < 1 or height > 8:
height = get_int('Height: ')
# calling the printing line method per each line in the pyramid
for i in range(height):
print_line(height, i)
# print line function
def print_line(height, line_number):
# increase line_number in 1 because it start in 0
line_number += 1
spaces = height - line_number
# left side
left = ' ' * spaces + '#' * line_number
# rigth side
rigth = '#' * line_number
print(left + ' ' + rigth)
main()
| true |
02d24b2edb513dcd1ef7a7496518ec43dbbae1a4 | p-lots/codewars | /7-kyu/olympic-rings/python/solution.py | 499 | 4.15625 | 4 | def olympic_ring(string):
lookup_table = { 'A': 1, 'B': 2, 'D': 1,
'O': 1, 'P': 1, 'Q': 1, 'R': 1, 'a': 1, 'b': 1,
'd': 1, 'e': 1, 'g': 1, 'o': 1, 'p': 1, 'q': 1, }
ret = 0
for letter in string:
if letter in lookup_table:
ret += lookup_table[letter]
if ret // 2 > 3:
return 'Gold!'
elif ret // 2 == 3:
return 'Silver!'
elif ret // 2 == 2:
return 'Bronze!'
else:
return 'Not even a medal!' | false |
4bd2212d2a726b5b5501bf10626e19a0b6ca282b | sn-orla-x/Imperative-vs-OO-Calendar-Implementations | /imperative_calendar_app.py | 2,851 | 4.28125 | 4 | #dictionary was hard coded
appoints = {"Monday" : [],
"Tuesday": [],
"Wednesday": [],
"Thursday": [],
"Friday": [],
"Saturday": [],
"Sunday": []}
#prompty prompts the user to enter commands on their terminal and then runs the command that they enter
def prompty():
prompt = input("Enter a command: ")
if prompt == "close":
return
elif prompt == "add" :
add_appoint()
elif prompt == "delete":
delete_appoint()
elif prompt == "print day":
print_day()
elif prompt == "print week":
print_week()
else:
print("This command doesn't exist! Enter a new one")
prompty()
def add_appoint():
day = input("Please enter what day your appointment is on: ")
appoint_name = input("What is your appointment?: ")
start_time = float(input("Enter your start time: "))
end_time = float(input("Enter the time it ends at: "))
if overlap_checker(day, start_time, end_time):
appoints[day].append([appoint_name,start_time,end_time])
print("Your {} appointment on {} has been added to the calendar.".format(appoint_name, day))
else:
print("There is an overlap with your schedule, please check your calendar and try again!")
#print(appoints)
return
def delete_appoint():
day = input("What day is the appointment you wish to delete on?: ")
appoint_name = input("What is the appointment?:")
for appointment in appoints[day]:
if appointment[0] == appoint_name:
appoints[day].remove(appointment)
print("Your {} appointment on {} has been deleted from the calendar.".format(appoint_name,day))
print("There is no such appointment")
#print(appoints)
return
def print_day():
day = input("What day would you like to see?: ")
for appointment in appoints[day]:
print("On {}, at {:.2f} you have a {}. It finishes at {:.2f}.".format(day, appointment[1], appointment[0], appointment[2]))
return
def print_week():
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for day in weekdays:
print(day)
if appoints[day] == []:
print("Nothing scheduled for today!")
else:
for appointment in appoints[day]:
print("At {:.2f}, you have a {}. It finishes at {:.2f}".format(appointment[1], appointment[0], appointment[2]))
return
#checks to see if an appointment overlaps with another appointment
def overlap_checker(day, start_time, end_time):
for appointment in appoints[day]:
if appointment[1] < start_time < appointment[2]:
return False
elif appointment[1] < end_time < appointment[2]:
return False
return True
def main():
print("Welcome to your calendar! Please enter times using the 24 clock.\nYour options are: \nAdd an appointment using 'add' \nDelete an appoint using 'delete' \nView a specific day using 'print day' \nView the entire week using 'print week'\nClose the calendar using 'close'")
prompty()
if __name__ == '__main__':
main() | true |
2a467366c2a35b92dac656f78e0c3fcf1623738d | prpllrhd/python-project | /learn.class/classmethodExample1.py | 1,310 | 4.65625 | 5 | from datetime import date
'''
here we are using @classmethod to create instance using a different method. so here the age is not being passed but birthyear.
this is an example of alternate constructor. here you use "fromBirthYear(cls, name, birthYear):" to create an alternate constructor which is "def __init__(self,name,age)" and then all class methods can be used on this.
example issue:
person_str = "sameer:1974". what will you do?
basically you will convert the values so to be able to get name,age
i found this little confusing so the notes
'''
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromstring(cls,namestr):
name,birthyear = namestr.split(":")
return cls(name,date.today().year - int(birthyear))
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
print Person.__dict__
person = Person('Adam', 19)
print person.__dict__
person.display()
person1 = Person.fromBirthYear('John',1985)
print person1.__dict__
person1.display()
newperson = "sameer:1974"
person3 = Person.fromstring(newperson)
print person3.__dict__
person3.display()
| true |
2b6560589b03a3a642f2233ad45ea4fc6717da89 | lindsaymarkward/cp1404_inclass_demos_2021_2 | /encrypt_solutions.py | 1,903 | 4.15625 | 4 | """Shift encrypt names/strings from text file
Let string A be the first 6 characters of your last-name
(if your last-name is less than 6 characters,
repeat the last letter until you get a six-character string).
(a) Encrypt string A using ROT3 cipher in the English alphabet.
(b) Encrypt string A using One-Time-Pad cipher,
where the key is 'SECRET'.
"""
from string import ascii_lowercase
NAME_LENGTH = 6
SHIFT_DISTANCE = 3
INPUT_FILENAME = "cp3404_names.txt"
OUTPUT_FILENAME = "cp3404_cryptograms.txt"
def main():
"""Get names and encrypt them."""
names = get_names(INPUT_FILENAME)
name_to_cryptogram = encrypt_names(names)
save_results(name_to_cryptogram, OUTPUT_FILENAME)
def encrypt_names(names):
name_to_cryptogram = {}
for name in names:
cryptogram = encrypt_name(name, SHIFT_DISTANCE)
name_to_cryptogram[name] = cryptogram
return name_to_cryptogram
def get_names(filename):
"""Retrieve and process names from text file using minimum length and repeated characters to fill."""
names = []
with open(filename) as input_file:
lines = input_file.readlines()
for line in lines:
name = line.strip().lower().replace(' ', '').replace('-', '') # ward
names.append(f"{name[:6]:{name[-1]}<6}") # warddd
return names
def encrypt_name(name, distance):
"""Use shift to encrypt one name."""
cryptogram = ""
number_of_letters_in_alphabet = len(ascii_lowercase)
for letter in name:
index = ascii_lowercase.index(letter)
new_index = (index + distance) % number_of_letters_in_alphabet
cryptogram += ascii_lowercase[new_index]
return cryptogram
def save_results(name_to_cryptogram, filename):
with open(filename, 'w') as output_file:
for name, cryptogram in name_to_cryptogram.items():
print(f"{name} => {cryptogram}", file=output_file)
main()
| true |
be9ab0dfbbe8f756e0759651f3267c69d938a6a7 | gautamsood15/top_questions | /palindrom.py | 287 | 4.125 | 4 | #O(N)
def is_palindrom(str):
original_str = str
reversed_str = str[::-1]
if original_str == reversed_str:
return True
return False
def is_palindrom_python(str):
return str == ''.join(str[::-1])
if __name__ == "__main__":
str = 'radar'
print(is_palindrom_python(str))
| false |
bd72699a3b5fe0f00cb3a5d9a99a92a3169f999e | alarconm/web-caesar | /caesar.py | 646 | 4.21875 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
'''take a message and rotate each character by the integer rot via helper function'''
newtext = ''
for char in text:
newtext += rotate_character(char, rot)
return newtext
def main():
'''get message and rotation amount to encrypt from user'''
from sys import argv, exit
if not argv[1].isdigit():
print("Sorry, you did not enter an integer to rotate, try again.")
exit()
message = input("Type a message:")
print(message)
print(encrypt(message, int(argv[1])))
if __name__ == "__main__":
main()
| true |
4208fc76fb272d48216e279fb55f64664e3d20a1 | migliom/Computer-Network-Security-Encryption-Algorithms- | /HW03/mult_inv.py | 2,673 | 4.21875 | 4 | #HW03 Coding Problem
#Matteo Miglio
#miglio@purdue.edu
#02/11/2021
#!/usr/bin/env python3
#mult_iv.py
import sys
'''This function was derived through the help of the following youtube video, the implementation is unique to this specific program'''
'''https://www.youtube.com/watch?v=w3m3xdw1E-Q&ab_channel=CPlus%2B'''
def multiply(x, y):
negOrPos = False
if ((x < 0) ^ (y < 0)):
x, y = abs(x), abs(y)
negOrPos = True
sum = 0
while(x > 0):
if (x & 1):
sum = sum + y
y = y << 1
x = x >> 1
if negOrPos:
return 0-sum
else:
return sum
'''This function is derived from the description given in stack overflow but the implementation is my unique interpretation'''
'''https://stackoverflow.com/questions/5284898/implement-division-with-bit-wise-operator?answertab=active#tab-top'''
def divide(numerator, denominator):
negOrPos = False
quotient = 1
if numerator == denominator:
return 1
#if the same return 1
if ((numerator < 0) ^ (denominator < 0)):
numerator, denominator = abs(numerator), abs(denominator)
negOrPos = True
#if either of the two arguments are negative then create a true boolean, but only if one is negative HENCE XOR
if numerator < denominator and numerator > 0:
return 0
count = -1
while denominator <= numerator:
count = count + 1
denominator = denominator << 1
denominator = denominator >> 1
#must run through the loop n+1 times where n is the number of shifts of the original denominator to line up the most significant 1
for i in range(count+1):
total = numerator - denominator
if total >= 0:
quotient = quotient | 1
numerator = total
numerator = numerator << 1
quotient = quotient << 1
#MUST RIGHT SHIFT TO ACCOUNT FOR PREVIOUS LEFT SHIFT
quotient = quotient >> 1
#IF NEG THEN RETUR 0-QUOT
if negOrPos:
return 0-quotient
return quotient
if len(sys.argv) != 3:
sys.stderr.write("Usage: %s <integer> <modulus>\n" % sys.argv[0])
sys.exit(1)
NUM, MOD = int(sys.argv[1]), int(sys.argv[2])
def inv_MI(num, mod):
NUM = num; MOD = mod
x, x_old = 0, 1
y, y_old = 1, 0
while mod:
q = divide(num, mod)
num, mod = mod, num % mod
x, x_old = x_old - multiply(q, x), x
y, y_old = y_old - multiply(q, y), y
if num != 1:
print("\nNO MI. However, the GCD of %d and %d is %u\n" % (NUM, MOD, num))
else:
MI = (x_old + MOD) % MOD
print("\nMI of %d modulo %d is: %d\n" % (NUM, MOD, MI))
inv_MI(NUM, MOD)
| true |
2bdae899f97a3de98c2c7328302718d5eeb2ee42 | SenorNoName/projectEuler | /euler4.py | 727 | 4.125 | 4 | '''
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
num1 = 100
num2 = 100
productArr = []
palindromeArr = []
def palindromeCheck(int):
int = str(int)
rev = ''.join(reversed(int))
if int == rev:
return True
return False
while num1 < 1000 and num2 < 1000:
for i in range(900):
num1 = 100
for num in range(900):
productArr.append(num1 * num2)
num1 += 1
num2 += 1
for i in productArr:
if palindromeCheck(i) == True:
palindromeArr.append(int(i))
print(max(palindromeArr))
| true |
396b42f35d0b83ea203229225e07e0bfadae1117 | aqshmodel/git_practice3 | /circle.py | 675 | 4.34375 | 4 | '''
課題1
動くようにクラスを設計
円の面積を計算するメソッド.areaが必要
円の円周長を計算するメソッド.perimeterが必要
'''
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return round((self.radius ** 2) * math.pi, 2)
def perimeter(self):
return round(self.radius * 2 * math.pi, 2)
# 半径1の円
circle1 = Circle(radius=1)
print('半径1の円')
print(circle1.area()) # 3.14
print(circle1.perimeter()) # 6.28
# 半径3の円
circle1 = Circle(radius=3)
print('半径3の円')
print(circle1.area()) # 28.26
print(circle1.perimeter()) # 18.85
| false |
7ea9dea9d4ddde7e248f60e9b437c7c694da8701 | Baaska21/python-hw | /hw1/hw3.py | 318 | 4.1875 | 4 | def is_power_of_two(n):
if n < 0:
return False
while n > 2:
if n % 2 == 0:
n = n / 2
if n == 2:
return True
else:
return False
if __name__ == '__main__':
n = int(input('Введите число: '))
print(is_power_of_two(n)) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.