blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f3d0c405d9c2efc27f90738fe3b46e7837dcf8e6 | manishhedau/ineuron-assignment | /Assignment-2/1.py | 298 | 4.1875 | 4 | # 1. Create the below pattern using nested for loop in Python.
"""
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
m = int(input('Enter the number of columns : '))
for i in range(1):
for j in range(m):
print('* '*j)
for k in range(m):
print('* '*(m-k-2))
print() | false |
5a69d46e14b7668fe2a346b53af0d969578a4345 | KarlYYY/LearnPython | /Python demo/test2.py | 500 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
list1=['Alice','Bob','Chris','Dean'] # list
print('The first list element is %s'%list1[0])
print('The last list element is %s'%list1[-1])
list1.pop()
print('The last list element is %s'%list1[-1])
list1.append('Eric')
print('The last list element is %s'%list1[-1])
tuple1=('A','B','C','D') #tuple
tuple2=(1,)
print('The first tuple element is %s'%tuple1[0])
tuple3=(1,'s',[10,20])
tuple3[2][0]=30
print('The tuple is %d'%tuple3[2][0])
name = input()
| false |
4266fac216ad1d316fc296b75728ee21f701d3c9 | Fhernd/Python-CursoV2 | /parte11/11.1_intro_funciones.py | 2,212 | 4.59375 | 5 | # Introducción a las funciones - Unidades de reutilización y encapsulación de información:
# 1. Creación de una función:
print('1. Creación de una función:')
def sumar(numero_1, numero_2):
"""
Suma dos números (sean enteros o punto flotante).
Parameters:
numero_1: primer valor a sumar.
numero_2: segundo valor a sumar.
Returns:
Suma de dos números (enteros o reales).
"""
suma = numero_1 + numero_2
return suma
x = 2
y = 3
resultado = sumar(x, y)
print('El resultado de sumar {} y {} es igual a {}.'.format(x, y, resultado))
print()
# 2. Invocación de una función:
resultado = sumar(2, 3)
print('El resultado de sumar {} y {} es igual a {}.'.format(x, y, resultado))
print()
# 3. Obtener documentación/ayuda de una función:
print('3. Obtener documentación/ayuda de una función:')
print()
help(sumar)
print()
help(print)
print()
# 4. Creación de una función para alternar los valores de dos variables:
print('4. Creación de una función para intercambiar los valores de dos variables:')
# a = 2, b = 3
# a = 3, b = 2
# auxiliar = 2
# a = 3
# b = 2
def intercambiar_valores(a, b):
"""
Intercambia los valores de dos variables.
Parameters:
a: primer valor.
b: segundo valor.
Returns:
Los valores de a y b intercambiados.
"""
auxiliar = a
a = b
b = auxiliar
return a, b
x = 2
b = 3
print('Valores de las variables `x` e `y` antes del intercambio:')
print(f'x = {x} - y = {y}')
resultado = intercambiar_valores(x, b)
x = resultado[0]
y = resultado[1]
print('Valores de las variables `x` e `y` después del intercambio:')
print(f'x = {x} - y = {y}')
print()
# 5. Uso de funcionalidad que provee en su defecto (incorporado) el lenguaje de programación:
print('5. Uso de funcionalidad que provee en su defecto (incorporado) el lenguaje de programación:')
x = 2
y = 3
resultado = x + y
print('El resultado de sumar {} y {} es igual a {}.'.format(x, y, resultado))
print()
print('Valores de las variables `x` e `y` antes del intercambio:')
print(f'x = {x} - y = {y}')
x, y = y, x
print('Valores de las variables `x` e `y` antes del intercambio:')
print(f'x = {x} - y = {y}')
| false |
ea222b881da640760d645bdaf33788f89d74aade | Fhernd/Python-CursoV2 | /parte11/ex11.03_producto_lista_tupla.py | 1,646 | 4.21875 | 4 | # Ejercicio 11.3: Crear una función para multiplicar todos los números en una lista o tupla.
def multiplicar(valores):
"""
Multiplica el conjunto o grupo de valores de una lista o tupla:
Parameters:
valores: Lista o tupla con los valores a multiplicar.
Returns:
Multiplicar de los valores en la lista o tupla.
"""
if isinstance(valores, (list, tuple)):
if len(valores):
acumulador = 1
for v in valores:
acumulador *= v
return acumulador
else:
return None
else:
raise ValueError('Ha pasado un argumento que ni es lista ni tupla.')
edades = [19, 29, 31, 21]
try:
resultado = multiplicar(edades)
print('El resultado de multiplicar las edades {} es igual a {}.'.format(edades, resultado))
except ValueError as e:
print('ERROR:', e)
print()
precios = (999.9, 59.9, 27.5)
try:
resultado = multiplicar(precios)
print('El resultado de multiplicar los precios {} es igual a {}.'.format(precios, resultado))
except ValueError as e:
print('ERROR:', e)
print()
numeros = 1000
try:
resultado = multiplicar(numeros)
print('El resultado de multiplicar los numeros {} es igual a {}.'.format(numeros, resultado))
except ValueError as e:
print('ERROR:', e)
print()
numeros = []
try:
resultado = multiplicar(numeros)
if resultado:
print('El resultado de multiplicar los numeros {} es igual a {}.'.format(numeros, resultado))
else:
print('No ha proveído datos para la lista o tupla. Está vacía.')
except ValueError as e:
print('ERROR:', e)
| false |
3956bde95df92f0d42cfe5b3971f0ec8be4b61a1 | momentum-cohort-2018-10/w1d2-house-hunting-meagabeth | /house_hunting.py | 611 | 4.21875 | 4 | annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
# portion_down_payment = total_cost*.25
# current_savings = current_savings + current_savings*r/12
num_of_months = 1
portion_down_payment = total_cost*.25
current_savings = 0
r = .04
while current_savings < portion_down_payment:
num_of_months += 1
current_savings = current_savings + current_savings*r/12 + (annual_salary/12*portion_saved)
print("Number of months: " + str(num_of_months)) | true |
309e576a8590e23e5e56f91b57385772f2466526 | mddeloarhosen68/Swap-Two-Variable | /swap.py | 290 | 4.25 | 4 | #Ex:1
a = 5
b = 6
temp = a
a = b
b = temp
print(a)
print(b)
#Ex:2
a = 5
b = 6
a = a + b
b = a - b
a = a - b
print(a)
print(b)
#Ex:3
a = 5
b = 6
a = a ^ b
b = a ^ b
a = a ^ b
print(a)
print(b)
#Ex:4
a = 5
b = 6
a,b = b,a
print(a)
print(b) | false |
bea263655e559f8f6a6e699a1483cf2263e3b2cb | spreadmesh/fastcampus_wps2 | /DAY_10/homework_2.py | 1,090 | 4.125 | 4 | ## 2. replace 함수의 구현 - 문자열을 치환하는 Python 내장 함수인 replace 를 직접 구현하세요.
"""
해결 방법
1. while문으로 직접 위치제어를 하자
2. 비교할 위치의 문자 갯수가 다르면 곤란한데 그냥 반복문이 끝나고 나머지 부분을 붙이는 형태로 정리
"""
def word_replace(string, before, after):
output=""
index=0
while index < len(string)-len(before)+1:
if before != string[0+index:len(before)+index]:
output += string[index]
else:
output += after
index += len(before)-1
index += 1
output += string[index:]
print(output)
print('''input => word_replace("패스트캠퍼스", "패스트", "Fast")''')
print("output => ", end="")
word_replace("패스트캠퍼스", "패스트", "fast")
print('''\ninput => word_replace("웹 프로그래밍 스쿨과 데이터 사이언스 스쿨", "스쿨", "SCHOOL")''')
print("output => ", end="")
word_replace("웹 프로그래밍 스쿨과 데이터 사이언스 스쿨", "스쿨", "SCHOOL")
| false |
a66060ca33414a76e51665db90a2aaea6c00bc63 | williechow97/String-Lists---Palindrome | /String List -- Palinedrome.py | 1,880 | 4.21875 | 4 | # Palindrome
# Ask the user for a string and print out whether this string
# is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
'''
fix to catch numbers
make so ignores spaces and exclamation
best to separate string into list of char and check conditions and create the reverse string
'''
SYMBOLS = ['!',',' '.', '?', '@', '#', '$', '%', '&', '*', '[', ']', '{', '}'] # Global variable of a list of special characters
def Palindrome(string):
'''@param: string
check to see if string is palindrome or not
'''
revString = '' # empty that will hold the reverse string
newString = '' # empty string that will hold the string without spaces
for i in string:
if not i.isspace() and i not in SYMBOLS: #disregards spaces and special symbols
newString = newString + i # concatenate string to have same chars as string parameter
revString = i + revString # concatenate char to the begin of revString
if revString.lower() == newString.lower(): # compare string(non-case sentitive)
print(string, "is a palindrome")
else:
print(string, "is not a palindrome")
def main():
again = True
userInput = input("Enter a string: ")
while again:
if not userInput.isdigit(): # don't allow only digits
if userInput not in SYMBOLS: # don't allow symbols
Palindrome(userInput)
again = False # break out of while loop
else: # continue asking user for correct input
print('No special symbols')
userInput = input('Enter a string: ')
else: # continue asking user for correct input
print('Please enter only characters:')
userInput = input('Enter a string: ')
main()
| true |
8dc25f4ce9c7d748f487d04975862f4a25d5496c | jjmanjarin/MathNStats | /_build/jupyter_execute/03_Graphs_with_Pandas.py | 2,954 | 4.375 | 4 | # Graphics with Pandas
We have seen how to use **matplotlib** to generate the basic graphs we may need in our statistical analysis. However, since the main data structure we are going to work with is the data frame which is defined in **pandas**, we may want to fully use this library to make the graphs.
If we use this pandas approach, we must understand that each of the graphs are just methods associated with the data frame structure and then they are called directly from the data frame. Let's see it.
## 1.- The Data
We already know how to connect to our drive, then let's load a data set from there and work with it
from google.colab import drive
drive.mount('mydrive')
now we load the dataset
import pandas as pd
remember that we need the pandas library!
mydf = pd.read_csv("/content/mydrive/My Drive/Statistics and Data Analysis - 2019/Data Sets/forestarea.csv")
mydf = pd.read_csv("/content/sample_data/california_housing_train.csv")
mydf.head()
## 2.- Histograms
Before going on, let's set the seaborn style for all our plots
import matplotlib.pyplot as plt
plt.style.use("seaborn")
Let's take as variable `total_rooms`, then its histogram is
mydf["total_rooms"].hist(color = "lightgreen", ec = "darkgreen")
plt.xlabel("Total Rooms")
plt.ylabel("Frequency")
plt.show()
since we are using matplotlib, everything we know about it can be used in these plots
## 3.- Boxplots
Boxplots have a particularity: the function does not accept a Series format, which means that we cannot use the single bracket notation (go back to the selection in pandas section) and must use double brackets
mydf[["total_rooms"]].boxplot(patch_artist = True,
showmeans = True,
widths = 0.6,
flierprops = dict(marker = 'o',
markerfacecolor = 'red'))
## 4.- Bar Plots
Consider the same example we had in matplotlib in which we had a dataframe grouped by gender and the activity level, the dataframe was (since it was randomly generated without a seed the values may change)
df = pd.DataFrame({"females": [69, 81, 85],
"males": [94, 95, 76]},
index = ["low", "mid", "high"])
df
For a data frame we can call directly to the **plot** function and then the corresponding graph, in this case the **bar**. Note that this can also be done using `plot(kind = "bar")`
df.plot.bar()
plt.xticks(rotation = 0)
plt.xlabel("Activity Level")
plt.ylabel("Frequency")
plt.show()
you can go back to matplotlib and see how pandas simplfies this considerably
## 5.- Scatter Plots
Just as we have done with the bar plots, the plot function can be used to call for other graphs. Of particular importance is the scatterplot which can be easily found as
mydf.plot.scatter("median_income", "median_house_value")
plt.show()
and now we are free to use all the layers we know from matplotlib | true |
b244c6a422b05a1ea159cdbc5cb207f23c793e51 | pereiradaniel/python_experiments | /raw_input/greeting.py | 441 | 4.15625 | 4 | # Prompt user for name
name = input("What is your name?: ")
# Print name if name is greater than 0 and consists of alphabetic characters
if len(name) > 0 and name.isalpha():
print ("Hello " + name)
# Print everything from the second letter onward
first = name[0]
new_word = name + first + "ay"
new_word = new_word[1:len(new_word)]
print ("Your name in pig latin is: " + new_word)
else:
print("Invalid input")
| true |
f1efa39e2e495d688f5737ce11ee14be81256a4c | c34809368/260201053 | /lab8/example5.py | 607 | 4.28125 | 4 | def password_checker(password):
level=0
if (len(password)<8) or (" " in password):
print("It is not valid")
return level
else:
for char in password:
if char.isdigit():
level+=1
break
for char in password:
if char.isalpha():
level+=1
break
for char in password:
if not char.isnumeric() and not char.isdigit() and char!=" ":
level+=1
break
return level
def main():
password=input("please enter a password:")
level=password_checker(password)
print("Security level of the entered password is:", level)
main() | true |
3df662f8b4851d35f4af76d83f49e05e71711efe | iguerrexo/111 | /111/intro.py | 871 | 4.15625 | 4 | print('Hello form Python')
last_name = 'Guerrero'
age = 20
found = False
total = 13.44
print(last_name)
print("Nora"+last_name)
print(age + age)
#this will give an error
print(last_name + str(age))
print (age + total)
#math
print('----------------------------------')
print(1 + 1)
print(42 - 21)
print(10 * 8)
print(101 - 3)
print(20 % 2)
#if
print('---------------------------------')
if(age < 99):
print('You Are still Young')
print('this is inside of the if')
print('this is outside of the if')
if(total > 100):
print("you will get free shipping")
print('')
elif(total > 50):
print("pay half of the shipping")
else:
print("you need to pay for shipping")
def say_hi():
print('hi from a function')
print('Still inside a function')
say_hi() # calling the fn
say_hi() | true |
f55009a4529b27991dda38b278478ce5aae01d3c | takashimokobe/algorithms | /lab3/array_list.py | 2,678 | 4.3125 | 4 | import unittest
from sys import argv
# A List is one of
# None
# A reference to an arrary and a int representing size
class List:
def __init__(self, list, size):
self.list = list
self.size = size
def __eq__(self, other):
return (type(other) == List
and self.list == other.list
and self.size == other.size
)
def __repr__(self):
return "List (%r, %r)" % (self.list, self.size)
# no arguments -> None
# this function returns an empty list.
def empty_list():
return List([], 0)
# list int value -> list
# puts the value at the index specified in your list
def add(alist, index, value):
if (index < 0 or index > length(alist)):
raise IndexError
else:
newList = List([None] * (length(alist) + 1), 0)
if index != 0:
for i in range(index):
newList.list[i] = alist.list[i]
newList.size += 1
newList.list[index] = value
newList.size += 1
for i in range(index, length(alist)):
newList.list[i + 1] = alist.list[i]
newList.size += 1
else:
newList.list[0] = value
newList.size += 1
for i in range(1, length(alist) + 1):
newList.list[i] = alist.list[i - 1]
newList.size += 1
return newList
# list -> int
# returns the number of elements in the list
def length(alist):
if (alist == None):
return 0
else:
return alist.size
# list int -> value
# returns the value at the index position in the list
def get(alist, index):
if (index < 0 or index > length(alist)):
raise IndexError
else:
return alist.list[index]
# list int value -> list
# replaces the element of the index postion specified with the given value
def set(alist, index, value):
if (index < 0 or index > length(alist)):
raise IndexError
else:
newList = List([None] * length(alist), 0)
for i in range(list.size):
if i == index:
newList.list[i] = value
else:
newList.list[i] = alist.list[i]
newList.size += 1
return newList
# list int - > list
# removes the value at the position index and returns a tuple of deleted element and rest of the list
def remove(alist, index):
if (index < 0 or index > length(list)):
raise IndexError
else:
if (index == length(alist) - 1):
newList = List([None] * (length(alist) - 1), 0)
for i in range(length(alist) - 1):
newList.list[i] = list.list[i]
newList.size += 1
else:
newList = List([None] * length(alist - 1), 0)
for i in range(length(alist) - 1):
if i < index:
newList.list[i] = alist.list[i]
else:
newList.list[i] = alist.list[i + 1]
newList.size += 1
return (alist.list[index], newList)
| true |
b6ff2566f5eef857b5d4687db07366a1ac0a0edc | poonam5248/MachineLearning | /Day1____14-June-2019/4.TypeCasting.py | 407 | 4.28125 | 4 | #TYPE CASTING
#TYPE CASTING COMMANDS
## int
## str
## chr
## float
## bin
## hex
## ord(original data of any letter)
## ------------
## ------------
## ------------
## ------------
a="Hello "
b=100
c=a+str(b)
print(c)
a='100'
b=5
c=int(a)+b
print(c)
a=65
print("Char of 'a' is: ",chr(a))
print("Original data of 'a' is: ",ord('A'))
print("Binary Number of 'a' is: ",bin(a))
| false |
be02dcd7076cb523940bfa85edf459f657cb358a | poonam5248/MachineLearning | /Day2____15-June-2019/1.Dictionary.py | 635 | 4.3125 | 4 | #DICTIONARY
# Dictionary is a Key-Value Pair Collection
dict={'abc':1000,10:123,1.5:'Hello','xyz':15,15.8:10,'m':'a','ab':'xyz'}
print(dict)
print(dict['abc'])
# print(dict[1]) It will Show Error Because there is no index postions in dictionary
print(dict[1.5])
##b=dict.values
##c=dict.keys
##print("Values are:", b)
##print("Keys are:", c)
w={'abc':1000,'1000':[{'a':(1,2,6,9)}]}
print(w)
print(w['abc'])
print(w['1000'][0]['a'][1:3])
##w['1000'][0]['a'][1:3]=(123,100) #Show Error Because tuple can't change
##print(w)
q={'abc':1000,'1000':[{'a':[1,2,6,9]}]}
print("q=", q)
q['1000'][0]['a'][1:3]=[123,100]
print(q)
| false |
4706aa47eeac1008a1289a7a9958364916fe43e0 | shrikantpadhy18/interview-techdev-guide | /Algorithms/Searching & Sorting/Insertion Sort/InsertionSort.py | 1,088 | 4.15625 | 4 | class InsertionSort():
def __init__(self, list_to_sort):
self.sorted_list = list_to_sort
self.__sort()
def __sort(self):
i = 1
while i < len(self.sorted_list):
x = self.sorted_list[i]
j = i - 1
while j >= 0 and self.sorted_list[j] > x:
self.sorted_list[j + 1] = self.sorted_list[j]
j -= 1
self.sorted_list[j + 1] = x
i += 1
def add_element(self, element): # can be used for online sorting: keep list sorted by adding elements one by one.
j = len(self.sorted_list) - 1
while j >= 0 and self.sorted_list[j] > element:
j -= 1
self.sorted_list.insert(j + 1, element)
@staticmethod
def sort(list_to_sort): # inplace sort
InsertionSort(list_to_sort)
def main():
print("Enter list elements, seperated by space \" \":")
numbers = [int(x) for x in input().strip().split(' ')]
InsertionSort.sort(numbers)
print(numbers)
if __name__ == '__main__':
main() | true |
0d94ee7adf61e4e1c20935b03cc42db3f408698e | quantacake/Library | /backend.py | 2,430 | 4.1875 | 4 | # Archive Application (Backend)
import sqlite3
"""
Backend:
Attach functions to all objects (e.g. listbox, butotns,
entries, etc) which will retreive data from an
SQLite database.
"""
class Database:
# initializer / constructor
# this gets executed when you call an instance of the class.
# it is called in frontend.py as database=Database()
def __init__(self,db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
self.conn.commit()
# user enters title, author, year, isbn
def insert(self, title, author, year, isbn):
# do not have to pass incremental values manually like id.
# only add id to string.
self.cur.execute("INSERT INTO book VALUES(Null,?,?,?,?)",(title,author,year,isbn))
self.conn.commit()
# fetch all rows of the table.
def view(self):
self.cur.execute("SELECT * FROM book")
rows=self.cur.fetchall()
return rows
# user enter title, author, year, or isbn
# pass empty string as default values if they do not exist.
# now the sql statement will search for an empty string along with values.
def search(self,title="",author="",year="",isbn=""):
self.cur.execute("SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?",(title,author,year,isbn))
rows=self.cur.fetchall()
return rows
# user first searches in database, then finds the ID of the book they want to delete.
def delete(self,id):
# column name is after the WHERE. paramter is the id user inputs
self.cur.execute("DELETE FROM book WHERE id=?",(id,))
self.conn.commit()
# allow user to update the entry widgets(Title, Author, Year, ISBN)
# select entry from widget box then refer to the id.
# update tables with these new values where id = this
def update(self,id,title,author,year,isbn):
self.cur.execute("UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?",(title,author,year,isbn,id))
self.conn.commit()
# before the script exits, this method will be executed
# in order to close the connection.
def __del__(self):
self.conn.close()
print('database has been closed')
| true |
0ad89a8b136632ad52a1fdd383702bf6642a14c5 | AAJAL/Simple-Python-Programs | /alphabet.py | 525 | 4.40625 | 4 |
def display_alphabet_by_code(preference):
if preference == "lowercase":
number = 97
for i in range(26):
print(chr(number))
number += 1
elif preference == "uppercase":
number = 65
for i in range(26):
print(chr(number))
number += 1
else:
print("Preference must be uppercase or lowercase")
print("Uppercase:")
display_alphabet_by_code("uppercase")
print()
print("Lowercase:")
display_alphabet_by_code("lowercase")
print() | true |
16b6c2d14666968fe3be9d1f6f167c65b5637887 | aadithpm/code-a-day | /py/Isograms.py | 479 | 4.15625 | 4 | """
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
"""
def is_isogram(string):
string = string.lower()
return len(set(string)) == len(list(string))
| true |
f77bb1ffce190ffa43009580fa1374d3bf911776 | UmbertoFasci/CodewarsWriteups | /Give_me_a_diamond.py | 1,388 | 4.46875 | 4 | #! /usr/bin/python3
"""
Jamie is a programmer, and James' girlfriend.
She likes diamonds, and wants a diamond
string from James. Since James doesn't know
how to make this happen, he needs your help.
You need to return a string that looks like a
diamond shape when printed on the screen,
using asterisk(*) characters. Trailing spaces
should be removed, and every line must be
terminated with a newline character( \n).
Return null/nil/None/... if the input is an
even number or negative, as it is not possible
to print a diamond of even or negative size.
n = 3
*
***
*
n = 5
*
***
*****
***
*
"""
"""
THOUGHTS:
n corresponds to the number of rows associated with
the diamond shape. n also corresponds to the number
of asterisks of the center row. The spaces required
at the beginning and end of the shape has the property
(n-1)/2.
"""
def diamond(n):
if n <1 or not n % 2: # this satifies the requirement for shapes of odd size.
return null
r = ''
for i in range(n): # loop necessary to build the asterisks for the line.
asterisk = '*'*(i * 2 + 1) if i <= n/2 else '*'*((n-i) * 2 - 1)
r += ' ' * int((n - len(asterisk)) / 2) + asterisk + '\n' # necessary for adding the next row of the shape.
return r
print(diamond(5))
| true |
aa8a549d51c9e261e32e905417ddae45cb56dc5a | yuliaxxx/homework_python | /easy/two_numbers.py | 355 | 4.21875 | 4 | first = int(input("Enter first number:"))
second = int(input("Enter second number:"))
operation = input("Enter operator:")
if operation == '+':
print(first+second)
elif operation == '-':
print(first-second)
elif operation == '*':
print(first*second)
elif operation == '/':
print(first/second)
else:
print("Wrong operator! try again")
| false |
c1452de1dde5bbe0dfe70fe1a1b5b50dcab271b0 | neeleshcrasto/Assignments | /MIT/assn1.py | 1,244 | 4.125 | 4 |
from math import *
# ----------------------------#
## COMPUTING PRIMES NUMBERS ##
# ----------------------------#
# function to compute product of primes
product = log(2)
def prdtprime (prdt):
global product
product = product + log(prdt)
return product
# function to check whether a number is prime
def pcheck(prim):
i = 2
global x
x = 0
while i < (prim/2):
check = prim%i
if check == 0:
x = 2
return None
elif check != 0:
i = i + 1
# print(prim,'is a prime number')
n = int(input('Enter which n(th) Prime number you want: '))
# for first prime number
if n == 1:
prime = 2
print ('The no.',n,'prime number is', prime)
# Generate number
if n > 1:
nos = 1
i = 2
iter = 1
while iter != n:
nos = nos + 2
pcheck(nos)
if x == 2:
pass
else:
iter = iter + 1
prdtprime(nos)
# print(nos,'is a prime number')
print('The number',n,'prime number is ',nos)
# ----------------------------#
## PRODUCT OF THE PRIMES ##
# ----------------------------#
print('The product is ', product)
# check if number is prime & print it out | false |
132d82ea41a401eac464184e1c8045aa20df014b | neeleshcrasto/Assignments | /100Plus/quest8.py | 458 | 4.28125 | 4 | #-------------------------------------------------------------------------------------#
## This accepts a comma separated sequence of words as input ##
## Then prints the words in a comma-separated sequence after sorting them alphabetically ##
#-------------------------------------------------------------------------------------#
words = [str(x) for x in input('Enter list of words separated by commas: ').split(',')]
words.sort()
print(','.join(words))
| true |
4d7998320a4e5dae8ecff7148d07892f1e59c774 | neeleshcrasto/Assignments | /100Plus/quest4.py | 378 | 4.28125 | 4 | #---------------------------------------------------------------------------------#
## Accept a string of comma separated values and print out as list & tuple ##
#---------------------------------------------------------------------------------#
values = input('Enter values separated by comma\n')
liszt = values.split(",")
toppel = tuple(liszt)
print(liszt)
print(toppel)
| true |
8225842771ab1017d304cf92c62de5b86f86bd65 | nkhaja/Data-Structures | /queue.py | 1,379 | 4.125 | 4 | #!python
from linkedlist import LinkedList
class Queue(LinkedList):
def __init__(self, iterable=None):
"""Initialize this queue and enqueue the given items, if any"""
super(Queue, self).__init__()
if iterable:
for item in iterable:
self.enqueue(item)
def __repr__(self):
"""Return a string representation of this queue"""
return 'Queue({})'.format(self.length())
def is_empty(self):
"""Return True if this queue is empty, or False otherwise"""
return super(Queue, self).is_empty()
def length(self):
"""Return the number of items in this queue"""
return super(Queue, self).length()
def peek(self):
"""Return the next item in this queue without removing it,
or None if this queue is empty"""
if self.is_empty():
return None
else:
return self.tail.data
def enqueue(self, item):
"""Enqueue the given item into this queue"""
super(Queue, self).prepend(item)
def dequeue(self):
"""Return the next item and remove it from this queue,
or raise ValueError if this queue is empty"""
if self.is_empty():
raise ValueError
dequeued_item = self.tail.data
super(Queue, self).delete(self.tail.data)
return dequeued_item
| true |
f2926a48ba00c6344cfab1dd4ee6c280c6352071 | TeoBlock/cti110 | /M3T1_AreaOfRectangles_McIntireTheodore.py | 1,693 | 4.5625 | 5 | # CTI-110
# Module 3 Tutorial 1
# Theodore McIntire
# 05 October 2017
# This program gets user input and then outputs which rectangle has the greater area
# variables for rectangle 1 and 2 length and width
length1 = 0
width1 = 0
area1 = 0
length2 = 0
width2 = 0
area2 = 0
# initial variable values are set to zero
#def main() to get user inputs, calculate areas and compare areas using the nested if-else method
def main():
print ('This program gets user input and then outputs which rectangle has the greater area.')
length1 = float(input('Enter the length of the 1st rectangle: '))
width1 = float(input('Enter the width of the 1st rectangle: '))
area1 = length1 * width1
print ('The area of the first rectangle is ', format(area1, ',.2f'))
print ()
length2 = float(input('Enter the length of the 2nd rectangle: '))
width2 = float(input('Enter the width of the 2nd rectangle: '))
area2 = length2 * width2
print ('The area of the second rectangle is ', format(area2, ',.2f'))
print ()
if area1 > area2:
print('The first rectangle has the greater area')
elif area1 < area2:
print('The second rectangle has the greater area')
elif area1 == area2:
print('The two rectangles have the same area')
else:
print('This program is messed up - complain to person who coded it...')
print ()
print ()
# This finishes the code for this method
'''
#def alt() outline for using the nested if-else method
def alt():
'''
# program start - multiple methods are alternated to test/compare code
main()
main()
main()
main()
# end program
| true |
734f158b54c8d856de0a2e81e59397b69399ddbf | TeoBlock/cti110 | /M5T2_McIntireTheodore.py | 1,073 | 4.34375 | 4 | # CTI-110
# Module 5 Tutorial 2
# Theodore McIntire
# 12 October 2017
# This program totals the number of bugs collected in a week
#def main() uses a for loop
def main():
# This program uses these variables
# ? ? ? I DO NOT UNDERSTAND WHY THIS PROGRAM DOES NOT RUN
# IF THESE VARIABLES ARE DEFINED OUTSIDE OF/ABOVE MAIN ? ? ?
quantityPerDay = 0
runningTotal = 0
week = range(1, 8)
for count in week:
print('Day', count)
quantityPerDay = int(input('Enter the number of bugs collected: '))
runningTotal = runningTotal + quantityPerDay
print ('On day', count, 'the number of bugs collected is', quantityPerDay, 'and subtotal is', runningTotal)
print(' ')
print("At the end of the week the total number of bugs collected is:", runningTotal)
# This finishes the code for this method
'''
#def alt() outline if needed
def alt():
# This finishes the code for this method
'''
# program start - multiple methods are run to test the code
main()
#end of program
| true |
6f71141dc458512bd412f4f4351ae6ca9ad029fa | Trex275/C---97 | /C97.py | 468 | 4.1875 | 4 | #Write a program to count the number of words in the input by user
userinput = input("Enter any sentence :")
print(userinput)
numberofwords = 1
numberofcharachters = 0
for i in userinput:
if i==' ':
numberofwords = numberofwords + 1
else:
numberofcharachters = numberofcharachters + 1
print("number of words in input string is")
print(numberofwords)
print("number of charachters in input string is")
print(numberofcharachters) | true |
f71b8ff05499b70dc7d062c09c60ffa566ce9e2e | jashburn8020/design-patterns | /python/src/prototype/prototype_test.py | 1,907 | 4.21875 | 4 | """Prototype pattern example."""
import copy
class Address:
"""A person's address."""
def __init__(self, street: str, city: str, country: str):
self.country = country
self.city = city
self.street = street
def __eq__(self, other: object) -> bool:
"""Two `Address` objects are equal if their attributes are equal."""
if not isinstance(other, Address):
return NotImplemented
return (
self.country == other.country
and self.city == other.city
and self.country == other.country
)
class Person:
"""A person's name and address."""
def __init__(self, name: str, address: Address):
self.name = name
self.address = address
def __eq__(self, other: object) -> bool:
"""Two `Person` objects are equal if their names and addresses are equal."""
if not isinstance(other, Person):
return NotImplemented
return self.name == other.name and self.address == other.address
def test_prototype_full() -> None:
"""Use a prototype that is a fully initialised object."""
address = Address("123 London Road", "London", "UK")
john = Person("John", address)
# Use `john` as a prototype.
jane = copy.deepcopy(john)
assert jane == john
assert jane is not john
jane.name = "Jane"
assert jane != john
assert jane.address == john.address
assert jane.address is not john.address
def test_prototype_partial() -> None:
"""Use a prototype that is a partially initialised object."""
address_london = Address("", "London", "UK")
address_john = copy.deepcopy(address_london)
address_john.street = "123 London Road"
john = Person("John", address_john)
expected = Person("John", Address("123 London Road", "London", "UK"))
assert john == expected
assert john is not expected
| true |
4a8634e9e9e8b767a7c36e57c6a1ee559c271a5e | sidhanshu2003/Python-assignments-letsupgrade | /Batch 6 Python Day 3 Assignment.py | 871 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[36]:
# Sum of n numbers with help of while loop
#Input from user
num = eval(input("Please enter the number "))
sum = 0
while num >0:
sum = sum + num
print(f"Number is --> {num} Sum is --> {sum}")
num= num -1
print ("Final Sum is ", sum)
print (f"Final Sum is {sum}")
print ("Final Sum is%4d"%(sum))
# In[66]:
# Take a number and find whether it is prime or not
# Input from user
num = int(input("Enter a number "))
# prime numbers are greater than 1
if num > 1:
# Check starting from 2 till number, increment by 1
for each in range(2,num):
if (num % each) == 0:
print(f"{num} is not a prime number!")
break
else:
print(f"{num} is a prime number!")
# input number is less than or equal to 1
else:
print(f"{num} is not a prime number!")
| true |
5ec55686e4dfb98d372ea6537a8a01c2ed893fb1 | asleake/AdventOfCode2020 | /Day3.py | 740 | 4.21875 | 4 | """Day 3 of Advent of Code 2020. Running this file will print out the correct answers to the two
puzzles from Day 3."""
from common.imports import importAdventFile
from common.slope_functions import findTreesOnSlope
data = importAdventFile('data/Day3Input')
def FirstPart():
""" Find the number of trees for the given slope on the hill """
return findTreesOnSlope(data,(3,1))
def SecondPart():
""" Find the product of the number of trees for the given slopes on the hill """
slopes = [(1,1),(3,1),(5,1),(7,1),(1,2)]
output = 1
for slope in slopes:
output *= findTreesOnSlope(data,slope)
return output
print("First Puzzle Answer:\t{}\nSecond Puzzle Answer:\t{}\n".format(FirstPart(),SecondPart())) | true |
c52d1872447e2ae0d2fce6e2b62517f892ac1af2 | SACHSTech/ics2o1-livehack---2-GavinGe3 | /problem1.py | 966 | 4.21875 | 4 |
"""
-------------------------------------------------------------------------------
Name: problem1.py
Purpose: Given an input of the number of antennas and eyes, determines the alien lifeform
Author: Ge.G
Created: 23/02/2021
------------------------------------------------------------------------------
"""
print("***Welcome to the alien life form detector***")
# get eye and antenna info
antennas = int(input("How many antennas does the lifeform have?: "))
eyes = int(input("How many eyes does the lifeform have?: "))
# determines and outputs the alien species
if antennas <= 6 and eyes >= 2:
print("\nLife form detected: MaxMartian")
if antennas >= 3 and eyes <= 4:
print("\nLife form detected: AudreyMartian")
if antennas <= 2 and eyes <= 3:
print("\nLife form detected: BrooklynMartian")
if antennas == 0 and eyes == 2:
print("\nLife form detected: MattDamonMartian")
if antennas > 6 and eyes > 4:
print("\nNo life form detected")
| true |
c3d9fbf50cc43b31032aa5a80a0433998774fa75 | Bedrock02/Interview-Practice | /CSSpartans/quiz3.py | 1,457 | 4.15625 | 4 | '''
Implement the function makeChange(cents, coins)
Given an input cents and coins, makeChange should output an object that contains
the minimum amount of coins needed to equate to cents in value.
Coins is an array that contains the coin values.
Input
makeChange will take in 2 parameters,
an integer cents,
and an unsorted array of integers, coins
Note: coins will always contain a 1
Output
makeChange should output an object.
The objects keys should be the value of the coin and the key values should be mapped to the amount of coins needed
Sample data
cents => 132
coins => [25, 10, 5, 1]
makeChange(cents, coins) => {25: 5, 10: 0, 5: 1, 1:2}
Here it will need 5 quarters, 1 nickel, and 2 pennies (25*5 + 5*1 + 1*2 = 132)
'''
from collections import defaultdict
def makeChange(cents, coins):
purse = defaultdict(int)
coins.sort(reverse=True)
for coin in coins:
purse[coin]
while(cents):
factors = findFactors(cents, coins)
if factors:
coin = factors[0]
purse[coin] = cents/coin
cents -= coin*purse[coin]
coins.remove(coin)
continue
else:
for coin in coins:
numberOfCoins = cents/coin
if numberOfCoins:
purse[coin] = numberOfCoins
cents -= coin*numberOfCoins
coins.remove(coin)
break
return purse
def findFactors(cents, coins):
factors = []
for coin in coins:
if cents%coin == 0 and coin is not 1:
factors.append(coin)
return factors
print makeChange(132, [25, 10, 5, 1])
| true |
357f133aa1d44da3baa30b32d2260f7edfcf0d51 | Bedrock02/Interview-Practice | /Array_Strings/string_compression.py | 1,259 | 4.34375 | 4 | '''
Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become
a2blc5a3.
If the "compressed" string would not become smaller than the
original string, your method should return the original string
My Solution
1. Iterat through string
2. If it is the first time we are seeing the character we add that to new string
3. Keep track of what character we saw previously
4. Continue iterating until you see a new character (while keeping count)
5. Once you see a new character place the count on string being built
6. Repeat steps 2 to 6
Things to note:
- copying a string is a runtime O(N+M) operation, since we are appending the same word we
are lookingat O(m^2). Concatenation basically copies over a string
'''
def compress_string(input):
prev_char = None
prev_count = 0
result = ""
def compress(resultString, extra=''):
return (resultString + str(prev_count) if prev_char is not None else '') + extra
for char in input:
if char is not prev_char:
result = compress(result, extra=char)
prev_count, prev_char = 1, char
else:
prev_count += 1
result = compress(result)
return result
| true |
cff73d26ab370d55660d3817b6b4d41527228fdc | Bedrock02/Interview-Practice | /Stacks_Queues/sort_stack.py | 1,536 | 4.1875 | 4 | '''Write a program to sort a stack in ascending order. You should not make any assump- tions
about how the stack is implemented. The following are the only functions
that should be used to write this program: push | pop | peek | isEmpty.'''
# Solution Explanation
# In order to sort a stack we need another stack
# 1 - if the spare stack is empty we want to push the top element of hte given stack
# to the spare stack
# 2 - else if we have items in the spare stack and we are sorting by acsending order
# While we don't run out of items to check against the spare stack and the element
# is greater than the top element in the spare stack, keep poping the spare stack
# 3 - Once we either run out of items or find that the element is < the top element
# in the spare stack then we want to push that element onto the spare stack
# We continue to repeat this step (hence the while) until the given stack is empty
from stack import Stack_Node
def sort_stack(stack):
spare_stack = Stack_Node()
while not stack.is_empty():
if spare_stack.is_empty():
spare_stack.push(stack.pop())
else:
element = stack.pop()
while not spare_stack.is_empty() and element > spare_stack.peek():
stack.push(spare_stack.pop())
spare_stack.push(element)
return spare_stack
unsorted_stack = Stack_Node()
unsorted_stack.push(1)
unsorted_stack.push(2)
unsorted_stack.push(8)
unsorted_stack.push(3)
unsorted_stack.push(9)
unsorted_stack.push(4)
sorted_stack = sort_stack(unsorted_stack)
print sorted_stack
print sorted_stack.peek() | true |
2affdb4fbe889a193f4f33973d3de94c63e76325 | PhoenixTAN/CS-591-Parallel-Computing | /Code/merge-k-lists/merge_lists_pairs.py | 2,298 | 4.34375 | 4 | import random
from typing import List
def merge_lists(inputs: List[List[int]]) -> List[int]:
"""
Merges an arbitrary number of sorted lists of integers
into a single sorted list of integers.
Iterates over the input list of lists.
On each iteration, selects pairs (a, b) of lists to merge,
copying the merged list over list a.
The outer loop doubles the value of leap starting at 1
and ending where leap equals the number of input lists.
The inner loop then finds pairs (i, i + leap), where
i ranges from 0 to num_lists, incrementing by 2 * leap.
For k = 8 input lists, the pairs of list indices used for merging
across all outer loop iterations would be
(0, 1) -> 0, (2, 3) -> 2, (4, 5) -> 4, (6, 7) -> 6
(0, 2) -> 0, (4, 6) -> 4
(0, 4) -> 0
:param inputs: list of sorted lists of integers
:return sorted list of integers
"""
num_lists = len(inputs)
leap = 1
while leap < num_lists:
i = 0
while i < num_lists:
if i + leap < num_lists:
inputs[i] = merge_two_lists(inputs[i], inputs[i + leap])
i += leap * 2
leap *= 2
return inputs[0]
def merge_two_lists(list_a: List[int], list_b: List[int]) -> List[int]:
"""
Helper function to merge elements of list_a and list_b into
a single list, which it returns.
:param list_a: list of integers to merge with those in list_b into a single list
:param list_b: list of integers to merge with those in list_a into a single list
:return:
"""
output = []
while len(list_a) or len(list_b):
if len(list_b) and (not len(list_a) or list_b[0] < list_a[0]):
output.append(list_b[0])
list_b.pop(0)
else:
output.append(list_a[0])
list_a.pop(0)
return output
if __name__ == '__main__':
input_lists = []
input_sizes = [5, 4, 3, 6, 7, 4, 5, 2]
random.seed(1)
for input_size in input_sizes:
new_list = random.sample(range(0, 100), input_size)
new_list.sort()
input_lists.append(new_list)
print('Inputs:')
for input_list in input_lists:
print(input_list)
output_list = merge_lists(input_lists)
print()
print('Outputs:')
print(output_list)
| true |
69d946050b26fe6412d1436e0bbcc049be9cca14 | engemp/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 268 | 4.21875 | 4 | #!/usr/bin/python3
def uppercase(str):
for character in range(len(str)):
letter = ord(str[character])
if str[character].islower():
letter = letter - 32
letter = chr(letter)
print("{}".format(letter), end="")
print()
| false |
183c733935f791b6a73f6b6e45e176a9e5b12f0d | engemp/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 320 | 4.125 | 4 | #!/usr/bin/python3
'''
Returns the number of lines in a txt
'''
def number_of_lines(filename=""):
'''
Returns the number of lines in a txt
'''
numberLines = 0
with open(filename, mode='r', encoding='utf-8') as filet1:
for line in filet1:
numberLines += 1
return numberLines
| true |
cf1f24787a41a57682780db8e785f1cc76536f33 | VPatel5/CS127 | /nameOrganizer.py | 424 | 4.21875 | 4 | # Name: Vraj Patel
# Email: vraj.patel24@myhunter.cuny.edu
# Date: September 13, 2019
# This program organizes the names inputted
#Cohn, Mildred; Dolciani, Mary P.; Rees, Mina; Teitelbaum, Ruth; Yalow, Rosalyn
message = input("Please enter your list of names using '; ' to separate each name: ")
list = message.split('; ')
for name in list:
lastName = name.split(', ')[0]
firstName = name.split(', ')[1][0]
print(firstName + ".", lastName)
| false |
3e39177428ef1421e0e47fd943c17924c9a45570 | whiterabbitsource/pyhello | /hello.py | 361 | 4.21875 | 4 | # Hello! World!
print("Hello, World!")
# Learning Strings
my_string = "This is a string"
## Make string uppercase
my_string_upper = my_string.upper()
print(my_string_upper)
# Determine data type of string
print(type(my_string))
# Slicing strings [python is zero-based and starts at 0 and not 1]
print(my_string[0:4])
print(my_string[:1])
print(my_string[0:14])
| true |
711dc1eca9d23e169eec6c52bd038f5e0671bb0b | Riopradheep007/Searching-and-Sorting-Algorithms | /Sorting/Selection Sort/selection_sort.py | 465 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 20 14:50:08 2021
@author: pradheep
"""
"""
find the minimum value placed in the left side
very worst algorithm
Best case O(n^2)
worst case O(n*2)
"""
def selection_sort(ls):
for i in range(len(ls)):
min_var=i
for j in range(i,len(ls)):
if ls[j]<ls[min_var]:
min_var=j
ls[i],ls[min_var]=ls[min_var],ls[i]
print(ls)
ls=[0,7,3,5,2,8,6,1,2]
selection_sort(ls)
| false |
0d1f9138991dee73f157d07adff1dba350647ba2 | NagaManjunath/algorithms | /stack/is_sorted.py | 1,238 | 4.34375 | 4 | """
Given a stack, a function is_sorted accepts a stack as a parameter and returns
true if the elements in the stack occur in ascending increasing order from
bottom, and false otherwise. That is, the smallest element should be at bottom
For example:
bottom [6, 3, 5, 1, 2, 4] top
The function should return false
bottom [1, 2, 3, 4, 5, 6] top
The function should return true
"""
import unittest
def is_sorted(stack):
storage_stack = []
for i in range(len(stack)):
if len(stack) == 0:
return True
first_val = stack.pop()
if len(stack) == 0:
return True
second_val = stack.pop()
if first_val < second_val:
return False
storage_stack.append(first_val)
storage_stack.append(second_val)
# Backup stack
for i in range(len(storage_stack)):
stack.append(storage_stack.pop())
return True
class TestSuite(unittest.TestCase):
"""
test suite for the function (above)
"""
def test_stutter(self):
# Test case: bottom [6, 3, 5, 1, 2, 4] top
self.assertFalse(is_sorted([6, 3, 5, 1, 2, 4]))
self.assertTrue(is_sorted([1, 2, 3, 4, 5, 6]))
if __name__ == "__main__":
unittest.main()
| true |
40f29fc621c51c189e097f3515a0ce7507e88d8d | manisha2412/SimplePythonExercises | /exc17.py | 829 | 4.34375 | 4 | """
Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored
"""
def palindrome_recognizer(str):
out = "".join(c for c in str if c not in ('!','.',':','?',' '))
t = ""
for i in range(len(out)-1, -1, -1):
t += out[i]
out = out.lower()
t = t.lower()
if out == t:
return "String is Palindrom"
else:
return "String is not Palindrom"
print palindrome_recognizer("Was it a rat I saw?")
| true |
79f762282c13ba6765ca4509a9bcebff60213892 | annesels/innlevering_1 | /oppgave_2.py | 592 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
a = input("Vil du finne (m), (v) eller (E)? " )
if a == "E":
m = float(input("Hva er massen (m)? "))
v = float(input("Hva er farten (v)? "))
E =(m*v**2)/2
print("Den kinetiske enegien til legemet er",E,"J")
elif a == "m":
E = float(input("Hva er energien (E)? "))
v = float(input("Hva er farten (v)? "))
m = 2*E/v**2
print("Massen til legemet ditt er",m,"kg")
elif a == "v":
E = float(input("Hva er energien? "))
m = float(input("Hva er massen?"))
math.sqrt(v) = math.sqrt((2*E)/m)
| false |
048aefeb9045a6163d2707a54c4bc9b256ab231a | doron04/dsf | /block_1/sort_algorithms.py | 1,469 | 4.125 | 4 | import random
import time
num_elements = 10000
S = [random.randint(0,1000000) for x in range(num_elements)]
def bubble_sort(array):
'''Bubble Sort Algorithm. Takes an unsorted list as input and returns a sorted list'''
k = len(array)
S = array
while k>0:
for i in range(k-1):
if S[i] > S[i+1]:
temp = S[i]
S[i] = S[i+1]
S[i+1] = temp
k -= 1
return S
s0 = time.time()
sorted_array = bubble_sort(S)
print(time.time()-s0)
sorted_array
def merge(left, right):
"""A function to reassemble the array"""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""A function that will be called recursively."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
S = [random.randint(0,1000000) for x in range(num_elements)]
s0 = time.time()
sorted_array = merge_sort(S)
print(time.time()-s0) | true |
36e9aeb82022742bc55ff804dff18410942d2bf5 | ikapoor/Project-Euler- | /palindromeChecker.py | 450 | 4.1875 | 4 | string = str(input("Please Enter a word: "))
string = string.replace(" ","")
length = len(string)
forwardString = []
for x in range(len(string)):
forwardString.append(string[x])
backwardsString = []
for x in range(len(string)):
backwardsString.append(string[length-1])
length = length -1
if (forwardString == backwardsString):
print("You have entered a palindrome! :)")
else:
print("You have not printed a palindrome! :(")
| true |
add28130e02da71486ecdba1da96381c2d983f96 | shincap8/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 273 | 4.15625 | 4 | #!/usr/bin/env python3
"""Function to return the shape of the matrix"""
def matrix_shape(matrix):
"""Function to return the shape of the matrix"""
shape = []
x = matrix
while type(x) is list:
shape.append(len(x))
x = x[0]
return shape
| true |
bca6fc69f750a8fe2067266eafcdd8aa1355dee0 | shincap8/holbertonschool-machine_learning | /math/0x00-linear_algebra/8-ridin_bareback.py | 654 | 4.1875 | 4 | #!/usr/bin/env python3
"""Function to return two multiply matrices"""
matrix_shape = __import__('2-size_me_please').matrix_shape
def mat_mul(mat1, mat2):
"""Function to return two multiply matrices"""
if matrix_shape(mat1)[1] != matrix_shape(mat2)[0]:
return None
mul = []
shapem = [matrix_shape(mat1)[0], matrix_shape(mat2)
[1], matrix_shape(mat1)[1]]
i = 0
j = 0
for i in range(shapem[0]):
mul.append(list())
for j in range(shapem[1]):
x = 0
for k in range(shapem[2]):
x += mat1[i][k] * mat2[k][j]
mul[i].append(x)
return mul
| false |
1610f9978876e43a5a97fe90a43bcb8fbe22f58e | ravichalla/wallbreaker | /week4/implement_stacks_using_queues.py | 1,764 | 4.21875 | 4 | '''
QUESTION:
225. Implement Stack using Queues
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
'''
import collections
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self._queue = collections.deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
q = self._queue
q.append(x)
for _ in range(len(q) - 1):
q.append(q.popleft())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self._queue.popleft()
def top(self):
"""
Get the top element.
:rtype: int
"""
return self._queue[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not len(self._queue)
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
'''
Ideas/thoughts:
using queues creating stacks.
first initialize a queue from collections deque . Deque is used , as it gives O(1) for append ,pop operations from both ends of queue
for removing in the stack , just do quue popleft
for getting the top ele , top , just return first ele .
''' | true |
88a14c40c2dd670acdd6ac98d4c40893e7f5502c | skyaiolos/AByteOfPython3 | /SEC08-Func/func_param.py | 317 | 4.15625 | 4 | def printMax(a, b):
if a > b:
print(f'{a} > {b}, {a} is the maximum')
elif a == b:
print(f'{a} = {b} , {a} is equal to {b}')
else:
print(f'{a} < {b} , {b} is the maximum')
printMax(3, 4) # directly give literal valuse
x = 5
y = 7
printMax(x, y) # give variables as arguments
| true |
cd74a9c17acda27bbafb8496da772ef319d467a6 | BrandonLMorris/InterviewPrep | /CrackingTheCodingInterview/Python/Chapter1/q3.py | 709 | 4.1875 | 4 | #!/usr/bin/env python3
"""Solution to question 3 of chapter 1"""
def is_perm(s1, s2):
"""Return true if s1 is a permutation of s2, assuming spaces count"""
if len(s1) != len(s2):
return False
# Add for occurences in s1, subtract for occurences in s2
counts = [0 for _ in range(128)]
for c in s1:
counts[ord(c)] += 1
for c in s2:
counts[ord(c)] -= 1
# Everything should be zero
return all([x == 0 for x in counts])
if __name__ == '__main__':
string1 = input('Enter string 1: ')
string2 = input('Enter string 2: ')
if is_perm(string2, string1):
print('They are permutations')
else:
print('They are not permutations')
| true |
39349ad653d01cf8eeaeed04e271b9057c770eb1 | ImagClaw/Python_Learning | /Classes&Objects/pet.py | 1,419 | 4.28125 | 4 | #! /bin/usr/env python3
#
# Author: Dal Whelpley
# Project: Pet Class build and then instantiation or the class
# Date: 4/25/2019
class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
def main():
name = input("What is your pet's name?\n")
animal_type = input("What type of pet is {name}?\n".format(name=name))
if animal_type == "dog":
age = input("Heck yeah! Dogs are awesome. How old is {name}?\n".format(name=name))
#if else animal_type == "lizard":
# age = input("Disgusting! Why??? Fine,ow old is {name}?\n".format(name=name))
else:
age = input("How old is {name}?\n".format(name=name))
pets = Pet(name, animal_type, age)
print('Here is the data you entered:')
print('Pet Name: ', pets.get_name())
print('Animal Type: ', pets.get_animal_type())
print('Age: ', pets.get_age())
print('This will be added to the records. ')
if __name__ == "__main__":
main() | true |
e1670d7b94b07d53ff54f582e94097ee1b31409f | ImagClaw/Python_Learning | /proj4.py | 477 | 4.28125 | 4 | #! /bin/usr/env python3
#
# Author: Dal Whelpley
# Project: Project 4 (convert Celsius to Fehrenheit)
# Date: 4/22/2019
print("Converts Celsius to Fehrenheit.") # Tells user about program
c = input("Enter the temp in Celsius: ") # input tempurature in celsius
f = float(9/5)*float(c)+32 # converts input to fehrenheit
# prints Celsius input and Fehrenheit conversion with 1 decimal place
print("\n{cels:.1f} °C = {fehr:.1f} °F".format(cels=float(c), fehr=float(f))) | true |
6db10de58682123f5dde420eb216c98efe1a2120 | Otabek-KBTU/PT-Python | /project/10ball.py | 670 | 4.25 | 4 | def count_words(text):
#google how to split text to words with multiple delimiters ' ', '-', '.' etc
# words = input(text)
words = special_split()
counter = {}
simbol = ('я', 'ты', 'он', 'она', 'оно', 'мы', 'вы', 'они','мой','твой','.',',','!','?')
#убрать местоимения, предлоги и другие лишные слова
words = exclude_odd_words(words)
for w in words:
if simbol in counter:
# counter[w] = counter[w] + 1
counter[w] = counter.replace(simbol.split())
else:
counter[w] = 1
#google how to sort dictionary by value
top_counter = get_top_10(counter)
return top_counter | false |
4451ca66232d7465fa9084de2b3cb3085e61069f | lbs1991/py | /isnotin.py | 482 | 4.21875 | 4 | #!/usr/bin/python27
x = [x for x in range(1,10)]
print(x)
y =[]
result = True if 12 not in x else False # this is the best way
print(result)
result = True if not 12 in x else False # this way just like as " (not 12) in x"
print(result)
print(x is y)
print(x is not y) # this is the best way
print(not x is y) # this way just like as " (not x ) is y" ,so upper is the best way
result = 2 if 1 < 2 else 5 if 4 > 5 else 6 # just as 1 > 2 ? 2 : 4 > 5 ? 5 : 6
print(result)
| true |
946b7da8a38704cd49fd96392a2a61deefbd8680 | tamarameisman/cse210-student-mastermind | /mastermind/game/player.py | 2,391 | 4.125 | 4 | class Player:
"""A person taking part in a game. The responsibility of Player is to keep track of their identity and last guess.
Stereotype:
Information Holder
Attributes:
_name (string): The player's name.
_guess (guess): The player's last guess.
"""
def __init__(self, name, guess):
"""The class constructor.
Args:
self (Player): an instance of Player.
"""
self._name = name
self._guess = guess
self._length = self._guess.get_number()
self._status = self.create_asterisks()
self._original_status = self.create_asterisks()
def get_guess(self):
"""Returns the player's last guess (an instance of guess). If the player
hasn't guessd yet this method returns None.
Args:
self (Player): an instance of Player.
"""
return self._guess
def get_name(self):
"""Returns the player's name.
Args:
self (Player): an instance of Player.
"""
return self._name
def get_status(self):
"""Returns the player's game status.
Args:
self (Player): an instance of Player.
"""
return self._status
def set_guess(self, guess):
"""Sets the player's last guess to the given instance of guess.
Args:
guess (guess): an instance of guess
"""
self._guess = guess
def set_name(self, name):
"""Returns the player's name.
Args:
self (Player): an instance of Player.
"""
self._name = name
def set_status(self, status):
"""Sets the player's last guess to the given instance of guess.
Args:
guess (guess): an instance of guess
"""
self._status = status
def create_asterisks(self):
""" Create the list of asterisks to give the hint
Args:
self (Player): an instance of player
"""
list_ast = []
for i in range(self._length):
list_ast.append('*')
return list_ast
def original_status(self):
""" Return the hint to the original status
Args:
self (Player): an instance of Player
"""
return self._original_status
| true |
993d9ab91794f3e07d2259146c4132ef65fabc62 | F4r4m4rz/MyPython | /Math/Fibonnacci.py | 223 | 4.125 | 4 |
def Fibonacci(seq):
if type(seq) != int:
raise ValueError("Expecting integer")
if seq==0 or seq == -1:
return 0
if seq == 1:
return 1
return Fibonacci(seq-2) + Fibonacci(seq-1)
| false |
bab22d104eb534c15aa529daab3e577603aca08d | KRHS-GameProgramming-2018/Lucas-and-Owen-Madlibs | /getInput.py | 2,985 | 4.125 | 4 | def getMenuInput():
goodInput = False
while not goodInput:
response = raw_input(" > ")
if (response == "1"
or response == "One"):
response = "1"
goodInput = True
elif (response == "2"
or response == "Two"):
response = "2"
goodInput = True
elif (response =="3"
or response =="Three") :
response = "3"
goodInput = True
elif (response == "4"
or response == "Four"):
response = "4"
goodInput = True
elif (response == "Q"
or response == "Quit"
or response == "q"
or response == "quit"
or response == "X"
or response == "Exit"):
response = "Q"
goodInput = True
else:
print "Please make a valid choice"
return response
def getWord(prompt):
goodInput = False
while not goodInput:
word = raw_input(prompt)
if not isSwear(word):
goodInput = True
else:
print "Watch your language!"
return word
def getEd(prompt):
goodInput = False
while not goodInput:
word = raw_input(prompt)
if not isSwear(word):
goodInput = True
else:
print "Invalid choice!"
break
if word[-2:] != "ed":
goodInput = False
print "word must end in ed"
return word
def getY(prompt):
goodInput = False
while not goodInput:
word = raw_input(prompt)
if not isSwear(word):
goodInput = True
else:
print "Invalid choice!"
break
if word[-1:] != "y":
goodInput = False
print "name must end in y"
return word
# You should have a third getter; maybe a list based one like get state or animal
def getNumber(prompt, minNumber, maxNumber):
goodInput = False
while not goodInput:
word = raw_input(prompt+" (Between " + str(minNumber) + " and " + str(maxNumber) + ") ")
nums = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
goodInput = True
for character in word:
if character not in nums:
print "not a number"
goodInput = False
break
if goodInput and (int(word) < minNumber or int(word) > maxNumber):
goodInput = False
print "Out of Range"
return word
def isSwear(word):
swearList = ["poop",
"piss"
"shit"
"fuck"
"ass"
"dick"
"bitch"
"damn"
"pussy"
"fortnite"
"dildo"
"hell"]
if word in swearList:
return True
else:
return False
| true |
0acd460f7ebbfcbbc4b5ea4395c0798d61940f01 | NestY73/Algorythms_Python_Course | /Lesson_1/line_equation.py | 809 | 4.28125 | 4 | #-------------------------------------------------------------------------------
# Name: line_equation
# Purpose: Homework_lesson1_Algorythms
#
# Author: Nesterovich Yury
#
# Created: 16.03.2019
# Copyright: (c) Nesterovich 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
print("Координаты точки A(x1; y1):")
x1 = float(input("x1 = "))
print("x1 =", x1)
y1 = float(input("y1 = "))
print("y1 =", y1)
print("Координаты точки B(x2; y2):")
x2 = float(input("x2 = "))
print("x2 =", x2)
y2 = float(input("y2 = "))
print("y2 =", y2)
print("Уравнение прямой, проходящей через эти точки:")
k = (y1 - y2) / (x1 - x2)
b = y2 - k*x2
print(" y = %.2f*x + %.2f" % (k, b))
| false |
977fb7c55a7c2c5e15fd9062d50a2574783ec6c6 | NestY73/Algorythms_Python_Course | /Lesson_1/bit_operations.py | 978 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: bit_operations
# Purpose: Homework_lesson1_Algorythms
#
# Author: Nesterovich Yury
#
# Created: 16.03.2019
# Copyright: (c) Nesterovich 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
n1 = int(input("Введите первое число: "))
n2 = int(input("Введите второе число: "))
bit_or = n1 | n2
bit_and = n1 & n2
bit_xor = n1 ^ n2
print("Результат побитового OR: %10s" % bin(bit_or))
print("Результат побитового AND: %10s" % bin(bit_and))
print("Результат побитового XOR: %10s" % bin(bit_xor))
print("Результат побитового сдвига на 2 разряда вправо: %10s" %bin(n1>>2))
print("Результат побитового сдвига на 2 разряда влево: %10s" %bin(n1<<2))
| false |
d562002df8df8225ecc1f967b62807c98208c089 | prachived/PlagiarismDetector | /PlagiarismDetector/plagiarism-detector/factorial1.py | 294 | 4.28125 | 4 | #Test for comments
def factorial():
#this is a comment
if number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif number == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,number + 1):
fact = fact*i
print("The factorial of",number,"is",fact) | true |
4a9e51b13e70e3d92bcdaa654fe612841975d40a | wspasindupanthaka/hands-on-nlp-with-python | /Python Crash Course/data_structures.py | 728 | 4.15625 | 4 |
#Non homegeneos list
list1 = [12,12.1,"Hi"]
#Printing a list
print(list1)
print(list1[0])
print(list1[1])
print()
#Inserting elements
list1.append(15)
print(list1)
list1.insert(0,"Inserted")
print(list1)
print()
#Updating list
list1[0]=125
print(list1)
print()
#Delete element
list1.pop()
print(list1)
del list1[2]
print(list1)
<<<<<<< HEAD
print()
#List length
print(len(list1))
print()
#List Iterating
for index in range(0, len(list1)):
print(list1[index])
print()
for item in list1:
print(item)
=======
for index in range(0,len(list1)):
print(list1[index], end=",")
print()
print()
for item in list1:
print(item)
>>>>>>> f284e7678be47171f81172b6382c64cf93a99a24
| false |
bc94f3dd8cc1a0a90e16dd506213791166996311 | 1232145/Rock_paper_scissor | /Rock_Paper_Scissor.py | 1,123 | 4.15625 | 4 | from random import randint
computer = randint(0,2)
if computer == 0:
computer = "rock"
if computer == 1:
computer = "scissor"
if computer == 2:
computer = "paper"
def main():
run = True
while run:
player = input("rock, paper, or scissor? ").lower()
if player == "rock" or player == "paper" or player == "scissor":
print("You choose " + str(player))
print("Computer chooses " + str(computer))
else:
print("Invalid input")
break
if player == computer:
print("Draw")
if player == "rock":
if computer == "scissor":
print("You win!")
if computer == "paper":
print("You lose!")
if player == "scissor":
if computer == "paper":
print("You win!")
if computer == "rock":
print("You lose!")
if player == "paper":
if computer == "rock":
print("You win!")
if computer == "scissor":
print("You lose!")
replay = input("Player again? Yes/No: ").lower()
if replay != "yes":
run = False
if __name__ == "__main__":
main()
| true |
bbf0d945f52849a9bf1c0e67ade855e1716c9d49 | Nmewada/hello-python | /15_lists.py | 323 | 4.1875 | 4 | # List
# Create a list using []
a = [1, 2 , 4, 50, 6]
print(a) # Print the list using print() function
# List Indexing
# Access using index using a[0], a[1], a[2]
print(a[2])
# Change the value of list using
a[0] = 90
print(a)
# We can create a list with items of different types
b = [15, "Nitin", False, 6.9]
print(b) | true |
bf117ed9ea57d686ca00d55fe788f1cbd2dac122 | alainno/fibras | /old_fibergen/rotation.py | 626 | 4.125 | 4 | import math
import matplotlib.pyplot as plt
def rotate(origin, point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy
point = (3,4)
origin = (0,0)
rotated = rotate(origin, point, math.radians(5))
#print(rotated)
plt.scatter(origin[0],origin[1])
plt.scatter(point[0],point[1])
plt.scatter(rotated[0],rotated[1])
plt.show()
| true |
868e5fc193c8a6982c1de1937e0f089adb9f9455 | vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3 | /Algorithms/2 Array Recursion/Segrigate.py | 1,568 | 4.1875 | 4 | """Segregate even odd.
"""
def SegregateEvenOdd(arr):
first = 0
second = len(arr) - 1
while first < second:
if arr[first] % 2 == 0:
first += 1
elif arr[second] % 2 != 0:
second -= 1
else:
arr[first], arr[second] = arr[second], arr[first]
"""
Segregate possitive ans negative.
"""
def SegregatePossitiveNegative(arr):
first = 0
second = len(arr) - 1
while first < second:
if arr[first] <= 0:
first += 1
elif arr[second] > 0:
second -= 1
else:
arr[first], arr[second] = arr[second], arr[first]
"""
Segrigate possitive and negative , order of appearence should be maintained.
Just Segregate like insertion sort.
Use an array.
"""
def SegregatePossitiveNegative2(arr):
index = 0
size = len(arr)
arr2 = list(arr)
for i in range(size) :
if arr2[i] <= 0:
arr[index] = arr2[i]
index += 1
for i in range(size) :
if arr2[i] > 0:
arr[index] = arr2[i]
index += 1
"""
Segrigate Even number at even index and odd numbers at odd index.
If possible then return true else return false.
"""
def SegregateEvenOdd2(arr):
odd = 1
even = 0
size = len(arr)
while odd <= size or even <= size:
if arr[even] % 2 == 0:
even += 2
elif arr[odd] % 2 != 0:
odd += 2
else:
arr[odd], arr[even] = arr[even], arr[odd]
if odd - even > 1:
return False
else :
return True
| true |
9f592349b2200db2fd3fa16a555026eb5d6781aa | vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3 | /Algorithms/2 Version/minimalSwap.py | 1,861 | 4.28125 | 4 | """
Minimum swaps required to bring all elements less than given value together at the start of array.
Use quick sort kind of technique by taking two index from both end
and try to use the given value as key.
Count the number of swaps that is answer.
"""
def minSwaps(arr, val):
swapCount = 0
first = 0
second = len(arr) - 1
while first < second:
if arr[first] <= val:
first += 1
elif arr[second] > val:
second -= 1
else:
arr[first], arr[second] = arr[second], arr[first]
swapCount += 1
return swapCount
def main():
arr = [2, 1, 5, 6, 3]
k = 3
print minSwaps(arr, k)
arr1 = [2, 7, 9, 5, 8, 7, 4]
k = 5
print minSwaps(arr1, k)
"""
Now in the above problem we dont want all the elements in start of array.
We want to find a window for which minimum number of swaps are requered to
bring all the elements less then the than given value together.
"""
def minSwapsWin(arr, val):
count = 0
size = len(arr)
for i in range(size):
if arr[i] <= val:
count += 1
currCount = 0
for i in range(count):
if arr[i] <= val:
currCount += 1
maxCount = currCount
first = 0
while first < size - count:
if arr[first] < val:
currCount -= 1
if arr[first + count] < val:
currCount += 1
if currCount > maxCount:
maxCount = currCount
first += 1
return count - maxCount
def main2():
arr = [2, 1, 5, 6, 3]
k = 3
print minSwapsWin(arr, k)
arr1 = [2, 7, 9, 5, 8, 7, 4]
k = 5
print minSwapsWin(arr1, k)
main2()
"""
find product of first k elements.
Use quick select to find kth element the elements which are at the left of
kth index will be the elements less then it.
""" | true |
629cc6420969359ac91259b2f817535966bd73f5 | Jasonhou209/notes | /leetcode/206_reverse_linked_list.py | 916 | 4.21875 | 4 | """
206.反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
cur = head
while cur != None:
cur.next, prev, cur = prev, cur, cur.next
return prev
def main():
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
resultNode = Solution().reverseList(head)
while resultNode != None:
print(resultNode.val, end=" ")
resultNode = resultNode.next
if __name__ == "__main__":
main() | false |
e1f076daa1983954c7c42fb70a35e2b2b428a50d | anjaandric/Midterm-Exam-2 | /task3.py | 572 | 4.25 | 4 | """
=================== TASK 3 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def rec_sum(lista):
if len(lista)==0:
return 0
else:
return lista[0] + rec_sum(lista[1:])
if __name__ == "__main__":
niz = [1,3,4,2,5]
print(rec_sum(niz))
| true |
b7bd510c8bac072a3183ce280105511722fa7f71 | pranshu1921/RockPaperScissors | /rock_paper_scissors.py | 1,048 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 17:25:10 2020
@author: Pranshu Kumar
"""
from random import randint
#creating play options list
t = ['Rock', 'Paper', 'Scissors']
#assigning random play to computer
computer = t[randint(0,2)]
#player set to False
player = False
while player == False:
player = input("Rock, Paper, Scissors ?")
if player == computer:
print("Tie!")
elif player == 'Rock':
if computer == 'Paper':
print("Oops! You lose", computer, 'covered', player)
else:
print("You win !", player)
elif player == 'Paper':
if computer == 'Scissors':
print("You lose !", computer, 'cut you.')
else:
print('you win', player)
elif player == 'Scissors':
if computer == 'Rock':
print("you lose")
else:
print("you win")
else:
print("Invalid play. Check spelling !")
player = False
computer = t[randint(0,2)]
| true |
f12d7347615cdedcb9e8614d2220a462083739e3 | victorcabral029/zipFunctionPython | /zip.py | 483 | 4.125 | 4 |
#Exemplo basico
lista1 = ['Um','Dois','Tres','Quatro']
lista2 = [1,2,3,4]
listaZip = zip(lista1,lista2)
print(listaZip)
#Exemplo Operacao
a = [1,3,5,6]
b = [2,6,7,9]
for i in zip(a,b):
print(i[0]*i[1])
#Exemplo Dicionario
fruits = {
'Laranjas': 7,
'Abacaxis': 3,
'Mangas': 5,
'Goiabas': 5,
'Cajus': 4,
}
lista = zip(fruits.keys(),fruits.values())
print(lista)
#Tamanhos diferentes de lista
a = [1,2,3,4,5]
b = [2,4,6,8,10,12]
c = zip(a,b)
print(c)
| false |
2675cf36e2898ca831f0f3c88d25fdb556414002 | grickoff/GeekBrains_3HW | /6.py | 1,365 | 4.15625 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв
# и возвращающую его же, но с прописной первой буквой.
# Например, print(int_func(‘text’)) -> Text.
def my_title (word):
word = word.title()
return word
print(my_title(input('Введите слово из маленьких латинских букв: ')))
# Продолжить работу над заданием.
# В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в нижнем регистре.
# Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
# Необходимо использовать написанную ранее функцию int_func().
result_list = []
x = input('Введите строку из слов, разделенных пробелом и '
'состоящее из латинских букв в нижнем регистре ')
ww = x.split()
for i in ww:
i = my_title(i)
result_list.append(i)
result_list = ' '.join(result_list)
print(result_list)
| false |
ef2bea49c58a2e7dda39534533fae90292d44f72 | SACHSTech/ics2o-livehack1-practice-SurelyH | /days_hours.py | 531 | 4.34375 | 4 | '''
-------------------------------------------------------------------------------
Name: days_hours.py
Purpose: Hours to days
Author: Huang.S
Created: date in 03/12/2020
------------------------------------------------------------------------------
'''
# input number of hours
hours = float(input("Enter the number of hours: "))
# changing hours to days
days = (hours // 24)
extrahours = (hours % 24)
# output of days + hours
print("The number of days would be " + str(days) + " day(s) and " + str(extrahours) + " hour(s)") | true |
597fe17d3975420cda713999ac3e449ac364225f | stemasoff/CrackingTheCodinglnterview | /Stack/3.2.py | 830 | 4.25 | 4 | '''
Как реализовать стек, в котором кроме стандартных функций push и рор будет
поддерживаться функция min, возвращающая минимальный элемент? Все
операции - push, рор и min - должны выполняться за время 0( 1 ).
'''
class Stack:
minimum = None
def __init__(self):
self.items = []
def push(self, x):
self.items.append(x)
if self.minimum == None:
self.minimum = x
elif x < self.minimum:
self.minimum = x
def pop(self):
return self.items.pop()
def is_empty(self):
return (self.items == [])
def min(self):
return self.minimum
s = Stack()
s.push(54)
s.push(45)
s.push(1)
print(s.min()) | false |
7274e6dfff8a8a440251c5540b5486ab0851adef | Helblindi/ProjectEuler | /21-40/Problem30.py | 1,157 | 4.15625 | 4 | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
import time
import numpy as np
def check(number, power):
string = str(number)
digits = np.array([])
for i in string:
digits = np.append(digits, int(i))
total = 0
for j in digits:
total += j**power
if number == total:
print("here's one: ", number)
return number == total
def main():
start_time = time.time()
total = 0
for num in range(10, 1000001):
if check(num, 5):
total += num
print('adding: ', num)
end_time = time.time() - start_time
print("found %s in %2f seconds." % (total, end_time))
# While not required, it is considered good practice to have
# a main function and use this syntax to call it.
if __name__ == "__main__":
main()
| true |
631e0b3445d7469c373ee3b920de47c5f78d395e | Helblindi/ProjectEuler | /21-40/Problem26.py | 1,144 | 4.1875 | 4 | """
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with
denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a
6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal
fraction part.
"""
import time
def main():
start_time = time.time()
num = longest = 1
for n in range(3, 1000, 2):
# we know that all even numbers will not result in a repeated decimal
if n % 5 == 0:
# go to the next value in the loop
continue
p = 1
while (10 ** p) % n != 1:
p += 1
if p > longest:
num, longest = n, p
end_time = time.time() - start_time
print("found %s in %2f seconds." % (num, end_time))
# While not required, it is considered good practice to have
# a main function and use this syntax to call it.
if __name__ == "__main__":
main()
| true |
0ac6d8684baa9490415a0c5e3df994b575040647 | Helblindi/ProjectEuler | /21-40/Problem35.py | 1,891 | 4.15625 | 4 | """
The number, 197, is called a circlar prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
"""
import time
# driver function for our program
def main():
start_time = time.time()
num_circ_primes = 0
# loop from 2 to 1,000,000 because 1 is not prime!
for i in range(2, 1000001):
if is_circular_prime(i):
num_circ_primes += 1
end_time = time.time() - start_time
print("Found %s in %2f seconds." % (num_circ_primes, end_time))
# check to see if a given value is a circular prime
def is_circular_prime(num):
# for speeds sake, don't even proceed to checking other values if the number itself is not prime
if not is_prime(num):
return False
circ_vals = get_circular_values(num)
for val in circ_vals:
if not is_prime(val):
return False
print(num, ' is a circular prime!')
return True
# function to return all the circular values from a given number
def get_circular_values(num):
circ_vals = []
copy = num
_len = len(str(num)) - 1
# what is the syntax for a do-while loop?? -------------------------------
digit = copy % 10
copy //= 10
copy += (digit * 10**_len)
circ_vals.append(copy)
while copy != num:
digit = copy % 10
copy //= 10
copy += (digit * 10**_len)
circ_vals.append(copy)
return circ_vals
# function to tell us if we have a prime number or not
def is_prime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# While not required, it is considered good practice to have
# a main function and use this syntax to call it.
if __name__ == "__main__":
main()
| true |
e3ea659a83119fbf64ad07c6abfa835118a6e58f | arti-shok/my_python | /.ipynb_checkpoints/table-checkpoint.py | 510 | 4.125 | 4 | value = int(input("Введите номер химического элемента:\n"))
if value:
number_of_element = value
if number_of_element == 3:
print("Li")
elif number_of_element == 25:
print("Mn")
elif number_of_element == 80:
print("Hg")
elif number_of_element == 17:
print("Cl")
else:
print("такого элемента в базе данных нет")
else:
print("Неверный формат входных данных")
| false |
2aabdcae8e38d6ab206ce7ab6973cd82073d425b | IMDCGP105-1819/portfolio-DarrylJF | /ex8.py | 853 | 4.21875 | 4 | portion_deposit = 0.2
current_savings = 0
r = 0.04
months = 0
annual_salary = float(input("Enter your annual salary: "))
semi_annual_raise = float(input("What is the semi-annual raise you expect to recieve (As a decimal): "))
portion_saved = float(input("Enter the percentage of your salary to save (As a decimal): "))
total_cost = float(input("Enter the cost of your dream home: "))
monthly_salary = (annual_salary/12)
interest = (monthly_salary*r)
deposit = (total_cost/portion_deposit)
while current_savings < deposit:
if months != 0 and months % 6 == 0:
current_savings += (monthly_salary) + (interest)
current_savings += (monthly_salary) + (monthly_salary*semi_annual_raise)
months += 1
else:
current_savings+=(monthly_salary) + (interest)
months=months+1
print("Number of months: " , months)
| true |
13abb2314b335eae9c64df4c716899c62a12e100 | IMDCGP105-1819/portfolio-DarrylJF | /ex4.py | 732 | 4.15625 | 4 | # replace these with your own values!
my_name = 'Chris Janes'
my_age = 21 # maybe
my_height = 67 # inches
my_weight = 160 # pounds
my_eyes = 'Green'
my_hair = 'Ginger'
is_heavy = my_weight > 3000
to_kilo = my_weight * 0.45 # kilograms
to_cent = my_height * 2.54 # centimetres
print(f"Let's talk about {my_name}.")
# swap in your preferred pronoun.
print(f"He is {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print(f"It is {is_heavy} that he is overweight.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height} and {my_weight} I get {total}")
print(f"His weight in kilos is {to_kilo}")
print(f"His height in centimetres is {to_cent}" ) | true |
8359343663507cf04b96b677d7aa9ce22d8df538 | vikumkbv/Hacktoberfest-2k19 | /python/isPrime.py | 821 | 4.21875 | 4 | # Run `python isPrime.py` for a standalone prime number checker.
# Import `check_prime` function if integrating into another program.
from math import sqrt
def check_prime(val):
if val <= 1:
return False
else:
for i in range(2, int(sqrt(val)) + 1):
if val % i == 0:
return False
return True
def main():
print("Check if a given integer is a prime number. Enter q to exit.")
while True:
try:
val = input("Enter an integer: ")
if val.lower() == 'q':
break
val = int(val)
if check_prime(val):
print(str(val) + " is a prime number!")
else:
print(str(val) + " is not a prime number!")
except ValueError:
print("That's not an integer! :(")
except:
print("Unknown error occured. Terminating program.")
break
return 0
if __name__ == '__main__':
main()
| true |
126d2d9e537ba919529a95f6304ca38408756d3e | CTEC-121-Spring-2020/mod-3-programming-assignment-blymatthew20 | /Prob-4/Prob-4.py | 1,502 | 4.28125 | 4 | # Module 3
# Programming Assignment 4
# Prob-4.py
# Matthew Bly
# Author: Bruce Elgort
# Date: July 12, 2017
"""
The Elgorte coffee shop sells coffee at $16.50 a pound
plus the cost of shipping. Each order ships for $0.76
per pound plus $1.25 fixed cost for overhead. If the
number of pounds of the coffee order exceeds 10, then
the shipping cost is waived. Write a program that
calculates the cost of an order. Name your function
coffeeProcessor()
"""
def coffeeProcessor():
# define variables
overHead = 1.25
priceOfCoffee = 16.50
# get number of pounds from user
# Fix number 1 added quotation mark to end of string
# Fix number 2 changed evaluate to eval
# Fix number 3 added a second parenthese at the end
quantity = eval(input("How many pounds of coffee would you like to order?"))
# Check number of pounds ordered
# If less than or equal to 10 pounds we must charge for shipping
if quantity <= 10:
shippingPerPound = .76
# Fix number 4 added a colon in front of else
else:
shippingPerPound = 0
# Calculate cost of order
# Fix number 5 the second spelling of quantity was fixed to correct spelling
costOfOrder = (quantity * priceOfCoffee) + (quantity * shippingPerPound) + overHead
# Print result
# Fix number 6 put quotation marks in correct place
print("The cost of the order is:",costOfOrder)
# start the program
# Fix number 7 took the word go out
coffeeProcessor() | true |
ef0b1c7fd00a3b3c75d0fd2e6e6d9dc235088828 | gabrielluchtenberg/Padawan | /Exercicios/blackjack_21/services/somethings.py | 259 | 4.125 | 4 | def proxima():
while True:
choose = input("Quer virar mais uma carta? (S/N): \n").upper()
if choose == 'S':
return True
elif choose == 'N':
return False
else:
print('Opção inválida!')
| false |
6a75f749c80ae40152aac987780fffa1170603b1 | ztxm/Python_level_1 | /lesson3/task6.py | 1,132 | 4.3125 | 4 | """
6) Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно
начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func().
"""
str = "house street sweet car"
new_str = []
print(f"Заданная строка: {str}")
def int_func(word):
return word.lower().title()
print(int_func("house"))
for el in str.split():
new_str.append(int_func(el))
print(f'Итоговая строка: {" ".join(new_str)}') | false |
1bc86bd7d9d64b8ff9f5bb97ba6cce372896ebd0 | ztxm/Python_level_1 | /lesson1/task2.py | 693 | 4.3125 | 4 | """
2. Пользователь вводит время в секундах. Переведите время в часы,
минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.
"""
time_in_seconds = int(input("Введите время в секундах: "))
if time_in_seconds <= 0:
print("Ошибка, время в скундах должно быть больше 0")
else:
hours = time_in_seconds // (60 * 60)
sec = time_in_seconds % (60 * 60)
minutes = sec // 60
seconds = sec % 60
print(f"Время в формате чч:мм:сс = {hours}:{minutes}:{seconds}") | false |
e94eeb996218f6f88b3116cca09142cb6fe9f8f9 | ztxm/Python_level_1 | /lesson4/task2.py | 736 | 4.1875 | 4 | """
2) Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Результат: [12, 44, 4, 10, 78, 123].
"""
my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
res = [12, 44, 4, 10, 78, 123]
print([el for el in my_list for a in res if a == el])
| false |
be3dd70643347324b6611aff9577ab07fe706d27 | guptaavani/Image-Filter | /Code.py | 887 | 4.1875 | 4 | #! /usr/bin/env python3
from PIL import Image
im=Image.open(input("Enter image path \n")) #Taking the image path as input and saving it to im
print("This is the original image you entered \n")
im.show() #Showing the original image
while(True):
n=int(input(" Enter 1 for black and white filter \n Enter 2 for magic filter \n Enter 3 for colour filter \n Enter 4 to exit \n"))
if (n==1):
img=im.convert('L') #Conver the image into black and white image
if (n==2):
r, g, b = im.split()
img=Image.merge("RGB", (b,r,g)) #Change the r,g,b values
if (n==3):
colour=input("Enter valid colour \n")
f=Image.new("RGB", im.size, colour) #Creating a filter of the entered colour
img=Image.blend(im, f, 0.25) #Applying the filter to the image
if (n==4): break #Exit the while loop
img.show() #Showing the image
| true |
2d6678f45d8734eefe8ff7033927e0df2337bf39 | LimZheKhae/DPL5211Tri2110 | /Lab5.3.py | 1,024 | 4.125 | 4 | #Student ID :1201200825
#Student Name :Lim Zhe Khae
#display the menu
# ask user to enter their choice [1 or 2].
#if choice is 1 call function get_cm()
#if choice is 2 call function get_meter()
# Else print "Invalid choice"
# In get_cm();
#Get the value of centimetre from the user
# Call function cm_to_meter()passs and cm to calculate meter
#Display the centimeter and meter
def cm_to_meter(centimeter):
meter=centimeter/100
return meter
def meter_to_cm(meter):
centimeter=meter*100
return centimeter
def get_cm():
cm=float(input("Please enter a value for centimeter: "))
m=cm_to_meter(cm)
print("For {} cm is {} m ".format(cm,m))
def get_meter():
m=float(input("Please enter a value for meter: "))
cm=meter_to_cm(m)
print("For {} m is {} cm ".format(m,cm))
choice=int(input("Please Enter your choice, 1 for cm to meter , 2 for meter to cm :"))
if (choice==1):
get_cm()
elif(choice==2):
get_meter()
else :
print("Invalid choice")
| true |
168774838d17c2fffdae061bfb064a9430102ce6 | pekkipo/DataStructures | /Queue/linkedqueue.py | 675 | 4.25 | 4 | from linkedlist import LinkedList
class LinkedQueue:
"""
This class is a queue wrapper around a LinkedList.
This means that methods like `add_to_list_start` should now be called `push`, for example.
"""
def __init__(self):
self.__linked_list = LinkedList()
def push(self, node):
self.__linked_list.add_start_to_list(node)
def pop(self):
return self.__linked_list.remove_end_from_list()
def find(self, name):
return self.__linked_list.find(name)
def print_details(self):
self.__linked_list.print_list()
def __len__(self): # call: len(variable)
return self.__linked_list.size()
| true |
3da2bf281a303c2d0010173ffcf1441300c66c58 | patdflynn95/Recreational-Projects | /primefactors.py | 944 | 4.46875 | 4 | # Python program to print prime factors
import math
# A function to print all prime factors of
# a given number n
def primefactors(n):
if n < 2:
primefactors(int(input("Please choose a number greater than 1: ")))
return None
# First check if number is even
if n % 2 == 0:
print(2)
while n % 2 == 0:
n = n // 2
# n must be odd at this point
# so a skip of 2 ( i = i + 2) can be used
for i in range(3, int(math.sqrt(n)) + 1, 2):
# while i divides n , print i once and divide n
if n % i == 0:
print(i)
while n % i == 0:
n = n // i
# Condition if n is a prime
# number greater than 2
if n > 2:
print(n)
# Driver Program to test above function
num = 10
primefactors(num)
primefactors(4)
primefactors(1)
| true |
2220e3c8cd04f1a04524e4e0b9c8d0753695c0f7 | moura-pedro/CS106A | /assignment02/khansole_academy.py | 785 | 4.34375 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
GOAL = 3
def main():
correct = 1
while (correct <= GOAL):
num1 = random.randint(10, 99)
num2 = random.randint(10, 99)
answer = num1 + num2
print(f"What is {num1} + {num2}?")
user_answer = int(input("Your answer: "))
if (user_answer == answer):
print(f"Correct! You've gotten {correct} in a row.")
correct += 1
else:
print(f"Incorrect. The expected answer is {answer}")
correct = 1
print("Congratulations! You've achieved your goal!")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
183e78aae1a73b7b0f9533b4874e06828c7a9233 | aditya0697/SortingAlgorithms | /merge_sort.py | 1,426 | 4.125 | 4 | #function of merge
def merge(arr, first, middle, last):
n1 = middle - first + 1
n2 = last - middle
left_array = [0]*n1
right_array = [0]*n2
for i in range(n1):
left_array[i] = arr[first+i]
for i in range(n2):
right_array[i] = arr[middle+1+i]
l_ptr = 0
r_ptr = 0
i=first
while(i != last+1):
if(left_array[l_ptr] < right_array[r_ptr]):
arr[i] = left_array[l_ptr]
l_ptr = l_ptr+ 1
i = i + 1
if(l_ptr >= n1):
while (i != last+1) :
arr[i] = right_array[r_ptr]
i= i+1
r_ptr = r_ptr + 1
else:
arr[i] = right_array[r_ptr]
r_ptr = r_ptr+ 1
i = i + 1
if(r_ptr >= n2):
#i= i+1
while i != last+1 :
arr[i] = left_array[l_ptr]
i= i+1
l_ptr = l_ptr + 1
#function of merge_sort
def merge_sort(arr, first, last):
if first < last :
middle = int((first + (last-1))/2)
#print("first ",first, " last ",last," middle ",middle)
merge_sort(arr, first, middle)
merge_sort(arr, middle+1, last)
merge(arr, first, middle, last)
#Main function
arr = [ 5,6,4,3,90,8,7,1,2,8,7,9,0]
print("length of arr ",len(arr))
print(arr)
merge_sort(arr, 0, len(arr)-1)
print(arr)
| false |
ea7c6189e4214742f6ac654205a0687596bdc9a5 | Nithy-Sree/Crazy-Python- | /colorChanger tkinter.py | 938 | 4.3125 | 4 | # pip install tkinter
# random is built-in module in python
import tkinter as tk
import random
colours = [
'red', 'blue', 'green',
'pink','black', 'yellow',
'orange','white','purple',
'brown']
# create a GUI Window
root = tk.Tk()
# set the size of the window
root.geometry("400x400")
# set the title
root.title("Color Changer")
# function to change the colour of window dynamically
def changeColor():
# choosing random colours from the list
k = random.choice(colours)
root.configure(bg=k)
# to display text in a window
label = tk.Label(root, text="Color Changer in Tkinter", bg="white")
label.pack()
# using button to change the window color
button = tk.Button(text="Change", command=changeColor)
button.pack()
# close the window manually
quit_button = tk.Button(text="Quit", command=root.destroy)
quit_button.pack()
# start the GUI Window
root.mainloop()
| true |
fe5710b591c22d818d09fe50e1b2a115ca424b42 | gauffa/mustached-dubstep | /wip/ch4ex10.py | 1,125 | 4.90625 | 5 | ## Matthew Hall
## ISY150
## Chapter 4
## Exercise 10
## 09/23/2013
##Write a program that calculates and displays a person's BMI. The BMI is
##often used to determine whether a person is overweight or underweight
##for their height.
##A person's BMI is calculated with the following formula:
##BMI = weight * 703 / height^2 (pounds) (inches)
#Identify purpose of script to the user
print("This script will calculate Body Mass Index", \
"(BMI) based on user input.")
def main():
#get input from user
weight = input("What is your weight in pounds?\n")
height = input("What is your height in inches?\n")
#math the input
bmi = (float(weight) * 703) / (float(height)**2)
#determine health level based on bmi
if float(bmi) > 18.5 and float(bmi) < 25:
health = "optimal weight"
elif float(bmi) < 18.5:
health = "underweight"
elif float(bmi) > 25:
health = "overweight"
#provide output of math in readable format
print("With a weight of", str(weight), "pounds and a height of",\
str(height), "inches you have a BMI of", \
format(bmi,'0.2f') + ".\nYou are", health + ".")
main()
| true |
d7fba79908b4eca52d30955abdb6282c917b7e83 | gauffa/mustached-dubstep | /ch7/ch7ex7.py | 700 | 4.15625 | 4 | #Matt Hall
#ISY 150
#Chapter 7 Exercise 7
#10/14/2013
#Write a program that writes a series of random numbers to a file.
#Each random number should be in the range of 1 through 100.
#The application should let the user specify how many random numbers
#the file will hold.
import random
def main():
#take user input
count = int(input("Please enter the amount of numbers to generate:\n"))
#open file to hold output
random_number_file = open('numbers.txt','w')
#iterate for loop 'count' number of times
for x in range(count):
random_number = random.randint(1,100)
random_number_file.write(str(random_number)+"\n")
#close output file
random_number_file.close()
main()
| true |
a0bf4ef24f31754d6916877dea5de800a6bb8a29 | gauffa/mustached-dubstep | /complete/ch3exr6.complete.py | 817 | 4.90625 | 5 | ## Matthew Hall
## ISY150
## Chapter 3
## Exercise 6
## 09/16/2013
##Write a program that calculates and displays a person's BMI. The BMI is
##often used to determine whether a person is overweight or underweight
##for their height.
##A person's BMI is calculated with the following formula:
##BMI = weight * 703 / height^2 (pounds) (inches)
#Identify purpose of script to the user
print("This script will calculate Body Mass Index (BMI) based on user input.")
def main():
weight = input("What is your weight in pounds?\n")
height = input("What is your height in inches?\n")
bmi = (float(weight) * 703) / (float(height)**2)
print("With a weight of", str(weight), "pounds and a height of",\
str(height), "inches you have a BMI of", format(bmi,'0.2f') + ".")
main()
| true |
59d2d20a01653c324ec54b86a61e6d15232eda93 | gauffa/mustached-dubstep | /complete/ch2exr9.complete.py | 2,585 | 4.4375 | 4 | ## Matthew Hall
## ISY150
## Chapter 2
## Exercise 9
## 09/05/2013
## Write a program that converts Celsius temperatures to Fahrenheit temperatures.
## The formula is as follows: F = (9/5) * C + 32 ##triple check this formula!
## The program should ask the user to enter a temperature in Celsius, and then
## display the temperateure convereted to Fahrenheit.
#Tell the user what the program/script does
print("\nThis script will convert a temperature from either Fahrenheit or Celsius to the other scale.")
#I decided to define a little subroutine so I could easily call it again if an
#unacceptable input was given.
def scale_conv():
#Ask the user if the temperature being input is Fahrenheit or Celsius
scale = input("\nWhat scale is your original temperature in [F]ahrenheit or [C]elsius?\n").lower()
#The opscale variable allows for calling a variable instead of using string
#text later in the subroutine
if scale[0] == "f":
opscale = "c"
else:
opscale = "f"
#calculate a celsius temperature based on the input of the user
#Deduct 32, then multiply by 5, then divide by 9
if scale == "fahrenheit" or scale == "f":
print("\nFarenheit it is! Wink-wink!")
OrgTemp = int(input("So, what is the Farenheit temperature that you would like converted to Celsius?\n"))
ConvTemp = (OrgTemp - 32) * 5 / 9
print("\nYour original tempurature of", str(int(OrgTemp)) \
+ chr(176) + str(scale[0].upper()), "converts to", \
str(int(ConvTemp)) + chr(176) + str(opscale[0].upper()) + ".")
#calculate a fahrenheit temperature based on the input of the user
#Multiply by 9, then divide by 5, then add 32
elif scale == "celsius" or scale == "c":
print("\nCelsius it is! Nudge-nudge!")
OrgTemp = int(input("So, what is the Celsius temperature that you would like converted to Farenheit?\n"))
ConvTemp = (((OrgTemp * 9) / 5) + 32)
print("\nYour original tempurature of", str(int(OrgTemp)) \
+ chr(176) + str(scale[0].upper()), "converts to", \
str(int(ConvTemp)) + chr(176) + str(opscale[0].upper()) + ".")
#tell user they didn't choose an acceptable answer
else:
print("Please choose either Farenheit or Celsius. Say no more, eh?")
scale_conv()
#Run the previously defined subroutine
scale_conv()
##Comments:
##I could not for the life of me find a way to 'split' input lines the same way
##I can split other lines or print() lines. Any advice on this would be great! Or
##feel free to tell me that spliting lines isn't important... I would like that.
| true |
580f2b7cbc7424123d3c8d0a6ce57af596740384 | gauffa/mustached-dubstep | /ch9/ch9ex5.py | 2,746 | 4.53125 | 5 | #Matt Hall
#ISY 150
#Chapter 9 Exercise 5
#10/27/2013
#Write a program that asks the user to enter a 10-character telephone number in
#the format XXX-XXX-XXXX. The program should display the telephone number with any
#alphanetic characters that appeared in the orignal translated to their numeric
#equivalent. For example, if the user enters 555-GET-FOOD the app should display
#555-438-3663.
#ABC = 2, DEF = 3, GHI = 4, JKL = 5, MNO = 6, PQRS = 7, TUV = 8, WXYZ = 9
def user_input():
input_str = 'Enter your alpha-numeric phone number (ex. XXX-XXX-XXXX):\n'
ok = False
while ok == False:
try:
input_number = input(input_str)
if input_number == '':
print("Blank input received. Program terminated.")
return
elif len(input_number) != 12:
print("Your phone number length is incorrect.")
elif input_number[3] != '-' or input_number[7] != '-':
print("Your phone number format is incorrect.")
elif input_number.isdigit():
print("Your phone number has no letters.")
else:
ok = True
except ValueError:
print('ERROR: You broked it. Please try again.')
return input_number
def convert_text_to_number(ui_number):
#declare lists
alpha_number_list = []
number_list = []
#declare local variables
phone_numerals = ''
new_var = ''
#transfer user input to list
for x in ui_number:
alpha_number_list.append(x)
#iterate through list and check against below
for x in range(0,12):
old_var = alpha_number_list[x].lower()
if old_var == 'a' or old_var == 'b' or old_var == 'c':
new_var = '2'
elif old_var == 'd' or old_var == 'e' or old_var == 'f':
new_var = '3'
elif old_var == 'g' or old_var == 'h' or old_var == 'i':
new_var = '4'
elif old_var == 'j' or old_var == 'k' or old_var == 'l':
new_var = '5'
elif old_var == 'm' or old_var == 'n' or old_var == 'o':
new_var = '6'
elif old_var == 'p' or old_var == 'q' or old_var == 'r' or old_var == 's':
new_var = '7'
elif old_var == 't' or old_var == 'u' or old_var == 'v':
new_var = '8'
elif old_var == 'w' or old_var == 'x' or old_var == 'y' or old_var == 'z':
new_var = '9'
else:
new_var = old_var
#append output of each iteration to list
number_list.append(new_var)
#put working list into string format
for x in number_list:
phone_numerals += x
return phone_numerals
def output(org_number,new_number):
print('\n\nThe number you originally entered is:\n'+org_number.upper()+\
'\nThe numeral-only phone number is:\n'+new_number+'\n\n')
def main():
ui_number = user_input()
#this return allows the program to terminate
#or handoff to a higher-level program
if not ui_number:
return
else:
phone_numerals = convert_text_to_number(ui_number)
output(ui_number,phone_numerals)
main() | true |
95950e0f1122293126a093150b3ae6154a305f49 | SusyVenta/TrigoPy | /radians_degrees_converter.py | 913 | 4.1875 | 4 | import math
def convert_to(number, to="radians"):
"""
:param number: number to convert
:param to: end unit of measure. default = 'radians'. Alternative = 'degrees'
:return: converted number
"""
if to == "degrees":
print("--------------- degrees to radians: deg * 180 / pi")
return math.degrees(number)
print("--------------- degrees to radians: deg / 180 * pi")
return math.radians(number)
def get_angle_from_ratio(number, ratio="cosine", result_in_degrees=True):
if ratio == "cosine":
angle = math.acos(number)
elif ratio == "sine":
angle = math.asin(number)
elif ratio == "tangent":
return math.tan(number)
if result_in_degrees:
return math.degrees(angle)
# print(get_angle_from_ratio(number=1/6, ratio="sine"))
# print(convert_to(number=2.5, to="degrees"))
print(math.cos(math.radians(9.594068226860461))) | true |
44e548fe4582127455aab4aa14d5e87aca51b4a6 | Akshatha-Udupa/AITPL2108 | /larestofthree.py | 529 | 4.28125 | 4 | #largest of 3 numbers
a = 100
b= 500
c = 00
if a > b and a > c:
print("{0} is largest number".format(a))
elif b > c:
print("{0} is largest number".format(b))
else:
print("{0} is largest number".format(c))
#using function
def largest(a,b,c):
if a > b and a > c:
print("{0} is largest number".format(a))
elif b > c:
print("{0} is largest number".format(b))
else:
print("{0} is largest number".format(c))
largest(0,1,1)
'''output
500 is largest number
''' | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.