blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b8c5889cb62a380ff06a0f05663577ab4f2bf2a7 | arnabs542/Leetcode-3 | /Solutions/1344.Angle-Between-Hands-of-a-Clock.py | 807 | 4.125 | 4 | """
1344. Angle Between Hands of a Clock
Given two numbers, hour and minutes.
Return the smaller angle (in degrees) formed between the hour and the minute hand.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:
Input: hour = 3, minutes = 15
Output: 7.5
Example 4:
Input: hour = 4, minutes = 50
Output: 155
"""
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_ratio = 360 / 12
min_ratio = 360 / 60
min_angle = min_ratio * minutes
hour %= 12
hour_angle = hour_ratio * hour + 360 / 60 / 12 * minutes
angle = abs(hour_angle - min_angle)
angle = min(angle, abs(360 - hour_angle + min_angle), abs(360 + hour_angle - min_angle))
return angle
| true |
9b85f543deb9d8999c7e38d21afe2b5fdbdbb452 | MorozN/Programming-Basics | /homeworks/Valik.Pavlenko_ValikPavlenko/Homeworks-1/hello wort.py | 620 | 4.125 | 4 | name = input("What you name? ")
last_name = input("What is your last name? ")
age = int(input("How old are you? "))
country =input("Where do you live (country)? ")
city = input("Where do you live(city)? ")
birth = input("Enter your date of birth(date/month/year)? ")
print("Your name and last mane is %s %s,your birthday %s, your age is %s "
"and you live in %s %s. Good!" % (name, last_name, birth, age, country, city))
result = 'name - %s, last_name - %s, age - %s, country-%s, city - %s, birth- %s .'%(name, last_name, age, country, city, birth)
file = open('info.txt', 'w')
file.write(result)
file.close()
| true |
7946385e5993296cdd2ea683983f779748414059 | agengsusila/pythonfrommosh | /part 3 type conversion.py | 332 | 4.125 | 4 | # MATERIAL LESSON
# int function is for convert a string value from birth year variab to int value
birth_year = input("Birth Year: ")
age = 2021 - int(birth_year)
print(age)
# QUIZ
print("Convert Pounds to Kilograms")
weight_pounds = input("Your weight in pounds: ")
weight_kg = int(weight_pounds) * 0.45
print(weight_kg, " kg")
| true |
54142ce7f76dcdcda254ab27086ef735fc2874ee | agengsusila/pythonfrommosh | /part 12 comparison operators..py | 401 | 4.4375 | 4 | temperature = 22
if temperature >= 30:
print("It's a hot day")
elif temperature <= 10:
print("It's a cold day")
else:
print("It's neither hot nor cold")
# EXERCISE
name = input("Enter your name: ")
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 50:
print("Name can be a maximum of 50 characters")
else:
print("Name looks good")
| true |
44bf5da2ed4635d4bbed415c2a63182bef97c445 | AvramPop/Fundamentals-Of-Programming | /HW4/src/Date.py | 1,868 | 4.25 | 4 | from datetime import date
from src.Exception import InvalidDateFormatException
class Date:
"""
Models date having day (0 < int < 31), month (0 < int < 13), year(int > 0)
"""
def __init__(self, day, month, year) -> None:
if type(day) == int:
if 0 < day < 31:
self.day = day
else:
raise InvalidDateFormatException
else:
raise InvalidDateFormatException
if type(month) == int:
if 0 < month < 13:
self.month = month
else:
raise InvalidDateFormatException
else:
raise InvalidDateFormatException
if type(year) == int:
if 0 < year:
self.year = year
else:
raise InvalidDateFormatException
else:
raise InvalidDateFormatException
def __eq__(self, other: "Date"):
return self.day == other.day and self.month == other.month and self.year == other.year
def isBeforeDate(self, dateUntil):
"""
Checks whether self is before date
:param dateUntil: the date to compare to
:return: True if self is before date, False otherwise
"""
if self.year < dateUntil.year or (self.year == dateUntil.year and self.month < dateUntil.month) or (self.year == dateUntil.year and self.month == dateUntil.month and self.day < dateUntil.day):
return True
else:
return False
def daysUntilDate(self, dateUntil: "Date"):
d1 = date(self.year, self.month, self.day)
d2 = date(dateUntil.year, dateUntil.month, dateUntil.day)
delta = d1 - d2
return abs(delta.days)
def __str__(self) -> str:
return "Date day: " + str(self.day) + ", month: " + str(self.month) + ", year: " + str(self.year)
| false |
9ce3b0cd178b9ff7fbc728fb6365c1626943be21 | jackdbd/concurrent-programming-python | /shared_data_with_processes.py | 1,819 | 4.5625 | 5 | """Example of a shared variable between processes.
Processes do not share the same memory space, so we need special techniques to define shared data and share state across processes.
When doing concurrent programming it is usually best to avoid using shared state as far as possible.
This is particularly true when using multiple processes.
However, if you really do need to use some shared data then `multiprocessing` provides a couple of ways of doing so.
Data can be stored in a shared memory map using `Value` or `Array`.
Usage:
$ python shared_data_with_processes.py
See Also:
shared_data_with_threads.py
"""
import argparse
from argparse import RawDescriptionHelpFormatter
from multiprocessing import Process, Array
def target(number, arr):
print(f"Appending {number}")
# multiprocessing.Array does not have an append method, so we have to use this
# syntax (in fact the Array has already 10 elements, so we just have to assign them here)
arr[number] = number
def parse_args():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=RawDescriptionHelpFormatter
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
shared_variable = Array(typecode_or_type="i", size_or_initializer=10)
processes = []
for i in range(10):
process_name = f"Subprocess-{i}"
proc = Process(target=target, args=(i, shared_variable), name=process_name)
processes.append(proc)
print(f"State of the shared variable BEFORE processing:")
for item in shared_variable:
print(item)
for proc in processes:
proc.start()
for proc in processes:
proc.join()
print(f"State of the shared variable AFTER processing:")
for item in shared_variable:
print(item)
| true |
2b56e6fc6d4350fadbb7675933c104dc046086c0 | fennieliang/week5 | /lesson_0312_tkGeo.py | 1,708 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 27 16:33:46 2021
@author: fennieliang
"""
import tkinter as tk
# creating the tkinter window
window = tk.Tk() #instantiate an gui window
window.title('Python class window')#give the window a title
#window.geometry("300x300") #give the window a size
# set window width and height
mywidth = 300
myheight = 300
# get screen height and width
scrwdth = window.winfo_screenwidth()
scrhgt = window.winfo_screenheight()
# write formula for center screen
xLeft = int((scrwdth/2) - (mywidth/2))
yTop = int((scrhgt/2) - (myheight/2))
# centred the window in any size of the screen
window.geometry(str(mywidth) + "x" + str(myheight) + "+" + str(xLeft) + "+" + str(yTop))
'''
practice
1. write a method called centre_math to a class named Tkinter_GUI
that allows users to provide the width and height,
and position the window at the centre of the users' screens
2. do a call to check the class performs right
0304 allow the user to input width and height for the tkinter window
'''
# variable
my_text = "system updated !!!"
# function define for
# updating the my_label
# widget content
def counter():#change the name to see what happens
# use global variable
global my_text
# configure
my_label.config(text = my_text)
# create a button widget and attached
# with counter function
my_button = tk.Button(window,
text = "click to update",
command = counter)
# create a Label widget
my_label = tk.Label(window,
text = "update system")
# place the widgets
# in the gui window
my_label.pack()
my_button.pack()
# Start the GUI
window.mainloop()
| true |
49ccc92c225eb93a8ed4929ccb7d911b986768c4 | AirmanKolberg/Cylinder-Gallons-Feet-Calculator | /main.py | 2,308 | 4.125 | 4 | from math import pi, sqrt
from time import sleep
from system_functions import clear_screen, get_float_value_from_user
# feet, feet; returns gallons
def get_cylinder_volume(height, diameter):
volume = (pi * (diameter**2) * height) / 4
volume *= 7.4805 # Convert to gallons
return volume
# gallons, feet; returns feet
def get_cylinder_height(volume, diameter):
volume /= 7.4805 # Convert from gallons
if diameter != 0:
height = (4 * volume) / (pi * (diameter**2))
return height
return 'diameter cannot be 0'
# gallons, feet; returns feet
def get_cylinder_diameter(volume, height):
volume /= 7.4805 # Convert from gallons
if height != 0:
diameter = (2 * sqrt(volume) * sqrt(pi * height)) / (pi * height)
return diameter
return 'height cannot be 0'
def main_menu():
print("""Welcome to the cylinder gallon calculator!
Select what aspect of the cylinder you're trying to find:
volume (v)
height (h)
diameter (d)
""")
selection = input('> ')
if selection == 'volume' or selection == 'v':
height = get_float_value_from_user('Height in feet: ')
diameter = get_float_value_from_user('Diameter in feet: ')
volume = get_cylinder_volume(height, diameter)
print(f'The volume of a cylinder with a height of {height}ft and diameter of {diameter}ft is:\n{volume} gallons')
elif selection == 'height' or selection == 'h':
volume = get_float_value_from_user('Volume in gallons: ')
diameter = get_float_value_from_user('Diameter in feet: ')
height = get_cylinder_height(volume, diameter)
print(f'The height of a cylinder with a volume of {volume}gal and diameter of {diameter}ft is:\n{height} feet')
elif selection == 'diameter' or selection == 'd':
volume = get_float_value_from_user('Volume in gallons: ')
height = get_float_value_from_user('Height in feet: ')
diameter = get_cylinder_diameter(volume, height)
print(f'The diameter of a cylinder with a volume of {volume}gal and height of {height}ft is:\n{diameter} feet')
else:
print(f'{selection} is not valid, please try again.\n')
sleep(1)
main_menu()
if __name__ == '__main__':
clear_screen()
main_menu()
| true |
00198e3afc761ba5729b6107e448641e496d3723 | JeremyBrightbill/coding_exercises | /Exercise_11.py | 2,508 | 4.125 | 4 | """Program to perform currency conversions.
Constraints: Ensure that fractions of a cent are rounded up to
the next penny.
My innovations:
* Get exchange rates from Open Exchange API
* Use command line arguments instead of prompts
* Allow conversion between any currencies with the following input:
$ python Exercise_11.py 10 USD EUR # converts 10 USD to EUR
* Validate inputs using argparse"""
import argparse
import os
import requests
import sys
from dotenv import load_dotenv
from utilities_ import to_usd, from_usd, round_up
load_dotenv() # Contains APP_ID as environment variable from .env file
API_BASE: str = 'https://openexchangerates.org/api/'
APP_ID: str = os.environ['APP_ID']
class Converter():
def __init__(self) -> None:
self.rates: dict = self.get_rates_all()
self.currencies = list(self.rates.keys()) # For printing in validation error message
def get_rates_all(self) -> dict:
endpoint: str = f'{API_BASE}latest.json?app_id={APP_ID}'
response = requests.get(endpoint)
return response.json()['rates']
def validate_input(self) -> None:
parser = argparse.ArgumentParser()
parser.add_argument("amount", help="amount", type=float)
parser.add_argument("currency_from", help="currency to convert from", type=str)
parser.add_argument("currency_to", help="currency to convert to", type=str)
args = parser.parse_args()
if not (args.currency_from in self.rates and args.currency_to in self.rates):
parser.error(f"Currency not recognized. Choose from the following:\n {self.currencies}")
inputs = vars(args)
self.amount, self.currency_from, self.currency_to = inputs.values()
def convert_currency(self) -> float:
if self.currency_from == 'USD':
rate = self.rates[self.currency_to]
self.output = from_usd(self.amount, rate)
if self.currency_to == 'USD':
rate = self.rates[self.currency_from]
self.output = to_usd(self.amount, rate)
else:
rate1, rate2 = self.rates[self.currency_from], self.rates[self.currency_to]
amount_usd = to_usd(self.amount, rate1)
self.output = from_usd(amount_usd, rate2)
return format(round_up(self.output, 2), '.2f') # Fill out zeros if needed
if __name__ == '__main__':
converter = Converter()
converter.validate_input()
output = converter.convert_currency()
print(output)
| true |
88a911a1f8e3762c8140b32fb2010866b43fce24 | shown440/desktop_book_store_tkinter | /backend.py | 2,403 | 4.65625 | 5 | import sqlite3
#import sqlite3 for work with Database and SQLite3 is built in Library of Python
#work with database in Python has 5 steps:
# 1. Connect to a database
# 2. Create a Cursor object
# 3. Write an SQL Query AND execute query in cursor
# 4. Commit changes
# 5. Close your Database Connection
#Create Database
def connect_Bookdb():
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
conn.commit()
conn.close()
#Add Book to the Database
def add_Bookdb(title, author, year, isbn):
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("INSERT INTO book VALUES(NULL,?,?,?,?)",(title, author, year, isbn))
conn.commit()
conn.close()
#View all books from Database
def viewall_Bookdb():
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("SELECT * FROM book")
# Dont use commit for view data from Database
# Use "cur.fetchall()" in place of "conn.commit()" to Fetch data from Database
rows = cur.fetchall()
conn.close()
return rows
#Search any book from Database
def search_Bookdb(title="", author="", year="", isbn=""):
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn))
# Dont use commit for view data from Database
# Use "cur.fetchall()" in place of "conn.commit()" to Fetch data from Database
rows = cur.fetchall()
conn.close()
return rows
#Delete any Book from Database
def delete_Bookdb(id):
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("DELETE FROM book where id=?",(id,))
conn.commit()
conn.close()
#Update any Book details in Database
def update_Bookdb(id, title, author, year, isbn):
conn = sqlite3.connect("book.db")
cur = conn.cursor()
cur.execute("UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?", (title, author, year, isbn, id))
conn.commit()
conn.close()
#connect_Bookdb()
#add_Bookdb("JavaSE Programming", "Herbert Shield", 2010, 1996552654641)
#update_Bookdb(4, "Java ProgrammingII", "Herbert Shield", 2010, 1996552654641)
#delete_Bookdb(4)
#print(search_Bookdb(title="", author="Subin Haider", year="", isbn=""))
#print(viewall_Bookdb())
| true |
b564dd07e3d00cb90cba8111877385d4b6a27e06 | OtherU/Python_Cursos_online | /desafio_018.py | 651 | 4.125 | 4 | # ------ Modules ------ #
from math import radians, sin, cos, tan
# ------ Header & Footers ------ #
header = (' Desafio 018 ')
subfooter = ('-'*68)
footer = ('='*68)
# ------ Header ------ #
print('{:=^68}'.format(header))
# ------ Body ------ #
ang = float((input('Digite o grau de um agulo: ')))
print()
sena = float(sin(radians(ang)))
cosa = float(cos(radians(ang)))
tana = float(tan(radians(ang)))
print('O seno do angulo {}° = {:.2f}°'.format(ang, sena))
print('O coseno do angulo {}° = {:.2f}°'.format(ang, cosa))
print('A tangente do angulo {}° = {:.2f}°'.format(ang, tana))
# ------ Footers ------ #
print(subfooter)
print(footer)
| false |
0c4a0a35132215ef7fbd7a79d7ab80fb0ddd687c | goutkannan/HackerRank | /Data Structure and Algorithms/manasa-and-stones.py | 2,037 | 4.1875 | 4 | """
Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that two consecutive stones have a difference of either or . Legend has it that there is a treasure trove at the end of the trail and if Manasa can guess the value of the last stone, the treasure would be hers. Given that the number on the first stone was , find all the possible values for the number on the last stone.
Note: The numbers on the stones are in increasing order.
Input Format
The first line contains an integer , i.e. the number of test cases. test cases follow; each has 3 lines. The first line contains (the number of stones). The second line contains , and the third line contains .
Constraints
Output Format
Space-separated list of numbers which are the possible values of the last stone in increasing order.
Sample Input
2
3
1
2
4
10
100
Sample Output
2 3 4
30 120 210 300
Explanation
All possible series for the first test case are given below:
0,1,2
0,1,3
0,2,3
0,2,4
Hence the answer 2 3 4.
Series with different number of final steps for second test case are the following:
0, 10, 20, 30
0, 10, 20, 120
0, 10, 110, 120
0, 10, 110, 210
0, 100, 110, 120
0, 100, 110, 210
0, 100, 200, 210
0, 100, 200, 300
Hence the answer 30 120 210 300
"""
def Manasa():
"""
Implementation based on the logic that addition is commutative (i.e) a + b + a = a + a + b and b + b + a = a + b + b
Hence for a given N the possible sums of a,b is sorted set of
(n-1)a + 0b
(n-2)a + 1b
(n-3)a + 2b
....
....
END = Nth time.
"""
T = int(input())
while T:
result_set = set()
n = int(input())
a = int(input())
b = int(input())
for i in range(n):
val = (n-i-1) * a + i * b
result_set.add(val)
# Print the sorted set
for value in sorted(result_set):
print(value, end=" ")
print()
T -= 1
if __name__ == '__main__':
Manasa()
| true |
157997d44ad86af8461c3c6c105788db9ef076cd | nguyenthanhvu240/DataAnalyst | /DA-With-W3school-Course/Matplotlib/subPlot.py | 1,066 | 4.28125 | 4 | import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0,1,2,3])
y = np.array([3,8,1,10])
plt.subplot(2,1,1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.plot(x,y,marker='o',mfc='red')
plt.grid(axis='y')
plt.ylabel('NAM')
#plot 2:
x = np.array([0,1,2,3])
y = np.array([10,20,30,40])
plt.subplot(2,1,2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
plt.plot(x,y)
plt.grid(axis='y')
plt.ylabel('NỮ')
#So, if we want a figure with 2 rows an 1 column (meaning that the two plots will be displayed on top of each other instead of side-by-side), we can write the syntax like this:
plt.suptitle('Gioi Tinh')
plt.show()
#==================================================
x1 = np.array([0,1,2,3])
y1 = np.array([3,8,1,10])
plt.subplot(1,2,1)
plt.plot(x1,y1,marker='o',mfc='red',ms=10,color='black')
plt.title('NAM')
plt.grid(axis='y')
x2 = np.array([0,1,2,3])
y2 = np.array([10,20,30,40])
plt.subplot(1,2,2)
plt.plot(x2,y2)
plt.title('NU')
plt.grid(axis='y')
plt.suptitle('GIOITINH')
plt.show()
| true |
51dbd250c943865413b45c0ee32a1b7d11adb5d8 | saikiran009/DS-Algorithms-HackerRank | /Arrays_Left_Rotation.py | 1,226 | 4.3125 | 4 | '''
A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
Input Format
The first line contains two space-separated integers denoting the respective values of (the number of integers) and (the number of left rotations you must perform).
The second line contains space-separated integers describing the respective elements of the array's initial state.
for more details: https://www.hackerrank.com/challenges/ctci-array-left-rotation
'''
count = 0
def array_left_rotation(a, n, k):
shift_1 = abs(n-k)
b = a[:] #So that when u perform changes on b list a list is not effected
for m in xrange(n):
if ((n-1)-(m)) >= shift_1:
b[m +shift_1] = a[m]
else:
b[(shift_1-((n-1)-(m))-1)] = a[m]
return b
n, k = map(int, raw_input().strip().split(' '))
a = map(int, raw_input().strip().split(' '))
answer = array_left_rotation(a, n, k);
print ' '.join(map(str,answer)) | true |
cab970fc3f828e11533daa2d4dc19108ae5b9e62 | Sujan0rijal/LabOne | /two.py | 471 | 4.53125 | 5 | '6. Solve each of the following problems using Python Scripts. Make sure you use appropriate variable names and comments.'
'When there is a final answer have Python print it to the screen.'
'A person’s body mass index (BMI) is defined as:'
'BMI=mass in kg / (height in m)2.'
mass_man=float(input('enter the mass of man:'))
height_man=float(input('enter the height of man:'))
BMI= mass_man / ( height_man*height_man)
print(f'A person`s body mass index (BMI) is {BMI}') | true |
e6ee3652a054328f44c6c1b4dc352415ef1a792f | Sujan0rijal/LabOne | /LabTwo/four.py | 452 | 4.34375 | 4 | '''4. Given three integers, print the smallest one. (Three integers should be user input)'''
integer1=int(input('enter first number:'))
integer2=int(input('enter second number:'))
integer3=int(input('enter third number:'))
if integer1<integer3 and integer1<integer2:
print(f'smallest number is {integer1}')
elif integer2<integer3 and integer2<integer1:
print(f'smallest number is {integer2}')
else:
print(f'smallest number is {integer3}') | true |
14fba71e74f39b77631a4480bc3b054254af2510 | vikash-verma-profile/hadoop-samples | /Part-6.py | 268 | 4.15625 | 4 | """a=[1,2,3,1,2]
a.append(1);
for item in a:
print(item)"""
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
"""
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
"""
| false |
29f824360fa98f663794036fe455264912d57930 | JieLIU-cn/untitled | /quick_sort.py | 928 | 4.21875 | 4 | def quick_sort(sequence):
def recursive(begin, end):
if begin > end:
return
left, right = begin, end
pivot = sequence[left]
while left < right:
while left < right and sequence[right] > pivot: # 因为是以left作为pivot,因此要把right侧分析放到前面,这样才能left = right = 比pivot小的值
right -= 1
while left < right and sequence[left] <= pivot:
left += 1
sequence[left], sequence[right] = sequence[right], sequence[left]
sequence[left], sequence[begin] = pivot, sequence[left] # 将pivot放到中间位置,之前对于left的方法,pivot一直处于begin的位置
recursive(begin, left-1)
recursive(right+1, end)
recursive(0, len(sequence)-1)
return sequence
if __name__ == '__main__':
sequence = [3,5,2,6,8,2]
print(quick_sort(sequence))
| false |
c6d1bc9f5b0fcb67b72519ac9eefb2a19786bcd3 | SantiRosas99/Condicionales | /Clase 3/condicionales_python-master/ejercicios_practica/ejercicio_1.py | 1,666 | 4.53125 | 5 | # Condicionales [Python]
# Ejercicios de práctica
# Autor: Inove Coding School
# Version: 2.0
# IMPORTANTE: NO borrar los comentarios
# que aparecen en verde con el hashtag "#"
# Ejercicios de práctica numérica
# Comparadores
# Ingrese dos números cualesquiera y realice las sigueintes
# comparaciones entre ellos
numero_1 = int(input('Ingrese el primer número:\n'))
numero_2 = int(input('Ingrese el segundo número:\n'))
# Compare cual de los dos números es mayor
# Imprima en pantalla según corresponda
if numero_1 > numero_2:
print('El primer número {} ingresado es mayor que el segundo número {}'.format(numero_1, numero_2))
else:
print('El segundo numero {} ingresado es menor que el segundo número {}'.format(numero_1, numero_2))
# Verifique si el numero_1 positivo, negativo o cero
# Imprima el resultado en cada caso
if numero_1 > 0:
print('El primer número {} es mayor a 0'.format(numero_1))
elif numero_1 == 0:
print('El número ingresado {} es igual a 0'.format(numero_1))
else:
print('El número ingresado {} es negativo'.format(numero_1))
# Verifique si el numero_1 es mayor a 0 y menor a 100
# Imprima en pantalla si se cumple o no la condición
if numero_1 > 0 and numero_1 < 100:
print('El número ingresado {} es mayor que 0 y menor a 100'.format(numero_1))
else:
print("El número ingresado {} no es mayor que 0 y menor a 100".format(numero_1))
# Verifique si el numero_1 es menor a 10 o el numero_2 es mayor a -2
# Imprima en pantalla si se cumple o no la condición
if numero_1 < 10 or numero_2 > -2:
print('Cumple la condición')
else:
print("No cumple la condición") | false |
c35a6d4abe51581b618465e4d6d72523dbdadf06 | humafarheen/learning_python | /Exercises/fourth.py | 572 | 4.125 | 4 | #!/usr/bin/env python3
#Binary search on a list
def binary_search(l,item):
start = 0
end = len(l) - 1
while(start <= end):
mid = (start + end) // 2
if(l[mid] == item):
return mid
elif(l[mid] > item):
end = mid - 1
else:
start = mid + 1
return -1
print("Enter a list")
l = [x for x in input().split()]
l = sorted(l)
print("Enter item to be searched:")
item = input()
found = binary_search(l,item)
if(found >= 0):
print("The item found at index",found)
else:
print("Item not found!!!")
| true |
595692066c8eb2950ea0399ddf6029c963ac5c39 | autobeaver/DSAA_Item_Bank | /BtreeTraversal.py | 1,860 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#二叉树遍历
from binarytree import tree
my_tree = tree(height=3, is_perfect=False)
print(my_tree)
root_value = my_tree.value
root_left = my_tree.left
#1. 先序遍历(根、左、右)
def preorder(my_tree):
print(my_tree.value)
if my_tree.left is not None:
preorder(my_tree.left)
if my_tree.right is not None:
preorder(my_tree.right)
if __name__ == "__main__":
print("preorder")
preorder(my_tree)
#1.2 先序遍历非递归(使用栈)
from queue import LifoQueue
def preorder_stack(my_tree):
s = LifoQueue()
t = my_tree
while t is not None or not s.empty():
while t is not None:
print(t.value)
s.put(t.right)
t = t.left
t = s.get()
if __name__ == "__main__":
print("preorder_stack")
preorder_stack(my_tree)
#2. 后序遍历(左、右、根)
def postorder(my_tree):
if my_tree.left is not None:
preorder(my_tree.left)
if my_tree.right is not None:
preorder(my_tree.right)
print(my_tree.value)
if __name__ == "__main__":
print("postorder")
postorder(my_tree)
#3. 中序遍历(左、根、右)
def middleorder(my_tree):
if my_tree.left is not None:
preorder(my_tree.left)
print(my_tree.value)
if my_tree.right is not None:
preorder(my_tree.right)
if __name__ == "__main__":
print("middleorder")
middleorder(my_tree)
#4. 广度优先遍历
from queue import Queue
q = Queue()
def breadthfirst(my_tree):
q.put(my_tree)
while not q.empty():
p = q.get()
print(p.value)
if p.left is not None:
q.put(p.left)
if p.right is not None:
q.put(p.right)
if __name__ == "__main__":
print("breadthfirst")
breadthfirst(my_tree) | false |
69d6adb2e3a8537c87f16b718b53561131d71c8b | nkiapy/python-tutorial | /examples/13_class.py | 2,766 | 4.125 | 4 | # coding=UTF-8
"""
class 클래스이름[(상속 클래스명)]:
<클래스 변수 1>
<클래스 변수 2>
...
def 클래스함수1(self[, 인수1, 인수2,,,]):
<수행할 문장 1>
<수행할 문장 2>
...
def 클래스함수2(self[, 인수1, 인수2,,,]):
<수행할 문장1>
<수행할 문장2>
...
...
"""
# 클래스
class DuckHunting:
ducks = 3 # 클래스 변수
def __init__(self, power):
self.power = power
print ("Dog's power is %d" % self.power)
def hunting(self):
print ("Catch!")
self.ducks -= 1
if self.ducks < 0:
self.ducks = 0
def checkDucks(self):
if self.ducks <= 0:
print ("Good Dog!")
else:
print (str(self.ducks) + " Ducks left")
dog1 = DuckHunting(1)
dog1.hunting()
dog1.checkDucks()
print (DuckHunting.ducks)
dog2 = DuckHunting(15)
dog2.checkDucks()
import sys
print (sys.version)
# 상속(Inheritance)
print ('')
print ('='*5 + '상속(Inheritance)')
class Parent():
def print_last_name(self):
print ("KingKong")
class Child(Parent):
def print_first_name(self):
print ("Amy")
# overriding
def print_last_name(self):
print ("Monkey")
amy = Child()
amy.print_first_name()
amy.print_last_name()
# 다중상속(Multiple Inheritance)
print ('')
print ('='*5 + '다중상속(Multiple Inheritance)')
class Amy():
def print_last_name(self):
print ("Monkey")
class Lex():
def print_first_name(self):
print ("Lex")
class AmyLex(Amy, Lex):
pass
amyLex = AmyLex()
amyLex.print_first_name()
amyLex.print_last_name()
# __add__, __sub__(+,- 연산자)
print ('')
print ('='*5 + '+,- 연산자')
class HousePark:
lastname = "박"
def __init__(self, name):
self.fullname = self.lastname + name
def travel(self, where):
print("%s, %s여행을 가다." % (self.fullname, where))
def __add__(self, other):
print("%s, %s 결혼했네" % (self.fullname, other.fullname))
def __sub__(self, other):
print("%s, %s 헤어졌네" % (self.fullname, other.fullname))
class HouseKim(HousePark):
lastname = "김"
def travel(self, where):
print("%s은 %s로 여행합니다." % (self.fullname, where))
pey = HousePark("응용")
juliet = HouseKim("줄리엣")
pey + juliet # + 연산자를 객체에 사용하게 되면 HousePark 클래스의 __add__ 라는 메서드가 자동으로 호출
pey - juliet # - 연산자를 객체에 사용하게 되면 HousePark 클래스의 __sub__ 라는 메서드가 자동으로 호출
| false |
1d23f35201f56850a07f7e7af2c66eb55e48ef8f | ajkim0701/projectE | /1.py | 338 | 4.21875 | 4 | '''Find the sum of all the multiples of 3 or 5 below 1000.
answer: 233168 '''
def foo(n):
a = 0
for x in range(1, n ):
if x % 3 == 0:
print(x, "Is divisible by 3")
a = a + x
elif x % 5 == 0:
print(x, "Is divisible by 5")
a = a + x
print(a)
foo(1000)
| false |
5c286f457c579ce1e72d18b5536fc6b32fdc6f00 | iffatunnessa/Artificial-intelligence | /lab3/New folder/s3p1.py | 691 | 4.15625 | 4 | # Writing to and reading from a file in Python
f1=open('stdfile.py', "w")
print("\n")
for i in range(2):
name=str(input("Enter the name:"))
dept=str(input("Enter the department:"))
cgpa=str(input("Enter the cgpa:"))
std=name+"\t"+dept+"\t"+cgpa
print(std, end="\n", file=f1)
f1.close
f1=open('stdfile.py', "r")
for l in f1:
name, dept, cgpa =l.split("\t")
print(name, dept, float(cgpa), end="\n")
f1.close
# Including files
import s3Module1 as m1
m1.display_file_lines('stdfile.py',2)
n=m1.num_of_lines('stdfile.py')
print("Number of lines in {} is {}.".format('stdfile.py',n))
m1.display_file('stdfile.py')
| true |
d832e81e854f6aaef5ad80cba90f30875813c00d | raj-shah14/Ctci | /StacknQueue/5.py | 1,170 | 4.125 | 4 | # Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use
# an additional temporary stack, but you may not copy the elements into any other data structure
# (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.
class Stack:
def __init__(self):
self.arr = []
def push(self,val):
self.arr.insert(0,val)
def pop(self):
popval = self.arr[0]
del self.arr[0]
return popval
def top(self):
return self.arr[0]
def isEmpty(self):
return self.arr == []
def showstack(self):
print(self.arr)
def sortStack(inputStack): # O(n^2) time Complexity and O(n) space Complexity
tmpStack = Stack()
while not inputStack.isEmpty():
tmp = inputStack.pop()
while not tmpStack.isEmpty() and tmpStack.top() > tmp:
inputStack.push( tmpStack.top() )
tmpStack.pop()
tmpStack.push(tmp)
return tmpStack
s = Stack()
s.push(10)
s.push(3)
s.push(5)
s.push(8)
s.push(1)
s.showstack()
res = Stack()
res = sortStack(s)
res.showstack() | true |
c570d3323d800d29b57abe9fa19b36be1d2e6c0d | raj-shah14/Ctci | /Recursion/1.py | 1,028 | 4.15625 | 4 | # Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3
# steps at a time. Implement a method to count how many possible ways the child can run up the
# stairs.
# Recursive
def tripleStep(n):
if n <= 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
return tripleStep(n-1) + tripleStep(n-2) + tripleStep(n-3)
print(tripleStep(5))
# Memoized -- > Bottom up Approach
def tripleStep_memo(n):
if n <= 3:
return n
temp = [0]*(n+1)
temp[0] = 0
temp[1] = 1
temp[2] = 2
temp[3] = 4
for i in range(4,n+1):
temp[i] = temp[i-1]+temp[i-2]+temp[i-3]
return temp[n]
print(tripleStep_memo(5))
# Top Down Approach with memo
memo = {0:0,1:1,2:2,3:4}
def tripleStep_td(n,memo):
if n in memo:
return memo[n]
else:
memo[n] = tripleStep_td(n-1,memo) + tripleStep_td(n-2,memo) + tripleStep_td(n-3,memo)
return memo[n]
print(tripleStep_td(5,memo)) | false |
432645728a986103a8f6ee5a149bfcb2d47d593d | raj-shah14/Ctci | /Arrays/9.py | 517 | 4.1875 | 4 | #Assume you have a method isSubstring which checks if one word is a substring of another
s1 = "waterbottle"
s2 = "erbottlewat"
def rotate(s1):
s1=list(s1)
temp = s1[0]
for i in range(len(s1)-1):
s1[i] = s1[i+1]
s1[len(s1)-1] = temp
return ''.join([i for i in s1])
def isSubstring(s1,s2):
if len(s1) != len(s2):
return False
for _ in range(len(s1)):
if (s1 == s2):
return True
s1 = rotate(s1)
# print(s1)
print(isSubstring(s1,s2)) | false |
7479fe8d200b4258c1c91dfcc6690e32ccc480a6 | raj-shah14/Ctci | /StacknQueue/1.py | 1,574 | 4.34375 | 4 |
# Three in One: Describe how you could use a single array to implement three stacks
class Kstacks:
def __init__(self,n,k):
self.n = n # Number of elements in Stack
self.k = k # Number of stacks
self.arr = [0]*self.n # Size of array
self.top = [-1] * self.k # Gives top of stack for each stack
#-1 says no value in stack
self.next = [i+1 for i in range(self.n)]
self.next[self.n -1] = -1
self.free = 0 # top of free stack
def isEmpty(self,sn): #Checks if the Stack is Empty
return self.top[sn] == -1
def isFull(self):
return self.free == -1
def push(self,sn,val):
if self.isFull():
print("Stack Overflow")
return
# Position to insert
insert_at = self.free
# Adjust the next free element
self.free = self.next[self.free]
#Insert the value in array
self.arr[insert_at] = val
# when we pop we want next to point previous value too
self.next[insert_at] = self.top[sn]
# Update top of stack
self.top[sn] = insert_at
def pop(self,sn):
pop_from = self.top[sn]
self.top[sn] = self.next[self.top[sn]]
self.next[pop_from] = self.free
self.free = pop_from
return self.arr[pop_from]
k = Kstacks(15,3)
k.push(0,5)
k.push(0,6)
k.push(0,14)
k.push(1,8)
k.push(1,15)
k.push(2,10)
k.push(2,11)
print(k.pop(0))
print(k.pop(1))
print(k.pop(2)) | true |
f3a0c33e6213a4a6ade928d3635ccbf03535aed3 | Dragos-n/00_Curs_Python | /Curs/c3_1.py | 475 | 4.25 | 4 | # print(2 > 3)
#
# a = None
# if 2 != 3:
# a = True
# else:
# a = False
#
# print(a)
#
# a = False
# b = True
#
# if a is False:
# print(a)
# intput_number = int(input("Introduceti numarul: "))
# even_count = 0
# odd_count = 0
#
# while intput_number != 0:
# if intput_number % 2 == 0: even_count += 1
# else: odd_count += 1
# intput_number = int(input("Introduceti numarul: "))
#
# print("Numere pare: ", even_count, "\nNumere impare: ", odd_count)
| false |
aeda510beec385b8622ff2fd6e74c867f9cd6c13 | gauthamp10/100DaysOfCode | /004/can_we_divide_8kyu.py | 659 | 4.21875 | 4 | """Your task is to create functionisDivideBy (or is_divide_by) to
check if an integer number is divisible by each out of two arguments."""
def is_divide_by(number, num_a, num_b):
"""Function to check divisibility"""
return True if abs(number) % abs(num_a) == 0 and abs(number) % abs(num_b) ==0 else False
def test_cases():
"""Some test cases"""
assert is_divide_by(-12, 2, -6) is True
assert is_divide_by(-12, 2, -5) is False
assert is_divide_by(45, 1, 6) is False
assert is_divide_by(45, 5 ,15) is True
assert is_divide_by(4, 1, 4) is True
assert is_divide_by(15, -5, 3) is True
print("Test Success!")
test_cases()
| true |
8addb336152c275bfcdba19520b60ff936feced3 | khidawo/python_variable- | /variable.py | 759 | 4.15625 | 4 | #an integer assignment
age=45
#a floating point
salary=16222.83
#a string
student="John"
print(age)
print(salary)
print(student)
#assigning a sinlge value to multiple variables
a=b=c=39
print(a)
print(b)
print(c)
#assigning a different values to multiple variables
a,b ,c =23, 34.3,"love python"
print(a)
print(b)
print(c)
#uses global because there is no local "a"
def f():
print('insisde f(): ',a)
#variable 'a' is redefined as a local
def g():
global
a=56
print('inside g():',a)
#uses global keyword to modify global 'a'
def h():
global
a=443
print('inside h():',a)
#global scope
print('global:',a)
f()
print('global:',a)
g()
print('global:',a)rint('global:',a)
h() | false |
3054847a6446d5b6eb193d5badc4c9ae4985bad8 | sanaydevi/leetCodeSolutions | /Leetcode--Python-master/Directory5/hammingDistance.py | 844 | 4.28125 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
"""
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
and_result = x & y
or_result = x | y
and_result = str(bin(and_result)[2:])
or_result = str(bin(or_result)[2:])
pos_diff = or_result.count("1") - and_result.count("1")
print(pos_diff)
if __name__ == "__main__":
ob = Solution()
ob.hammingDistance(1, 5)
| true |
e6e5f8d757a749c0f2f05c2423c003f209344567 | hvaltchev/python-practice | /number-game/game.py | 670 | 4.28125 | 4 | #!/usr/bin/env python3
#Generate a Random Number
#Have the user guess numbers until its right
#Say higher or lower
#Keep track of nymber of trys
#TODO Store player scores in a file
import random
import sys
numrange = int(sys.argv[1])
number = random.randint(1,numrange)
attempts = 1
print('The random number is in the range from 1 to', numrange)
while (True):
guess = int(input('Enter your guess: '))
attempts = attempts + 1
if guess < number:
print('Your guess is smaller.')
elif guess > number:
print('Your guess is bigger.')
else:
break
print('You are correct.')
print('You guessed in', attempts, 'attempts.')
| true |
0f3a7654d9ac9457beba815f8858286f7a4cfd9f | Att4ck3rS3cur1ty/Python_para_desenvolvedores-Exemplos-do-livro | /Exemplo_conversões_numéricas.py | 465 | 4.125 | 4 | # Real para inteiro
print("int(3.14) =", int(3.14))
# Inteiro para real
print("float(5) = ", float(5))
# Cálculo entre inteiro e real resulta em real
print("5.0 / 2 + 3 = ", 5.0 / 2 + 3)
# Inteiros em outra base
print("int('20', 8) =", int('20', 8)) # base 8
print("int('20', 16) =", int('20', 16)) # base 16
# Operações com números complexos
c = 3 + 4j
print("Parte real: ", c.real)
print("Parte imaginária: ", c.imag)
print("Conjugado", c.conjugate())
| false |
65e767531927e5747a6cdd3d3cb1420ea31b43c0 | Rkhwong/RHK_PYTHON_LEARNING | /PythonExercices/Semana_Python_Ocean_Marco_2021-main/Exercicios_Python_PauloSalvatore/Exercicio_14.py | 2,338 | 4.15625 | 4 | """
Exercício 14
Nome: Média Escolar
Objetivo: Escrever uma aplicação utilizando funções que calcule a média de um aluno.
Dificuldade: Intermediário
1 - Um professor, muito legal, fez 3 provas durante um semestre mas só vai levar em conta as duas
notas mais altas para calcular a média.
2 - Faça uma aplicação que peça o valor das 3 notas, mostre como seria a média com essas 3 provas,
a média com as 2 notas mais altas, bem como sua nota mais alta e sua nota mais baixa.
"""
#Tirar a Media
def mediaDasNotas(n1,n2,n3):
return (( n1 + n2 + n3 )/3)
def mediaDasMaioresNotas ( n1, n2):
return (( n1 + n2) / 2)
#Identifica qual a maior nota entre 2
def maiorNota(n1,n2):
# Primeiro Maior
if n1 > n2:
return n1
#Igual
elif n1 == n2:
return n1
#Segundo Maior
else:
return n2
#Mostrar a Nota menor
def menorNota(n1,n2):
# Segundo Maior
if n1 < n2:
return n1
#Igual
elif n1 == n2:
return n1
#Segundo Menor
else:
return n2
#Mostrar a nota mais Alta
def notasMaisAltas(notas):
# Pegamos a maior nota entre a nota1 e a nota2
maior1 = maiorNota(notas[0],notas[1])
# Pegamos a maior nota entre a nota2 e a nota3
maior2 = maiorNota(notas[1],notas[2])
# Caso a maior nota (1) seja igual a maior nota (2), pegamos a maior nota entre a 1 e a 3
if maior1 == maior2:
maior2 = maiorNota(notas[0],notas[2])
mediaMaiorNota = mediaDasMaioresNotas(maior1,maior2)
return mediaMaiorNota
def dados():
provas = [0,0,0]
for x in range (3):
provas[x] = float(input("Nota {} :".format(x+1)))
mediaMaiorNota = notasMaisAltas(provas)
# Pegamos a maior nota entre as três notas
maior_Nota = maiorNota(provas[0],provas[1])
maior_Nota = maiorNota(maior_Nota,provas[2])
# Pegamos a menor nota entre as três notas
menor_Nota = menorNota(provas[0],provas[1])
menor_Nota = menorNota(menor_Nota,provas[2])
mediaGeral = mediaDasNotas(provas[0],provas[1],provas[2])
print("==============================\nResultados\n============================== \n •Nota 1: {}\n •Nota 2: {}\n •Nota 3: {}\n •Média Geral : {:.2f}\n •Media das melhores Notas : {:.2f} ".format(provas[0],provas[1],provas[2],mediaGeral,mediaMaiorNota))
#Main
dados() | false |
77ecd7154d60a05c9386eecac9147309dfb28a8b | Rkhwong/RHK_PYTHON_LEARNING | /Python_Learning/Numpy.py | 1,134 | 4.125 | 4 | # Create 2 new lists height and weight
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
# Import the numpy package as np
import numpy as np
# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)
print(type(np_weight))
print(np_height)
print(np_weight)
# Calculate bmi
bmi = np_weight / np_height ** 2
# Print the result
print(type(bmi))
print(bmi)
# For a boolean response
bmi < 25
# Print only those observations above 23
print(bmi[bmi < 25])
"""First, convert the list of weights from a list to a Numpy array.
Then, convert all of the weights from kilograms to pounds.
Use the scalar conversion of 2.2 lbs per kilogram to make your conversion.
Lastly, print the resulting array of weights in pounds."""
weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
import numpy as np
# Create a numpy array np_weight_kg from weight_kg
np_weight = np.array(weight_kg)
# Create np_weight_lbs from np_weight_kg
np_weight_lbs = np_weight * 2.2
# Print out np_weight_lbs
print(np_weight_lbs)
print(np_weight_lbs[np_weight_lbs < 190]) | true |
83726d284b7a31c7c50eba8ce6d4cd92b9a0a726 | AnnaNik553/basics-of-the-language-Python | /lesson_1/lesson1-1.py | 495 | 4.28125 | 4 | # Поработайте с переменными, создайте несколько, выведите на экран, запросите у
# пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
name = 'Alise'
age = 18
print(name, age)
name = input('Введите ваше имя: ')
age = int(input('Введиде ваш возврат: '))
print(f'Имя: {name}, возраст: {age}') | false |
8f3685176a64fa5fe08f6c1db4239f30d495e5ec | kayyali18/Python-Code | /Python 31 Programs/Ch 1 - 4/Coin Flip Counter.py | 740 | 4.3125 | 4 | ##Coin flip counter program
##Algorithm
##import random
##Set value for coin to range (1,2)
##Create heads and tails value set at 0
## Create flip counter
##While count is < 100
##Flip coin
## Count if heads or tails
## Repeat
print("Welcome to the Coin Flip Counter Program")
input("This program will flip a coin 100 times and give you \n\
back the results. Press enter to check it out:")
import random
heads = 0
tails = 0
flip_counter = 0
while flip_counter < 100:
coin = random.randint(1,2)
if coin == 1:
heads += 1
elif coin == 2:
tails += 1
flip_counter += 1
print("Total amount of heads vs tails in 100 tries is:\n\t",
heads, "heads\n\t", tails,"tails.")
input ("\nPress Enter to exit")
| true |
09db1ed5dd377fc4e8be78db671c0408aa989449 | kayyali18/Python-Code | /Python 31 Programs/Ch 7/Pickle_it.py | 1,131 | 4.125 | 4 | # Pickle it
# Demonstrates pickling and shelving data
import pickle, shelve
print ("Pickling lists")
variety = ["Sweet", "Hot", "Dill"]
shape = ["Whole", "Spear", "Chip"]
brand = ["Claussen", "Heinz", "Classic"]
f = open ("pickles1.dat", "wb")
pickle.dump (variety, f)
pickle.dump (shape, f)
pickle.dump (brand, f)
f.close ()
# unpickling the lists from the file
print ("\nUnpickling lists")
f = open ("pickles1.dat", "rb")
variety = pickle.load (f)
shape = pickle.load (f)
brand = pickle.load (f)
print (variety)
print (shape)
print (brand)
f.close ()
## Shelving
## Shelves act like a dictionary thus providing random access to the lists
print ("Shelving Lists")
# Creating shelf
shelf = shelve.open ("pickles2.dat")
shelf["variety"] = ["Sweet", "Hot", "Dill"]
shelf["shape"] = ["Whole", "Spear", "Chip"]
shelf["brand"] = ["Claussen", "Heinz", "Classic"]
shelf.sync () ## make sure data is written
print("\nRetrieving lists from a shelved file:\t")
print ("brand - ", shelf["brand"])
print ("variety - ", shelf["variety"])
print ("shape - ", shelf["shape"])
shelf.close ()
input ("\nPress Enter key to exit")
| true |
094f58bd7c6dcf83cb8327cbe9f5c9929df77842 | Rohit263/python-practice | /soln3_smallest_divisible.py | 963 | 4.15625 | 4 | def div():
#l_lim = lower limit of the searching range
#u_lim = upper limit of the searching range
#declaring x,y,l_lim,u_lim as global variable
global x,y,l_lim,u_lim
l_lim =1
u_lim =1
values = []
# Getting the value of lower limit and upper limit of the search for any x and y
for i in range(x-1):
l_lim = 10*l_lim
u_lim = ((l_lim*10)-1)
#Appending all the values that are in search area and is divisible by any given y to a list
for r in range(l_lim,u_lim+1):
if r%y==0:
values.append(r)
# Finding the smallest value among all the feasible values
smallest = min(values)
print('')
print(f'Smallest {x} digit number divisible by {y} is: {smallest}')
# Start of main function block
if __name__ == '__main__':
x= int(input("Enter no. of digit: "))
y= int(input("Enter divisibility number: "))
#Calling of the div() function
div()
| true |
d4ba69c6ada98281ba4485ca93f492b66f4dcb1a | aleranaudo/SizeItUp | /dic.py | 1,505 | 4.21875 | 4 | #dictionary
'''
family_members= {
'maria':'mom, age 46, born in venezuela',
'daniele':'dad, age 49, born in the usa',
'daniel':'brotha, age 13, born in the usa',
'david':'brotha, age 11, born in the usa',
'ada':'gramma, age 70, born in venezuela',
'david':'cousin, age 19, born in venezuela',
'andrea': 'cousin, age 26, born in venezuela',
}
print(family_members)
family_members["maria"]=17
print(family_members)
def main():
while True:
print("heyyyy, ready to take my survey??")
user_input = input()
print("lets take the survey")
user_input = input()
print("so before we start lemme know ur age")
user_input = input()
print("r u male female or other")
user_input = input()
print("ok thats great lastly what do u wanna be when you grow up?")
user_input = input()
print("i have a perfect survey fthat wil identify what you really wanna be when you grow up")
user_input = input()
print("where do you like eating in wendys or mccdonalds?")
user_input = input()
print("do u shop at forever 21 or at fashion nova?")
user_input = input()
print("do u prefer long nails or short nails")
user_input = input()
print("ur set to be a carpenter")
break
user_input = input()
num=int(input("enter a number: "))
if(num%2)==0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num))
break
# no tocar
if __name__ == "__main__":
main()
| false |
9d2ca5a385555fa9a79f69d935c87814d84d8fe3 | aleranaudo/SizeItUp | /word.py | 778 | 4.1875 | 4 | import random
'''
# A list of words that
potential_words = ["money"]
word = random.choice(potential_words)
# Use to test your code:
# print(word)
# Converts the word to lowercase
word = word.lower()
# Make it a list of letters for someone to guess
current_word = ["money"] # TIP: the number of letters should match the word.....
'''
# Some useful variables
guesses = []
maxfails = 10
fails = 0
while fails < maxfails:
guess = input("guess: ")
guesses.extend(guess)
if guess=="m":
print("u got it!")
print(guesses)
continue
# check if the guess is valid: Is it one letter? Have they already guessed it?
# check if the guess is correct: Is it in the word? If so, reveal the letters!
fails = fails+1
print("You have " + str(maxfails - fails) + " tries left!")
| true |
6228036c577a50e233b0eac7c0face5dd10dca3b | imaspen/First-Term | /sdd/practicals/eight/6.py | 2,655 | 4.125 | 4 | #!/usr/bin/env python3
"""
Simulates a chat system for a University.
"""
import random
import re
__author__ = "Aspen Thompson"
__email__ = "u1862679@hud.ac.uk"
__date__ = "15-11-2018"
def get_random_name():
"""
Returns a random string from a list.
:return: name string
"""
NAMES = ['Alice', 'Bob', 'Charlie', 'Delia']
return random.choice(NAMES)
def get_random_answer():
"""
Returns a random answer from a list.
:return: answer string
"""
ANSWERS = ["Maybe.", "Tell me more.", "I am pleased to hear that."]
return random.choice(ANSWERS)
def is_valid_email(candidate):
"""
Checks a string to check if it is a valid email address.
:param candidate: the potential email address.
:return: True if is an email address, else False.
"""
email_check = re.compile("\A[^@\s]+@pop\.ac\.uk\Z")
return email_check.match(candidate)
def get_email_user(email_address):
"""
Gets all of an email address that precedes the @.
:param email_address: the email address to strip.
:return: the string that precedes the @.
"""
return email_address[:email_address.find("@")].capitalize()
def get_query_input():
"""
Asks the user to enter text until "goodbye" is entered.
:return: nothing.
"""
while True:
query = input("Please enter your query: ").lower()
if question_has_string(query, "library"):
print("The library is closed today.")
elif question_has_string(query, "wifi"):
print("WiFi is excellent across the campus.")
elif question_has_string(query, "deadline"):
print("Your deadline has been extended by two working days.")
elif query == "goodbye":
print("Goodbye!")
return
else:
print(get_random_answer())
if random.randint(0, 100) < 15:
print("Connection Lost")
return
def question_has_string(question, search_string):
"""
Checks if a string is within a question.
:param question: the string to search within
:param search_string: the string to search for
:return: True if question has string, else False
"""
return search_string in question
if __name__ == "__main__":
email = input("Please enter your University of Poppleton email address: ")
if is_valid_email(email):
print("Thank you, that email checks out.")
else:
print("That email is not valid, sorry, but we will be unable to answer your query, goodbye.")
exit(1)
print("Hello {}, my name is {}.".format(get_email_user(email), get_random_name()))
get_query_input()
| true |
4e90cbc01519f53afa42c87173ba1445bcf9f56b | durguupi/python_programs | /fundamentals/numberrange.py | 345 | 4.4375 | 4 | # Write a short program that prints the numbers 1 to 10 using a for loop. Then write an equivalent
# # program that prints the numbers 1 to 10 using a while loop
print("Using FOR Loop")
for num in range(1, 11):
print(f"Number: {num}")
print("Using while loop")
number = 1
while number < 11:
print(f"Number: {number}")
number += 1
| true |
47026023f30e86599bcf8b00b4aade5015987c36 | durguupi/python_programs | /basics/zip_functions/overforloop.py | 614 | 4.34375 | 4 | # Traversing Lists in Parallel using for loop
# Python’s zip() function allows you to iterate in parallel over two or more iterables.
# Since zip() generates tuples, you can unpack these in the header of a for loop:
letters = ['a', 'b', 'c']
numbers = [0, 1, 2]
operators = ['*', '/', '+']
# for let, num in zip(letters, numbers):
# print(f"Number: {num} Type: {type(num)}")
# print(f"Letter: {let} Type: {type(let)}")
for let, num, oper in zip(letters, numbers, operators):
print(
f"Number: {num} Type: {type(num)} \nLetter: {let} Type: {type(let)} \nOperators: {oper} Type: {type(oper)}")
| true |
f65f7843ac05a0799737e04877fad43030063dd3 | durguupi/python_programs | /fundamentals/copydecopy.py | 791 | 4.1875 | 4 | # Although passing around references is often the handiest way to deal with lists and dictionaries, if the
# function modifies the list or dictionary that is passed, you may not want these changes in the original list or
# dictionary value.
#
# For this, Python provides a module named copy that provides both the copy() and deepcopy()
# functions. The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value like a list or
# dictionary, not just a copy of a reference
import copy
spam = ['A', 'B', 'C', 'D']
print(id(spam))
cheese = copy.copy(spam)
print(id(cheese)) # cheese is a different list with different identity.
cheese[1] = 42
print(spam)
print(cheese)
# cheese = copy.copy(spam) creates a second list that can be modified independently of the first.
| true |
3729c43eaf67b6353b1993559c5237438109e90d | durguupi/python_programs | /intermdeiate/comprehensions/dictionarycomprehension.py | 596 | 4.21875 | 4 | names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
new_value_zipped = zip(names, heros)
print(list(new_value_zipped))
new_value = {}
# Using normal for loops we got new value with names:heros
for name, hero in zip(names, heros):
new_value[name] = hero
print(new_value)
# Using dictionary comprehensions we can get with names:values without peter value
new_value_comp = {name: hero for name,
hero in zip(names, heros) if name != 'Peter'}
print(f"Output using dictionarycomprehension: {new_value_comp}")
| true |
f1013bf7366c583fd463cfa7e67620d9ed576bb7 | durguupi/python_programs | /basics/list_examples/exercise2.py | 460 | 4.125 | 4 | # Write a Python program to count the number of strings where the string length is 2 or more and
# the first and last character are same from a given list of strings.
# Sample List : ['abc', 'xyz', 'aba', '1221']
# Expected Result : 2
sample_list = ['abc', 'xyz', 'aba', '1221']
count_items = 0
for items in sample_list:
print(items)
if len(items) >= 2 and items[0] == items[-1]:
count_items += 1
print(f"Count of the items: {count_items}")
| true |
f2b59e0cc37c5bcaf05f6b2013699064a1d98c9e | durguupi/python_programs | /fundamentals/while.py | 812 | 4.15625 | 4 | # While condition executes untill the condtion is true
# The code in a while clause will be executed as long as the while statement’s condition is True
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
# There is a shortcut to getting the program execution to break out of a while loop’s clause early. If the
# execution reaches a break statement, it immediately exits the while loop’s clause
# If the user enters any name besides Joe, the continue statement causes the program execution to jump
# back to the start of the loop
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
| true |
40cf2bba1f213cf0f9daeb6a16dfa2e2129261f2 | GloriaGutGut/Portafolio_MisionTic2022 | /Phyton/Reto1_input.py | 1,046 | 4.125 | 4 | """
Un asesor de seguros debe calcular el valor total de los seguros que vende
teniendo en cuenta los siguientes parámetros:
nombre y apellido del tomador del seguro
valor_asegurado, valor a pagar (15% del valor asegurado)
descuento del mes (5%)
"""
nombre = input("ingrese el nombre del tomador del seguro ")
apellido = input("ingrese el apellido del tomador del seguro ")
nom_apell = nombre + " " + apellido
valor_1 = int(input("ingrese el valor asegurado sin puntos o comas "))
valor_2 = valor_1 * 0.15
descuento = valor_2 * 0.05
total = valor_2 - descuento
print("Reto 1 realizado por: Gloria Beatriz Gutiérrez G. cc43615404")
print ("EMPRESA DE SEGUROS TRANQUILIDAD")
print ("Sólo por éste mes descuento del 5% en el valor de su seguro")
print ("EL TOMADOR DEL SEGURO ES: " + str(nom_apell))
print ("Monto asegurado es: $" + str(valor_1))
print ("Valor del seguro antes de aplicar descuento es: $" +str(valor_2))
print ("Descuento realizado es: $" +str(descuento))
print ("Valor total a pagar por el seguro es: $" + str(total))
| false |
33eff8d49ebc4a7fa4d43a73454ba74a003e4809 | zxt2012bs/testpython | /code/Area of radius.py | 230 | 4.125 | 4 | # Assign a value to radius
radius = eval(input("请输入圆的半径:")) # radius is now 20
# Compute area
area = radius * radius * 3.14159
# Display results
print ("The area for the circlue of radius", radius ,"is", area)
| true |
975f85fbdb46195f1dc18ef56fe362cc56bb6502 | RJStuver/old-man-learning | /Alphabet.py | 656 | 4.21875 | 4 | #Alphabet
alphabet = 'ABCDEFGHIJLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
stringToEncrypt = (input('Please enter a message to encrypt '))
stringToEncrypt = stringToEncrypt.upper()
shiftAmount = int(input('Pliese enter a whole number frin 1-25 to be your key'))
encryptedString = ''
for currentCharacter in stringToEncrypt:
position = alphabet.find(currentCharacter)
newPosition = position + shiftAmount
if currentCharacter in alphabet:
encryptedString = encryptedString + alphabet[newPosition]
else:
encryptedString = encryptedString + currentCharacter
print('Your encrypted message is', encryptedString)
| true |
5403154c6836e626231cc8552d8424ed2bf5ed86 | RJStuver/old-man-learning | /Character.py | 229 | 4.15625 | 4 | #Character
print('Create Character')
name = input('What is your character called?'' ')
age = input('How old is your character?'' ')
print('My characters name is', (name) ,'and he is',(age) ,'years old.')
| false |
9b7af57829ee8cb9cd2f6efb5a374b0158d409f1 | mccoinj6975/cti110 | /P4HW1_ CaloriesBurned _JessicaMcCoin.py | 1,115 | 4.3125 | 4 | # Description: This program uses a for loop to calculate the number of calories burned on
# a treadmill after 20, 35, and 45 minutes assuming you burn 5 calories per minute.
# Date: 19 March 2019
# CTI-110 P4HW1: Calories Burned
# Name: Jessica McCoin
#
# create a while loop to range from 19 to 46
# incriment minutes by 1 through the loop
# create if/else statements to select the numbers 20, 35, 45
# print out the calories burned for 20, 35, 45 minutes
def main():
minutes = 19 #set minutes to 19 where the loop will begin
while minutes < 46: #begining of while loop
#print(i)
minutes += 1 #incriment minutes by 1 to keep the loop going
if minutes == 20:
print('The amount of calories burned for 20 minutes is 100.')
elif minutes == 35:
print('The amount of calories burned for 35 minutes is 175.')
elif minutes == 45:
print('The amount of calories burned for 45 minutes is 225.')
else:
continue #keep the loop going until it reaches 46
main()
| true |
601f339ec423f8ccb2b53141eed15aac077b809d | mccoinj6975/cti110 | /P4T2_BugCollector_JessicaMcCoin.py | 781 | 4.3125 | 4 | # Description: This program uses a for loop for enter the number of bugs collected
# each day for 9 days and add them together.
# Date: 7 March 2019
# CTI-110 P4T2a: Bug Collector
# Name: Jessica McCoin
#
# import turtle into program
# set total = 0
# input bugs collected for a day
# add bugs collected to total
# display total
def main():
#Initialize the accumaulator
total = 0
#Get the bugs collected for each day
for day in range(1, 8):
#prompt the user
print('Enter the bugs collected on day', day)
#Input the number of bugs.
bugs = int(input())
#Add bugs to total.
total += bugs
# Display the total bugs
print('You collected a total of', total, 'bugs.')
main()
| true |
b815a9013ed8c62ad9cfb64ef4fdc0353edd559e | iDelith/python-learning | /Python/Curso Em Video/Mundo 1/Exercicios/ex009.py | 2,019 | 4.375 | 4 | #!/usr/bin/env python3
# ===========================================================================
# Exercício 009 Aula 07 - Tabuada
# Faça um programa que leia um número inteiro qualquer e mostre na tela
# sua tabuada.
# ===========================================================================
# Tabuada básica utilizando apenas a função print
num = int(input('Digite um número para verificar a tabuada: '))
print(f'''
{'='*40}
Utilizando apenas o método print():
{'='*40}
'''
)
print('-' * 20)
print('{} x {:2} = {}'.format(num, 1, num * 1))
print('{} x {:2} = {}'.format(num, 2, num * 2))
print('{} x {:2} = {}'.format(num, 3, num * 3))
print('{} x {:2} = {}'.format(num, 4, num * 4))
print('{} x {:2} = {}'.format(num, 5, num * 5))
print('{} x {:2} = {}'.format(num, 6, num * 6))
print('{} x {:2} = {}'.format(num, 7, num * 7))
print('{} x {:2} = {}'.format(num, 8, num * 8))
print('{} x {:2} = {}'.format(num, 9, num * 9))
print('{} x {:2} = {}'.format(num, 10, num * 10))
print('-' * 20)
# Vamos tentar fazer essa mesma tabuada utilizando for loop
print(f'''
{'='*40}
Utilizando o método for-loop:
{'='*40}
'''
)
print('-' * 20)
for i in range(1, 11):
print('{} x {:2} = {}'.format(num, i, num * i))
print('-' * 20)
# OUTPUT
# Digite um número para verificar a tabuada: 9
# ========================================
# Utilizando apenas o método print():
# ========================================
# --------------------
# 9 x 1 = 9
# 9 x 2 = 18
# 9 x 3 = 27
# 9 x 4 = 36
# 9 x 5 = 45
# 9 x 6 = 54
# 9 x 7 = 63
# 9 x 8 = 72
# 9 x 9 = 81
# 9 x 10 = 90
# --------------------
# ========================================
# Utilizando o método for-loop:
# ========================================
# --------------------
# 9 x 1 = 9
# 9 x 2 = 18
# 9 x 3 = 27
# 9 x 4 = 36
# 9 x 5 = 45
# 9 x 6 = 54
# 9 x 7 = 63
# 9 x 8 = 72
# 9 x 9 = 81
# 9 x 10 = 90
# --------------------
| false |
d760bde404c17ea3b6c643d3cd4bd3c35229c9b6 | iDelith/python-learning | /Python/Curso Em Video/Mundo 1/Exercicios/ex008.py | 2,073 | 4.34375 | 4 | #!/usr/bin/env python3
# ===========================================================================
# Exercício 008 Aula 07 - Conversor de Medidas
# Escreva um programa que leia um valor em metros e o exiba convertido
# em centímetros e milímetros.
# ===========================================================================
# Escala de conversão
# -------------------------------------------------------------------
# km hm dam m dm cm mm
# 0,001 0,01 0,1 1 10 100 1000
# -------------------------------------------------------------------
# Vamos aproveitar e mostrar todas as medidas relacionadas seguindo a tabela.
medida = float(input('Digite uma distância em metros: '))
km = (medida / 1000)
hm = (medida / 100)
dam = (medida / 10)
dm = (medida * 10)
cm = (medida * 100)
mm = (medida * 1000)
print('\n \nDistância de referência: {} em [metros]'.format(medida))
# Vamos colocar isso dentro de uma table para facilitar a visualização
print(f'''
{'-'*70}
km hm dam m dm cm mm
{km} {hm} {dam} {medida} {dm} {cm} {mm}
{'-'*70}
'''
)
print(
'{}m podem ser convertidos para as seguintes medidas: \n\n'
f'''{'-'*10}''' '\n'
'{:.0f} mm \n'
'{:.0f} cm \n'
'{:.0f} dm \n'
'{} dam \n'
'{} hm \n'
'{} km \n'
f'''{'-'*10}''' '\n'
.format(medida, mm, cm, dm, dam, hm, km)
)
# OUTPUT
# Digite uma distância em metros: 5
# Distância de referência: 5.0 em [metros]
# ----------------------------------------------------------------------
# km hm dam m dm cm mm
# 0.005 0.05 0.5 5.0 50.0 500.0 5000.0
# ----------------------------------------------------------------------
# 5.0m podem ser convertidos para as seguintes medidas:
# ----------
# 5000 mm
# 500 cm
# 50 dm
# 0.5 dam
# 0.05 hm
# 0.005 km
# ----------
| false |
20d60e3e0d3c3e6c014ef9111e8ba58e131e919c | markser/CS362-SP21-HW4 | /averageInList.py | 709 | 4.3125 | 4 | # to run
# python3 averageInList.py
# then input elements in console one by one, list finishes when user inputs string
def main():
# print("Enter integer to include in list, any non integers will exit and compute the average")
# try block to handle the exception
try:
my_list = []
while True:
my_list.append(float(input()))
# if the input is not-integer, just print the list
except:
print("This is the user input list: {0}".format(my_list))
average = sum(my_list)/len(my_list) if len(my_list) else 0
print("This is the average of elements in the list: {0}".format(average))
if __name__ == "__main__":
main()
| true |
01140680bfd205dae2f294c7970d4a6668aad20e | skocevski/mike | /assignment1/mike_assignment1_2.py | 1,221 | 4.21875 | 4 | import math #importing math library to be able later to use the functions sin() and cosin()
import random #importing the library random, to use the function randomint to generate random numbers in a specific range
x = 0 #declaring integer variable to use it as a counter later in a loop
while (x < 10): #while loop that circels 10 times
y = random.randint(0, 90) #declaring y variable that has the value of the result of the function randit() which generates random value in the range of 0-99
s = math.sin(y) #declaring s variable that holds the result of the function sinus() of the previous randomly generated number
c = math.cos(y) #declaring c variable that holds the result of the function cosine() of the previous randomly generated number
print("Number %d has \t sin:%f \t and cosine:%f" % (y, s, c)) #command print to show the randoly generated number and its sinus in cosinus
x += 1 #increasing the value of the counter by 1
# Team name: mike
#Team memebers: Anish Girijashivaraj, Shohel Ahamad, Slobodan Kocevski
| true |
1ea4e068848b9ffe74bfa30870c89c07496b86e9 | SubhajitCode/HackingAndCtf | /RingZero/Crypto/Some_martian_message/decrypt.py | 1,019 | 4.125 | 4 | import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-E","--Encrypt",help ="Enter The encryption text")
parser.add_argument("-D","--Decrypt",help ="Enter The decryption text")
args = parser.parse_args()
key = 26
plaintext=""
# encipher
if(args.Encrypt):
for x in range(key):
ciphertext = ""
plaintext = args.Encrypt
for c in plaintext:
if(c.isalpha()):
if ((c>='a' and c<=chr(ord('z')-x)) or (c<=chr(ord('Z')-x) and c>='A')):
ciphertext = ciphertext+chr((ord(c)+x))
else:
ciphertext = ciphertext+chr((ord(c)+x)-26)
else:
plaintext2 += c
print ciphertext
# decipher
if (args.Decrypt):
for x in range(key):
plaintext2 = ""
ciphertext = args.Decrypt
for c in ciphertext:
if(c.isalpha()):
if ((c>=chr(ord('a')+x) and c<='z') or (c<='Z' and (c>=chr(ord('A')+x)))):
plaintext2 = plaintext2+chr((ord(c)-x))
else:
plaintext2 = plaintext2+chr((ord(c)-x)+26)
else:
plaintext2 += c
print plaintext2
#print plaintext
| false |
39c8f3b7954482fc18f72bafdc7c5f9f2610de03 | Nexian32/python | /belajarpython.py | 622 | 4.15625 | 4 | msg = input("What's the secret password: ")
# Password attempt is 3 times, starts at 2, then 1 and ends when counter is 0
num = 3
# bananas is the correct password
while msg != "":
# exhausted all 3 attempts, should print given message.
if msg == "bananas":
print("DECRYPT SUCSSESFUL")
break
elif num < 1:
print("Too many wrong attempts. You are locked out!")
break
else:
print(f"Wrong Password! You have {num} chances left") # password incorrect, display attempts left
msg = input("What's the secret password: ")
num = num - 1
| true |
ea3935d677e86da70f333e8edef97696dc2eb4e0 | Shikhar0907/Algo-and-data-structure-questions | /Amazon_interview/Array/reverse_string_recursive.py | 240 | 4.28125 | 4 | def reverse_string(string):
if len(string) == 0:
return(string)
return(string[-1:] + reverse_string(string[:-1]))
def main():
string = str(input("Please enter the string: "))
print(reverse_string(string))
main()
| true |
bc54eda795fc8d969cee0b45fe20f4e53350958a | ynjacobs/python_fundamentals1 | /exercise5.py | 292 | 4.25 | 4 | distance = 0
answer = ""
while answer != "quit":
print("Would you like to walk or run or quit?")
answer = input()
if answer == "walk":
distance += 1
elif answer == "run":
distance += 5
print("Distance from home is {} km".format(distance))
| true |
480a1a9ecdeef64d746b3a0310e66c9480a4aeb1 | sandro-fidelis/Cursos | /Curso Python/ex033.py | 473 | 4.1875 | 4 | n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
if n1>n2 and n1>n3:
maior=n1
else:
if n2>n1 and n2>n3:
maior=n2
else:
maior=n3
print('O maior número digitado foi {}'.format(maior))
if n1<n2 and n1<n3:
menor = n1
else:
if n2<n1 and n2<n3:
menor = n2
else:
menor = n3
print('O menor número digitado foi {}'.format(menor))
| false |
0f2ad445d44eee60a31dde04295793cafdbe46bd | EMiles12/BeginnerPython | /C1 Challenges (int. mode).py | 1,310 | 4.25 | 4 | Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #C1 Challenges
>>> #1 - Create an error of your very own by entering your favourite ice cream flavour in interactive mode. Then, make up for your misdeed and enter a statement that prints the name of your favourite ice cream flavour.
>>>
>>> strawberry
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
strawberry
NameError: name 'strawberry' is not defined
>>> print("My favourite ice cream flavour is strawberry.")
My favourite ice cream flavour is strawberry.
>>>
>>> #2 - Write and save a program that prints out your name and waits for the user to press the Enter key before the program ends.
>>>
>>> print("My name is Emma.")
My name is Emma.
>>> input("\n\nPress the enter key to exit.")
Press the enter key to exit.
''
>>> #3 - Write a program that prints your favourite quote. It should give credit to the person who said it on the next line.
>>> print("There is no path to happiness, happiness is the path.")
There is no path to happiness, happiness is the path.
>>> print("-Buddha")
-Buddha
>>> input("\n\nPress the enter key to exit.")
Press the enter key to exit.
| true |
c7191344ca95f9e5550755e8e66c2900797a4687 | dorianbizgan/programs | /CS 303e Assignments/Age.py | 796 | 4.3125 | 4 | #I'm guessing this is a comment xd
#So instead of while true, you want to take user input for whether he/she wants the loop to continue.
continueInput = True
#prompt user to change continueInput after each iteration of loop.
while continueInput:
print ("Input the first number you'd like to use:")
#I don't really understand why you indented this stuff so idk.
try:
#I think this should be on a new line.
numInput1 = int(input())
continueInput = False
# I'm starting the second input here
secondInput = True
while secondInput:
print("Input your second number here:")
try:
numInput2 = int(input())
secondInput = False
# I think this checks to see if the input is a integer
# I need to make it loop somehow if it realizes its not an int
| true |
853d30c874a1078f34965db95498b251d184af05 | dorianbizgan/programs | /Practice/queue_with_linked_list.py | 2,071 | 4.1875 | 4 | def queue_with_linked_list():
# queue using linked list
class node:
def __init__(self, data, next):
self.data = data
self.next = next
def __repr__(self):
return(str(self.data))
class queue:
def __init__(self):
self.first = None
self.last = None
def enqueue(self, data):
temp = node(data, None)
if self.first == None:
self.first = temp
else:
if self.last == None:
self.last = temp
self.first.next = temp
else:
self.last.next = temp
self.last = temp
def dequeue(self):
if self.first == None:
self.last = None
return(None)
else:
temp = self.first
self.first = self.first.next
return(temp)
def __str__(self):
temp = ""
cur_node = self.first
while cur_node != None:
temp += str(cur_node.data) + " "
cur_node = cur_node.next
return(temp)
# Initializations
user_in = None
mode = "enqueue"
q = queue()
print("Enter value use want to add. \nEnter 'shift' to change mode from enqueue or dequeue. \nEnter 'Exit' to exit program.")
while user_in != "Exit":
print(q)
user_in = input()
if user_in == "shift":
if mode == "enqueue":
mode = "dequeue"
else:
mode = "enqueue"
print("Current mode is:",mode)
elif user_in == "Exit":
break
else:
if mode == "enqueue":
q.enqueue(user_in)
else:
q.dequeue()
queue_with_linked_list() | false |
40c931436e3fd51f37503b510879e117f3bf3a36 | dorianbizgan/programs | /CS 303e Assignments/Doors.py | 1,774 | 4.1875 | 4 | # File: Deal.py
# Description:Simulation of let's make a deal. Finds the probability that
# a contestent would win by swapping doors, rather than sticking
# with the one that
# Student Name:
# Student UT EID:
# Course Name: CS 303E
# Unique Number:
# Date Created:
# Date Last Modified:
import random
#determines which door the host reveals
def other_door(door_prize, door_guess):
door_other = 1
while door_other == door_guess or door_other == door_prize:
door_other += 1
return(door_other)
#function that runs the simulation of making deals and swapping doors
def swap_door(games):
current_game = 0
won_swapping = 0
while current_game < games:
#generates door for prize and what contestent chooses
door_prize = random.randint(1,3)
door_guess = random.randint(1,3)
current_door = 1
revealed_door = other_door(door_prize, door_guess)
#considering whether or not the game is won by swapping
while current_door == door_guess or current_door == revealed_door:
current_door += 1
if current_door == door_prize:
won_swapping += 1
current_game += 1
print(" "*3,door_prize," "*8,door_guess," "*8,revealed_door," "*8, current_door)
print()
probability = won_swapping/games
print("Probability of winning by swapping = ",format(probability,".2f"))
print("Probability of winning by not swapping = ", format(1 - probability,".2f"))
def main():
games = int(input("Enter number of times you want to play: "))
print()
print(" Prize Guess View New Guess")
# calls function that finds probability of winning and prints doors information
swap_door(games)
main()
| true |
eae26cd3f639b9b43c3ccdd70f52869e3a4ec55b | san-had/codewars | /pydev/pylearn/grocary_list.py | 389 | 4.125 | 4 |
def printList(list):
print('Your Grocery List:')
text_length = 25
print(' {}'.format('-' * text_length))
print(' {}'.format('-' * 25))
for item in list:
print(item)
grocary_list = []
item = 'Hello'
while item!='':
item = input('Enter an item for your grocery list. Press <ENTER> when done: ')
grocary_list.append(item)
printList(grocary_list)
| true |
1d1dfbaed1876c6d76b5d0cb245e4990ad84a8eb | san-had/codewars | /pydev/pylearn/vegetable.py | 396 | 4.125 | 4 | animal = "deer"
vegetable = "spinach"
mineral = "aluminium"
print("Here is an {}, a {}, and an {}.".format(animal, vegetable, mineral))
user_input = input('Please type something and press enter: ')
print('You entered: ')
print(user_input)
user_input = input('Please type something and press enter: ')
text_length = len(user_input)
print('_' * text_length)
print('< {} >'.format(user_input)) | true |
521eaa8383b77c91fbecc21f7af3e67141c0790a | ejhobbs/Python_Arcade_Games | /Chapter Four/camel.py | 2,610 | 4.1875 | 4 | import random
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down! Survive your")
print("desert trek and out run the natives.")
done = False
natives_travelled = -20
drinks_left = 5
miles_travelled = 0
camel_tiredness = 0
thirst = 0
while not done:
#print choices
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = input("Your Choice? ").lower()
if user_choice == "q":
done = True
elif user_choice == "e":
print("Miles travelled: ",miles_travelled)
print("Drinks left: ",drinks_left)
print("The natives are", miles_travelled-natives_travelled, "miles behind you")
elif user_choice == "d":
camel_tiredness = 0
print("Camel is now happy!")
natives_travelled += random.randrange(7,15)
elif user_choice == "c":
distance = random.randrange(10,21)
miles_travelled += distance
print("You travelled",distance,"miles")
thirst += 1
camel_tiredness += random.randrange(1,4)
natives_travelled += random.randrange(7,15)
elif user_choice == "b":
distance = random.randrange(5,13)
miles_travelled += distance
print("You travelled",distance,"miles")
thirst += 1
camel_tiredness += 1
natives_travelled += random.randrange(7,15)
elif user_choice == "a":
if drinks_left > 0:
thirst -= 1
drinks_left -= 1
print("You take a drink")
else:
print("You have no drinks left!")
# output conditions
if random.random() < 0.05:
print("You found an oasis!")
drinks_left = 5
thirst = 0
camel_tiredness = 0
if thirst > 6:
print("You died of thirst!")
done = True
elif thirst > 4:
print("You're thirsty!")
if camel_tiredness > 8 and not done:
print("Your camel died")
done = True
elif camel_tiredness > 5 and not done:
print("Your camel is tired")
if miles_travelled - natives_travelled <= 0 and not done:
print("The natives have caught up with you!")
done = True
elif miles_travelled - natives_travelled < 15 and not done:
print("The natives are getting close!")
if miles_travelled >= 200 and not done:
print("You escaped the desert!")
done = True | true |
8aaa87f8e53322e500f0aa00da4eaa198d0d99d3 | hitesh2940/Python_practice | /Assignment 3/Q27_Genrator_Countdown.py | 305 | 4.1875 | 4 | #Write a script to accept a input from user and to generate a list in countdown order till 0 using Generator function.
def countdown(n):
for i in range(n,0,-1):
yield i
n=int(input("enter number you want to Countdown from"))
for i in countdown(n):
print(i) | true |
c58932a792b4f1287fad0478e8b6ea0799f1d6c6 | hitesh2940/Python_practice | /Assignment_2/Q12_calculator.py | 463 | 4.3125 | 4 | #Write a python program to implement a simple calculator to perform operations : +, -, *, /.
a=int(input("enter first number"))
b=int(input("enter Second number"))
print("enter + to add")
print("enter - to subtract")
print("enter / to divide")
print("enter * to multiply")
c=input()
if(c=="+"):
print(a+b)
elif(c=="-"):
print(a-b)
elif(c=="/"):
print(a/b)
elif(c=="*"):
print(a+b)
else:
print("Enter Correct expression") | false |
712919a1ef6b9d98917a2548e36cb3b692657526 | hitesh2940/Python_practice | /Assignment 3/Q22_Max.py | 355 | 4.125 | 4 | #Write a Python script to receive three inputs from user and to find largest no. using lambda function
from functools import reduce
lst=[]
a=int(input("Enter First Number"))
b=int(input("Enter Second Number"))
c=int(input("Enter Third Number"))
lst.append(a)
lst.append(b)
lst.append(c)
d=reduce(lambda x, y: x if (x > y) else y, lst)
print(d) | true |
f5646a4305f28686b26c9d33680d4fdfb8686c18 | olexandra-dmytrenko/KidsLessons2019 | /test.py | 831 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Тест на базові поняття по Python можна пройти тут:
# https://quizlet.com/_6ntfz3
# for i in range(10):
# print(i)
#
# for i in range(1, 10):
# print(i)
#
# for i in range(int(3/2), 10, 3):
# print(i)
#
# while True:
# print("Hi")
#
# while False:
# print("Hi")
#
# i = 0
# while i<10:
# print(i)
# i = 10
# while i >= 10:
# print(i)
# i = 0
# while i <= 10:
# print(i)
# i = i + 1
#
#
# name = "bad guy"
# if (name=="mom"):
# print("I love you mom")
# elif (name=="dad"):
# print("You're the best, dad!")
# else:
# print("I don't know you, " + name)
#
# def output(great):
# print(great)
# output("Hi")
def output(great, name = "body"):
print(great + " " + name)
output("Hi", "Kate")
| false |
9b35f82a7c42d553c8980ee0b4eb6d6da92a7bba | taronegeorage/Pytorch-project | /00_Numpy/4_ Broadcasting.py | 1,951 | 4.59375 | 5 | import numpy as np
print('add a constant vector to each row of a matrix')
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # Create an empty matrix with the same shape as x
# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
y[i, :] = x[i, :] + v
# Now y is the following
# [[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]
print(y)
#when the matrix x is very large
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other
print(vv) # Prints "[[1 0 1]
# [1 0 1]
# [1 0 1]
# [1 0 1]]"
y = x + vv # Add x and vv elementwise
print(y) # Prints "[[ 2 2 4
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
#using broadcasting
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # Add v to each row of x using broadcasting
print(y) # Prints "[[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
print('some broadcasting applications')
# Compute outer product of vectors
v = np.array([1,2,3]) # v has shape (3,)
w = np.array([4,5]) # w has shape (2,)
print(np.reshape(v, (3, 1)) * w)
# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:
# [[2 4 6]
# [5 7 9]]
print(x + v)
# Add a vector to each column of a matrix
print((x.T + w).T)
#or
print(x+np.reshape(w, (2,1)))
print(x * 2)
| true |
f56afcaa1f52048bcbca53d89c9a052637083d09 | colinfrankb/grokking-algorithms | /python/selection_sort.py | 652 | 4.21875 | 4 | def find_smallest(arr):
smallest_value = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest_value:
smallest_value = arr[i]
smallest_index = i
return smallest_index
# return a sorted list
# selection sort will insert the results in a new array
def selection_sort(arr):
result = []
# not looping through each item actually,
# but instead setting up a loop that will loop
# for the same number of items in the array
for i in range(1, len(arr)):
smallest_index = find_smallest(arr)
result.append(arr.pop(smallest_index))
return result
print(selection_sort([5, 3, 6, 2, 100]))
| true |
753ebad319935279127aeffaa27491994cbb0b51 | xueyanjonathan/unit_five | /assignment_5.py | 2,131 | 4.25 | 4 | # Jonathan Lin
# 10/18/2018
# For and While loops
# Using for and while loops to write a function modulling the craps game, and calculate the winning percentage
import random
def roll_a_dice():
"""
This function modules a dice being rolled
The points will be returned.
:return: Points the user gets from rolling the dice.
"""
return random.randint(1, 6)
def craps():
"""
This function modules craps games which are played by the user for multiple times.
The user inputs the times he or she wants to play the game.
The function stores the number of wins among all games played.
The function returns the number of wins and the total number of games.
:return: number of wins and the total number of games.
"""
wins = 0
games = int(input("How many games do you want to play?"))
for x in range(games): # The beginning of the craps game.
dice_one = roll_a_dice()
dice_two = roll_a_dice()
sum_one = dice_one + dice_two
if sum_one == 7 or sum_one == 11: # If the user gets 7 or 11 from the dices he or she rolls, the user wins.
wins = wins + 1 # If the user wins, the total number of wins adds 1.
elif sum_one == 2 or sum_one == 3 or sum_one == 12:
pass # The user loses.
else:
# The user continues rolling until they roll the point(sum_one) again (they win)
# or they roll a 7 (they lose).
while True:
dice_three = roll_a_dice()
dice_four = roll_a_dice()
total = dice_three + dice_four
if total == sum_one:
wins = wins + 1
break # The user wins and stops rolling the dice.
elif total == 7:
break # The user loses and stops rolling the dice.
return wins, games
def main():
wins, games = craps()
loses = games - wins
percentage = wins / games * 100
print("You played", games, "games. You won", wins, "games and lost", loses, "games.")
print("You won", percentage, "percent of the time.")
main()
| true |
797923a5e51298fdfc07e6d47f82d333e4af20aa | xiaomaomi7/DSA | /Data Structure/Recursion/Problems/Flatten.py | 905 | 4.1875 | 4 | '''
Author: Hongxiang Qi
Date: 30/06/2021
Description:
Write a recursive fucntion called flatten which accepts an array of arrays
and returns a new array with all values flattened.
Example:
flatten([1,2,3,[4,5]]) # [1,2,3,4,5]
flatten([1,[2,[3,4],[[5]]]]) # [1,2,3,4,5]
flatten([[1],[2],[3]]) # [1,2,3]
flatten([[[[1],[[[2]]],[[[[[[[3]]]]]]]]]) # [1,2,3]
'''
'''
Apporach:
1. Recursive case - the flow
flatten(arr) = arr[:1] + flatten(arr[1:])
2. Base condition - the stopping criterion
len(arr) <= 0 return arr
len(arr[0]) = list return flatten(arr[0]) + flatten(arr[1:])
3. Unintentional case - the constraint
'''
def flatten(arr):
if len(arr) <= 0:
return arr
elif isinstance(arr[0], list):
return flatten(arr[0]) + flatten(arr[1:])
else:
return arr[:1] + flatten(arr[1:])
array = [1,2,3]
print(flatten(array)) | true |
02fe63c7e1c74ef19be80e209489aadfc7df1c01 | JideMartins/Python-Learnig-Project | /02 Even and odd/even-odd.py | 267 | 4.34375 | 4 | x = int(input())
#conditional statement for checking even or odd number
if x % 2 == 0: #if the remainder of x divided by 2 is equal to zero
print('Number is EVEN')
else: #Else, definitely odd
print('Number is odd')
print('Cheers Mate :)') | true |
ada04be3cfa865118c7fa4fcf27e6ede0cbf2d85 | guyao/leetcode | /median-of-two-sorted-arrays.py | 1,664 | 4.1875 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n
respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m = len(nums1)
n = len(nums2)
if m > n:
m, n, nums1, nums2 = n, m, nums2, nums1
imin, imax = 0, m
half_len = (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i < m and nums2[j - 1] > nums1[i]:
imin = i + 1
elif i > 0 and nums1[i - 1] > nums2[j]:
imax = i - 1
else:
if i == 0:
max_of_left = nums2[j - 1]
elif j == 0:
max_of_left = nums1[i - 1]
else:
max_of_left = max(nums1[i - 1], nums2[j - 1])
if (m + n) % 2 == 1:
return max_of_left
if i == m:
min_of_right = nums2[j]
elif j == n:
min_of_right = nums1[i]
else:
min_of_right = min(nums1[i], nums2[j])
return (max_of_left + min_of_right) / 2.0
# a = [1, 3, 5, 7, 11, 13]
# b = [2, 4, 6, 8, 10]
a = [1, 2]
b = [3, 4]
r = Solution().findMedianSortedArrays(a, b)
| true |
46773a8d2ef82a650bc3c0d6db78b10b0196bb4e | guyao/leetcode | /unique-paths-ii.py | 1,138 | 4.25 | 4 | """
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
"""
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if m == 0:
return 0
# dp = [[ 1 if ((i == m-1) or (j == n -1)) and (obstacleGrid[i][j] != 1) \
# else (0 if obstacleGrid[i][j] == 1 else None) \
# for j in range(n)] \
# for i in range(m)]
dp = [[0 for i in range(n+1)] for j in range(m+1)]
dp[m-1][n] = 1
for i in reversed(range(m)):
for j in reversed(range(n)):
dp[i][j] = dp[i + 1][j] + dp[i][j + 1] if obstacleGrid[i][j] != 1 else 0
for d in dp:
print(d)
return dp[0][0]
r = Solution().uniquePathsWithObstacles(t) | true |
ba8bc4cbfa52b6b5c7794ac57c58c18df83bde39 | guyao/leetcode | /maximum-product-subarray.py | 729 | 4.15625 | 4 | """
Find the contiguous subarray within an array (containing at least one number)
which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxans = nums[0]
maxhere = nums[0]
minhere = nums[0]
for i in nums[1:]:
mx = maxhere
mn = minhere
maxhere = max(mx * i, i, mn * i)
minhere = min(mn * i, i, mx * i)
maxans = max(maxans, maxhere)
return maxans
t1 = [2, 3, -3, 4] # expect 6([2, 3])
t2 = [-4,-3,-2]
t3 = [-1, 0, -1]
| true |
785305327f8fb973a8608a97f790cd9f58ca4d11 | JacksonMcGlothlin/Lab9 | /lab9-85pt.py | 445 | 4.28125 | 4 | ############################################
# #
# 85pt #
# Who has a fever? #
############################################
# Create a for loop that will search through temperatureList
# and create a new list that includes only numbers greater than 100
myList = [102,98,96,101,100,99,103,97,98,105]
for W in myList:
if W > 100:
print W
| true |
281fbd359a0e324298874beb8248cb08c59db334 | karata1975/laboratory | /Матрица яма.py | 779 | 4.3125 | 4 | print('Задача 10. Яма ')
# В одной компьютерной текстовой игре рисуются всяческие элементы ландшафта.
#
# Напишите программу,
# которая получает на вход число N и выводит на экран числа в виде “ямы”:
# Введите число: 5
#
# 5........5
# 54......45
# 543....345
# 5432..2345
# 5432112345
number = int(input('Введите число: '))
print()
for line in range(number):
for left in range(number, number - line - 1, -1):
print(left, end='')
point = 2 * (number - line - 1)
print('.' * point, end='')
for right in range(number - line, number + 1):
print(right, end='')
print()
| false |
28fbef2b1d6eb18172d46daa6378576ba3129f8a | jtschoonhoven/algorithms | /insertion_sort.py | 1,066 | 4.1875 | 4 |
def insertion_sort(int_list):
"""
Sort a list of integers, moving left to right, shifting items left as needed.
Runtime: f(n) = O(n^2)
"""
for idx, item in enumerate(int_list):
if idx == 0:
continue
prev_idx = idx - 1
prev_item = int_list[prev_idx]
# swap item with left neighbor until sorted
while prev_item > item and prev_idx >= 0:
int_list[prev_idx + 1] = prev_item
prev_idx -= 1
prev_item = int_list[prev_idx]
int_list[prev_idx + 1] = item
return int_list
class Tests():
def test_sort__increasing(self):
int_list = [1, 2, 3]
expected = [1, 2, 3]
assert insertion_sort(int_list) == expected
def test_sort__decreasing(self):
int_list = [3, 2, 1]
expected = [1, 2, 3]
assert insertion_sort(int_list) == expected
def test_sort__random(self):
int_list = [2, 1, 9, 7, 7, 1]
expected = [1, 1, 2, 7, 7, 9]
assert insertion_sort(int_list) == expected
| true |
0ce1e055fa11b67c049563a63a28ba2f7a4cf9b2 | a5eeM/PWB | /Ch 01/ex_23_area_regular_polygon.py | 426 | 4.25 | 4 | """
Compute area of a regular Polygon
"""
from math import pi, tan
# Get Input
number_of_sides = int(input("Enter number of sides: "))
length_of_side = float(input("Enter length of a side: "))
# Compute
area = (number_of_sides * length_of_side**2) / (4 * tan(pi / number_of_sides))
# Display
print(f"Area of the regular polygon with {number_of_sides} sides and \
length of each side {length_of_side:.02f} is {area:.02f}")
| true |
27a3d1b4cf1e3b2a41658af6f1a4d138c2a6f984 | a5eeM/PWB | /Ch 01/ex_24_units_time.py | 560 | 4.34375 | 4 | """
Compute seconds
"""
SECONDS_PER_DAY = 86400
SECONDS_PER_HOUR = 3600
SECONDS_PER_MINUTE = 60
# Get Input
days = int(input("Enter number of days: "))
hours = int(input("Enter number of hours: "))
minutes = int(input("Enter number of minutes: "))
seconds = int(input("Enter number of seconds: "))
# Compute
num_sec = (days * SECONDS_PER_DAY) + (hours * SECONDS_PER_HOUR)
num_sec += (minutes * SECONDS_PER_MINUTE) + seconds
# Display
print(f"NUmber of seconds in {days} days, {hours} hours, {minutes} minutes \
and {seconds} seconds are {num_sec} seconds")
| false |
6080d057ebb76dbfaa2cf4c1b07e5f36289f04c9 | a5eeM/PWB | /Ch 01/ex_19_free_fall.py | 312 | 4.125 | 4 | """
speed in free fall
"""
from math import sqrt
ACC_G = 9.8
INITIAL_VELOCITY = 0
# Get Input
height = float(input("Enter drop height: "))
# Compute
velocity = sqrt(INITIAL_VELOCITY**2 + 2 * ACC_G* height)
# Display
print(f"Velocity when the object hits the ground is {velocity:.02f} \
meters per second")
| true |
b8b41d8f5d75a90a2d0952d77196b2815bc0b531 | a5eeM/PWB | /Ch 02/ex_42_frequency_to_note.py | 902 | 4.375 | 4 | """
Frequency to Note
"""
# Get Input
frequency = float(input("Enter frequency(in Hz): "))
threshold = 1
# Compute
if frequency >= 261.63 - threshold and frequency <= 261.63 + threshold:
note = "C4"
elif frequency >= 293.66 - threshold and frequency <= 293.66 + threshold:
note = "D4"
elif frequency >= 329.63 - threshold and frequency <= 329.63 + threshold:
note = "E4"
elif frequency >= 349.23 - threshold and frequency <= 349.23 + threshold:
note = "F4"
elif frequency >= 392.00 - threshold and frequency <= 392.00 + threshold:
note = "G4"
elif frequency >= 440.00 - threshold and frequency <= 440.00 + threshold:
note = "A4"
elif frequency >= 493.88 - threshold and frequency <= 493.88 + threshold:
note = "B4"
else:
note = ""
# Display
if note:
print(f"{frequency} belongs to {note} note.")
else:
print("Frequency does not correspond to a known note!!")
| true |
dd63864423c07b8c9ced0a5a1c5a0ed3b21e9b58 | a5eeM/PWB | /Ch 01/ex_15_distance_units.py | 495 | 4.3125 | 4 | """
Compute distance in inches, yards and miles
"""
INCHES_PER_FOOT = 12
YARDS_PER_FOOT = 0.33
MILES_PER_FOOT = 0.000189394
print("Enter distance in feet:")
# Get Input
feet = float(input("feet: "))
# Compute
distance_inches = feet * INCHES_PER_FOOT
distance_yards = feet * YARDS_PER_FOOT
distance_miles = feet * MILES_PER_FOOT
# Display
print(f"You travelled a distance of {feet:.0f} feet, or {distance_inches:.0f} inches,\
or {distance_yards:.02f} yards, or {distance_miles:.02f} miles.")
| false |
466f357a1caac38eda185693f2dea5b6a030d2db | a5eeM/PWB | /Ch 02/ex_51_letter_grade_points.py | 916 | 4.46875 | 4 | """
Determine grade points from grade
"""
# Get Input
grade_letter = input("Enter grade: ")
grade_points = None
# Compute
if grade_letter == "A+" or grade_letter == "A":
grade_points = 4.0
elif grade_letter == "A-":
grade_points = 3.7
elif grade_letter == "B+":
grade_points = 3.3
elif grade_letter == "B":
grade_points = 3.0
elif grade_letter == "B-":
grade_points = 2.7
elif grade_letter == "C+":
grade_points = 2.3
elif grade_letter == "C":
grade_points = 2.0
elif grade_letter == "C-":
grade_points = 1.7
elif grade_letter == "D+":
grade_points = 1.3
elif grade_letter == "D":
grade_points = 1.0
elif grade_letter == "F":
grade_points = 0
else:
grade_points = "INVALID"
# Display
if grade_points == "INVALID":
print(f"{grade_letter} corresponds to {grade_points} grade points!")
else:
print(f"{grade_letter} corresponds to {grade_points} grade points!")
| false |
60dd834b0732809283d823156313efaec7f491fc | Shubhamg2595/RESTfulAPI-using-FLask | /SQLite3test.py | 1,448 | 4.5 | 4 | # import sqlite3
#
# # creating a connection
#
# connection=sqlite3.connect('data.db')
# #we are cimple creating a file called data.db that we will connect all the required data to connect to our sqlite DB.
#
# cursor=connection.cursor()
#
# #creating a new table in sqlite
#
# create_table="create table users(id int,username text,password text)"
# # cursor.execute(create_table)
#
#
# "once you run this script, a data.db file will be created. ignore it for now"
# 'comment the create table part,once you have created the table'
#
# 'lets create a new user'
#
# # user=(1,'shubham',70422) #simple tuple containing user data
# # insert_query="insert into users values (? ,? ,? )"
# # cursor.execute(insert_query,user)
#
# 'also commit your changes, when inserting , deleting or updating' \
#
# # connection.commit()
# # connection.close()
#
# 'after running the insert script,go and check data.db'
#
# 'HOW TO CREATE MULTIPLE USERS IN ONE GO'
# '''
# users_list=[(2,'ayu',99906),
# (3,'sam',82929)]
# insert_query_for_many_users="insert into users values(?,?,?)"
#
# cursor.executemany(insert_query_for_many_users,users_list)
#
# connection.commit()
# connection.close()
# '''
#
# 'HOW TO FETCH DATA FROM TABLES'
# select_query="select * from users"
# for row in cursor.execute(select_query):
# print(row)
#
# # select_query_using_id="select username from users"
# # for row in cursor.execute(select_query_using_id):
# # print(row) | true |
e936cd98007617119d201a8b3dd7af3d58c90dee | xinyiz1019/python-exercises | /pe03.py | 1,369 | 4.3125 | 4 | '''
Exercise 3
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
2. Write this in one line of Python.
3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
'''
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#i=0
print('a has',len(a),'elements')
#for i in range(len(a)) :
# if int(a[i]) < 5:
for i in a:
if i<5:
print(i)
# i=i+1
# else:
# i=i+1
#'for i in a' can directly represent the elements in a
#usage of 'for' is different from C language: for ... in ...
#extras
a = [1, 101, 2, 31, 5, -8, 13, 21, 6, 55, 89]
b=[]
print('a has',len(a),'elements')
for i in a:
if i<10:
b.append(i)
print('b has',len(b),'elements','\n',b)
#to define an empty array: b=[]
#array.append(sth u want to add)
num=int(input('Enter a number: '))
c=[]
for i in a:
if i<num:
c.append(i)
d=sorted(c)
print(d)
#c.xxx只用于对array 'c' 进行操作,比如c.sort()对c进行排序,但不能作为函数引用,如果写成d=c.sort(); print(d)会出错 | true |
b91cae5cf3ecf2165de0e8eeba1000f3ad6a54de | xinyiz1019/python-exercises | /pe13.py | 705 | 4.53125 | 5 | '''
Exercise 13
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
'''
def Fib(a):
fib1=1
fib2=1
print(fib1);print(fib2)
for n in range(0,a):
temp=fib2
fib2=fib1+fib2
fib1=temp
print(fib2)
a=int(input('How many Fibonnaci numbers do you want? '))
Fib(a) | true |
4ec29128fd8e5ffec10711b491342b2fb078b31b | ifthikhan/Challenges | /count-num-primes.py | 763 | 4.375 | 4 | #!/usr/bin/env python
"""
Count the number of prime numbers below a given number. This uses the
sieve of eratosthenes algorithm (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
"""
import sys
def prime_numbers_count(max_number):
prime_list = [True] * max_number
prime_list[0] = prime_list[1] = False
primes = []
for stride, isPrime in enumerate(prime_list):
if isPrime:
primes.append(stride)
for i in xrange(stride, max_number, stride):
prime_list[i] = False
return primes
if __name__ == '__main__':
number = int(sys.argv[1])
result = prime_numbers_count(number)
print "The number of primes below %s is %s" % (number, len(result))
#print "The primes are: %s" % result
| true |
6a3357987b7048eb6431d922f23ac13f68b24ed2 | NanaAY/codecademy | /simple projects/gradebook.py | 1,384 | 4.4375 | 4 | #Nana Osei Asiedu Yirenkyi
#Summer 2018
#In this project, you will act as a student and create a gradebook to keep track of some #of the subjects you've taken and grades you have received in them. To complete the #project, you will need to understand how to create and combine lists, and how to add #elements.
#creates a list of pairs last semester subjects and the corresponding grades
last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
#creates a list of this semester's subjects
subjects = ['physics', 'calculus', 'poetry', 'history']
#creates a list of this semester's subjects
grades = [98, 97, 85, 88]
#adds computer science to the list of subjects
subjects.append('computer science')
#adds the computer science grade to the list of grades
grades.append(100)
#creates a list called 'gradebook' which pairs this semester's subjects with their corresponding grades
gradebook = list(zip(subjects, grades))
#adds the subject visual arts and its corresponding grade to the gradebook list
gradebook.append(('visual arts', 93))
#prints the list of this semesters subjects and corresponding grades
print(gradebook)
#combines the list of this semester's subjects and grades to that of last semester
full_gradebook = last_semester_gradebook + gradebook
#prints the combined list of grades and subjects from both semesters
print('\n',full_gradebook)
| true |
cacbbcf41303d3fb1951b5c8ababf1a11487766c | GhulamMustafaGM/PythonChallenges | /GuessMyNumberApp.py | 1,220 | 4.21875 | 4 | # Conditionals Challenge 19: Guess My Number App
import random
print("\nWelcome to the Guess My Number App")
# Get user input
name = input("\nHello! What is your name: ").title().strip()
# Pick a random integer from 1 to 20
print("Well " + name + ", I am thinking of a number between 1 and 20.")
number = random.randint(1,20)
# Guess the number 5 times
for guess_num in range(5):
guess = int(input("\nTake a guess: "))
if guess < number:
print("Your guess is too low.\n")
elif guess > number:
print("Your guess is too high.\n")
else:
break
# The game is done, recap winning or loosing
if guess == number:
print("\nGood job, " + name + "! You guessed my number in " + str(guess_num + 1) + " guesses!")
else:
print("\nGame Over. The number I was thinking of was " + str(number) + ".\n")
# Program output
# Welcome to the Guess My Number App
# Hello! What is your name: Issac
# Well Issac, I am thinking of a number between 1 and 20.
# Take a guess: 17
# Your guess is too high.
# Game Over. The number I was thinking of was 1.
# Take a guess: 13
# Your guess is too high.
# Game Over. The number I was thinking of was 1.
# Take a guess: 1 | true |
4bfa10c62e3b627ad7b48608f1a16243ff4616db | amanpuranik/ds-algos | /ds-algos/bubble_sort.py | 644 | 4.1875 | 4 | #look at first 2 elements, if first is greater than the second, swap
#move on to the next elements and repeat
class Bubble_sort:
def bubble_sort(list):
size = len(list)
for i in range(size-1):
for i in range(size-1): #iterate through indices
if list[i] > list[i+1]:
tmp = list[i] #store this variable at this indice
list[i] = list[i+1]
list[i+1]=tmp #swap the variables
if __name__ == '__main__':
list = [5,4,3,6,8,1,2,4,9,10]
bs = Bubble_sort
bs.bubble_sort(list)
print(list) #the list will come back sorted
| true |
b272e3bcf355bb58606bbbf58ad89d4655e81d37 | jmat94/PythonProgramming | /SortAndFindDifferenceOfMinAndMax.py | 947 | 4.3125 | 4 | """
This program is used to find the difference between the min and max number(without using the inbuilt functions) after sorting the list
"""
# Define the function
def sort_and_find_big_diff(nums):
# Create min and max variables
min_num = nums[0]
max_num = nums[0]
# Sort the list
for i in range(len(nums) - 1):
for j in range(len(nums) - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
print("The sorted list is: {}".format(nums))
# Find the minimum number
for i in nums:
if i < min_num:
min_num = i
# Find the max number
for i in nums:
if i > max_num:
max_num = i
# Find the difference between the min and max number
print("The difference between the largest and smallest number is: {}".format(max_num - min_num))
sort_and_find_big_diff(nums=[10, 3, 5, 6])
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.