blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c3bb54518500f812fc7a04184ac3789384338027 | yuri77/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,256 | 4.21875 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
for i in range(len(arr)):
print("arr", arr)
last_index = len(arr)
current = arr[i]
# TODO: can I find index of the smallest element and the value at the same time, i.e in one loop?
smallest = min(arr[i:last_index])
smallest_index = arr.index(smallest)
arr[i] = smallest
arr[smallest_index] = current
# for i in range(0, len(arr) - 1):
# cur_index = i
# smallest_index = cur_index
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# check first item
# compare against neighbor
# if swap happens continue
# otherwise go to the next index
for i in range(len(arr)):
print("i", i)
for j in range(len(arr)-1-i):
print("j", j)
if arr[j] > arr[j+1]:
tmp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = tmp
print("if arr", arr)
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
list = [6, 2, 5, 4, 1, 3]
# print(bubble_sort(list))
print(selection_sort(list))
| true |
5ad96eda63d0304403695bad58753f9847ea77e4 | DavidIyoriobhe/Week-2 | /Area of a Trapezoid.py | 481 | 4.3125 | 4 | #This is a program is written to calculate the area of a Trapezoid
"""You are given any values to work with, as the program
is only to assist you in solving this problem.
Hence, you will be required to enter values as appropriate."""
a = float(input("Enter a value for the shorter base, a: "))
b = float(input("Enter a value for the longer base, b: "))
h = float(input("Enter a value for height, h: "))
area = (1/2)*(a+b)*h
print("Area of the sector is ", round(area,2))
| true |
8f2cf30c2b3bd9deb637539ad59a7a832d61fb9a | cfrome77/ProgrammingMeritBadge | /python/tempConverter.py | 947 | 4.25 | 4 | #!/usr/bin/env python3
''' Temperature Convertor
Converts from fahrenheit to celsius
'''
done = False # Variable to determine if we are done processing or not
while not done: # Repeat until the done flag gets set
temp = int(input("Enter the temperature in degrees Farenheight (F): ")) # reads in the given input
conversion_result = str((temp - 32) * 5 / 9) + 'C'
# creat the variable for storage the final message
message = ""
# check for temperature below freezing
if temp < 0:
message = "Pack long underwear!"
# check for it being a hot day
if temp > 100:
message = "Remember to hydrate!"
print("The tempature is: " + conversion_result)
print(message)
# looks for the user to enter y,
# otherwise the loop end and the program finishes
done = input("Input another temperature? ").lower() != 'y' # != is 'not equal'
print("Done!") | true |
17c77c097c5964261d819a828c225c80f4ce20a3 | MaheshBhandaree/python | /MinMax.py | 299 | 4.15625 | 4 | a= int(input("Enter First no"))
b= int(input("Enter Second no"))
min=a if(a<b) else b
print("MINIMUM VALUE IS :",min)
# for MAX VAlue
a= int(input("Enter First no"))
b= int(input("Enter Second no"))
c= int(input("Enter Third no"))
max= a if a>b and a>c else b if(b>c) else c
print("Max value:",max) | false |
4ccdec52e51795aa67503fabc1c2b08816440432 | santhoshdevaraj/Algos | /419.py | 1,539 | 4.125 | 4 | # Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's,
# empty slots are represented with '.'s. You may assume the following rules:
# You receive a valid board, made of only battleships or empty slots.
# Battleships can only be placed horizontally or vertically. In other words, they can only be made of
# the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
# At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
# Example:
# X..X
# ...X
# ...X
# In the above board there are 2 battleships.
# Invalid Example:
# ...X
# XXXX
# ...X
# This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
# Follow up:
# Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
count, rows, cols = 0, len(board), len(board[0])
def is_new_ship(row, col):
return True if row < 0 or col < 0 or board[row][col] == '.' else False
for row in xrange(rows):
for col in xrange(cols):
if board[row][col] == 'X' and is_new_ship(row-1, col) and is_new_ship(row, col-1):
count += 1
return count
print Solution().countBattleships([['X', '.', '.', 'X'], ['.', '.', '.', 'X'], ['.', '.', '.', 'X']]) | true |
3fa3618c5d43b2c07b26a46b32d8d7eecfc48f2f | Ezlan97/python3-fullcourse | /fullcourse.py | 2,659 | 4.28125 | 4 | #import libary
from math import *
#simple print
print("Hello World!")
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
#variable
name = "John"
age = 25
print("There once was a man name " + name + ", ")
print("he was " + str(age) + " years old.")
print("he really liked the name " + name + ", ")
print("but didn't like being " + str(age) + ".")
#new line, quote
print("first line \n second line")
print("quote\"")
#basic string function
print(name.lower())
print(name.upper())
print(name.isupper()) #return true or false if it uppercase or not
print(name.upper().isupper()) #more than one function
print(len(name)) #string lenght
print(name[0]) #return character by using index number
print(name.index("J")) #return character index number
print(name.replace("John", "Mike")) #replace word or letter (default, change)
#basic int
num1 = -5
print(abs(num1)) #return absulate number
print(pow(3, 2)) #power function
print(max(4, 6)) #return highest number between two
print(round(3.4)) #return rounded number
print(sqrt(9)) #return square root parameter number
#input
userName = input("Enter your name: ")
userAge = input("Enter your age: ")
print("Hello " + userName + "!!, your age is " + userAge)
num1 = input("Enter first number:")
num2 = input("Enter second number:")
result = float(num1) + float(num2) #convert string to int
print("Total = " + str(result))
#function
def sayHi():
print("Hello User")
sayHi()
def profile(name, age):
print("Hello " + name + " " + age)
profile("Eizlan", "22")
def cube(num):
return num*num*num
print(cube(3))
#if else
isMale = True
isTall = True
if isMale or isTall: #true if either true
print("You are a male or tall")
elif isMale and not(isTall):
print("You are short male")
else:
print("You are female")
#comparison
def maxNum(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
print(num1 + " is the largest number!")
elif num2 >= num1 and num2 >= num3:
print(num2 + " is the largest number")
elif num1 == num2 and num2 != num3:
print("all the three number is the same number")
else:
print(num3 + " is the largest number")
maxNum("3","1","2")
#Dictionary
monthConversion = {
"Jan" : "January",
"Feb" : "Febuary",
"Mar" : "March",
"Apr" : "April",
"May" : "May",
"Jun" : "June",
"Jul" : "July",
"Aug" : "August",
"Sep" : "September",
"Oct" : "October",
"Dec" : "December",
}
print(monthConversion.get("Mar"))
#while loop
i = 1
while i <= 10:
print(i)
i += 1 | true |
249d5c418b62ac935e377286bd77c00bfe0fcc50 | ppaul456/Python | /Assignments/homework_assignment_3/working_with_lists.py | 856 | 4.15625 | 4 | #Pohsun Chang
#830911
#MSITM6341
#09/17/2019
grocery_items = ['Apple','Orange', 'Steak', 'Chicken', 'water']
# create 5 items in a list
price_of_grocery_items = [40,30,60,50,10]
# ceate each item's price in another list
print(grocery_items)
print(price_of_grocery_items)
print(grocery_items[2]+' costs $'+str(price_of_grocery_items[2]))
#Print the 3rd item followed by it’s price
print(grocery_items[-1]+' costs $'+str(price_of_grocery_items[-1]))
#Print the last item followed by it’s price
grocery_items.append('watermelon')
price_of_grocery_items.append(25)
#add something to the last(append)
print(grocery_items)
print(price_of_grocery_items)
del grocery_items[0]
del price_of_grocery_items[0]
#delete [0] elements from both lists
price_of_grocery_items[1] = 120
#Double the price of the 2nd item
print(grocery_items)
print(price_of_grocery_items)
| true |
97c162ba4d94d9563b62768d5ed2c3faec5ecd59 | mcharanrm/python | /stack/maximum_element.py | 651 | 4.3125 | 4 | '''Find the maximum element in the stack
after performing few queries
1 x -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.
'''
#ProblemStatement:
#https://www.hackerrank.com/challenges/maximum-element/problem
def maximum_element_modified(n): #saving time from finding max_element
stack=list()
for i in range(n):
x,*y=tuple(map(int,input().strip().split()))
if x==1: stack.append(y[0])
if x==2: stack.pop()
if x==3: print(max(stack))
if globals()['__name__']=='__main__':
n=int(input().strip())
maximum_element_modified(n)
| true |
7f68390c001467a4904cbecb34d490161f24ca19 | SoftwareIntrospectre/Problem-Solving-Practice | /Convert_lambda_to_def.py | 795 | 4.34375 | 4 | # Convert a Lambda Expression into a def statement (function)
##Example 1: Check if a number is even
# Step 1: Take original lambda expression
even = lambda num: num % 2 == 0
print even(4) # returns True
print even(5) # returns False
# Step 2: Convert syntax to def statement
def even(num):
return num % 2 == 0
print even(10) # returns True
print even(11) # returns False
#===================================================================
## Example 2: Grabs the first character of a string
first = lambda s: s[0]
print first('rope')
def first:
#===================================================================
## Example 3: Reverse a string
rev = lambda str: str[::-1]
print rev("rope")
def reversed(str):
rev = str[::-1]
return rev
print reversed("rope")
| true |
e3abca0fbb77725fc086141f6e88f063447ddcc3 | SoftwareIntrospectre/Problem-Solving-Practice | /InheritanceWithMeals.py | 841 | 4.46875 | 4 | # Use inheritance to create Derived Classes: Breakfast, Lunch, and Dinner from the Base Class: Meal
class Meal(object):
def __init__(self):
print 'This is a meal'
def timeOfDay(self):
print 'Any time of day'
class Breakfast(Meal):
def __init__(self):
Meal.__init__(self)
print 'This is breakfast'
def timeOfDay(self):
print 'Morning'
class Lunch(Meal):
def __init__(self):
Meal.__init__(self)
print 'This is lunch'
def timeOfDay(self):
print 'Afternoon'
class Dinner(Meal):
def __init__(self):
Meal.__init__(self)
print 'This is dinner'
def timeOfDay(self):
print 'Evening'
b = Breakfast()
l = Lunch()
d = Dinner()
print b.timeOfDay()
print l.timeOfDay()
print d.timeOfDay()
| true |
bdaaec8409cf7802b77a636ddd742aecd3ac2655 | Shaaman331/Aula-Python-Pro | /Aulas/Aula10.For.py | 697 | 4.71875 | 5 | '''
For
* Um loop for é usado para iterar sobre uma sequência (que é uma lista, uma tupla, um dicionário,
um conjunto ou uma string).
* Isso é menos parecido com a palavra-chave for em outras linguagens de programação e funciona mais
como um método iterador encontrado em outras linguagens de programação orientadas a objetos.
* Com o loop for, podemos executar um conjunto de instruções, uma vez para cada item em uma lista,
tupla, conjunto etc.
'''
nome = "Tarcisio"
for v in nome:
print(v)
print()
for i in range(len(nome)):
print(i, nome[i])
print()
for i, v in enumerate(nome):
print(i, nome[i])
print()
for i, v in enumerate(nome):
print(i, v)
print()
| false |
029335d2052a04d8536a1fddf930c502e7f1f0b5 | Shaaman331/Aula-Python-Pro | /Aulas/Aula12.Interando.Dicionario.py | 1,157 | 4.5625 | 5 | ''' O dicionário possue métodos destinados a interação sobre seus elementos,
você consegue interar diretamente sobre o dicionário usando o laço For
* O métodos keys() retonará uma lista de todas as chaves do dicionário,
* O método values() retornará uma lista de todos os valores no dicionário.
* É possivel fazer o desenpacotamento usando o método itens()
* o método items() retornará cada item em um dicionário, como tuplas em uma lista.
* A lista retornada é uma visão dos itens do dicionário, o que significa que qualquer
das alterações feitas no dicionário serão refletidas na lista de itens.
* o método pop() remove o item com o nome de chave especificado:
'''
print('Interação de Dicionário')
linguas = {'br' : 'português', 'eua' : 'inglês', 'es' : 'espanhol' }
print(linguas)
print()
print('Chave')
for chave in linguas:
print(chave)
print()
print('Valor')
for chave in linguas.values():
print(chave)
print()
print('Desenpacotamento')
for chave, valor in linguas.items():
print(chave, valor)
print()
print(linguas)
print()
print('Removendo valor')
linguas.pop('br')
print(linguas)
print()
| false |
fded2bf256ad45b75f0e9f4dc0ff364f942a5181 | mirondanielle/hello-world | /Week1project6 - Miron.py | 759 | 4.34375 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> radius = float(input("Enter the radius: "))
Enter the radius: 7
>>> area = 3.14 * radius ** 2
>>> print ("The area is", area, "square units.")
The area is 153.86 square units.
>>> radius = float(input("Enter the radius: "))
Enter the radius: 6.31
>>> area = 3.14 * radius ** 2
>>> print ("The area is", area, "square units.")
The area is 125.02255399999999 square units.
>>> radius = float(input("Enter the radius: "))
Enter the radius: 14.96
>>> area = 3.14 * radius ** 2
>>> print ("The area is", area, "square units.")
The area is 702.7370240000001 square units.
>>> | true |
1077fb7bcd3c578e896ae9bbdf7b82e5a5c85b63 | mirondanielle/hello-world | /Week4pi.py | 280 | 4.15625 | 4 | iterations = int(input("Enter the number of iterations: "))
piFour = 0
numerator = 1
denominator = 1
for count in range(iterations):
piFour += numerator / denominator
numerator = -numerator
denominator += 2
print("The aprroximation of pi is", piFour * 4)
| false |
ebb0a30391415bf601c50a11d56c365703cebc16 | siyengar88/Python4selenium | /DemoTest1/InterchangeFLinList.py | 425 | 4.46875 | 4 | #Python program to interchange first and last elements in list
li=[1,2,3,4,5,6,7,8]
print("{} {}".format("Original List: ",li))
temp=li[-1] #storing the last element in a temporary variable
li[-1]=li[0] #Bringing first element to last position
li[0]=temp #storing last element in first position
print("Exchanging first and last elements in the list.")
print("{} {}".format("List after exchange: ",li)) | true |
3c127048a5aaff0b8a4d6f41fdfccd821c25ceb8 | techsparksguru/python_ci_automation | /Class2/python_functions.py | 1,167 | 4.78125 | 5 | """
https://www.tutorialspoint.com/python3/python_functions.htm
https://docs.python.org/3/library/functions.html
https://realpython.com/documenting-python-code/
"""
# Creating a function
def my_function():
print("Hello from a function")
# Calling a Function
my_function()
## Functions with arguments/Parameters
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
# Multiple arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
# Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# Passing value to the arguments in the calling function
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
## Functions with default parameter values
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
# Return Statement
def my_function(x):
return 5 * x
print(my_function(3)) | true |
91158d5f59f950c22ac811b0f9125c10c6da71f6 | DtjiPsimfans/Python-Set | /python_set.py | 1,544 | 4.28125 | 4 | # Python Set
class PythonSet:
"""
This class contains attributes of a python set.
"""
def __init__(self, elements=[]):
# type: (list or str) -> None
self.elements: list = [] # initial value
for element in elements:
if element not in self.elements:
self.elements.append(element)
self.elements = sorted(self.elements)
def add(self, element):
# type: (object) -> bool
if element not in self.elements:
self.elements.append(element)
self.elements = sorted(self.elements)
return True
return False
def remove(self, element):
# type: (object) -> bool
if element in self.elements:
self.elements.remove(element)
return False
return True
def concat(self, other):
# type: (PythonSet) -> None
for element in other.elements:
self.add(element)
def subtract(self, other):
# type: (PythonSet) -> None
for element in other.elements:
self.remove(element)
def clear(self):
# type: () -> None
self.elements = []
def length(self):
# type: () -> int
return len(self.elements)
def __str__(self):
# type: () -> str
return str(self.elements)
# Testing
a: PythonSet = PythonSet()
b: PythonSet = PythonSet([1, 2, 3])
c: PythonSet = PythonSet([1, 4, 4, 2])
d: PythonSet = PythonSet("abc")
print("a = " + str(a))
print("b = " + str(b))
print("c = " + str(c))
print("d = " + str(d))
a.add(5)
print("a = " + str(a))
a.concat(b)
print("a = " + str(a))
a.concat(c)
print("a = " + str(a))
a.subtract(b)
print("a = " + str(a))
b.subtract(c)
print("b = " + str(b)) | true |
c8fae950c0238d63e5a2e3e2dc3eecec4e87383e | ErhardMenker/MOOC_Stuff | /fundamentalsOfComputing/interactiveProgramming/notes_acceleration&friction.py | 808 | 4.21875 | 4 | ## The spaceship class has two fields:
# self.angle is the ship orientation (the angle, in radians, of the ship's forward velocity from the x-axis)
# self.angle_vel is the speed in which the ship moves in the current direction
## Acceleration
# Acceleration can be modeled by increasing the velocity with time, just as in Pong...
# ...increasing the velocity increased the speed with time (positive 2nd derivative!)
# Acceleration adds itself to the velocity vector for every time step. This velocity...
# ...vector is in turn added to the position vector.
# The acceleration vector is given as: forward = [math.cos(self.angle), math.sin(self.angle)]
## Friction
# Friction can be modeled by scaling the velocity vector by a slightly negative number...
# In the limit, the velocity vector will go to zero.
| true |
a7d76c6044048cf5775dc5b92e90536fa3acfbac | ErhardMenker/MOOC_Stuff | /fundamentalsOfComputing/interactiveProgramming/notes_variables.py | 1,056 | 4.375 | 4 | # variables - placeholders for important values
# used to avoid recomputing values and to
# give values names that help reader understand code
# valid variable names - consists of letters, numbers, underscore (_)
# starts with letter or underscore
# case sensitive (capitalization matters)
# legal names - ninja, Ninja, n_i_n_j_a
# illegal names - 1337, 1337ninja
# Python convention - multiple words joined by _
# legal names - elite_ninja, leet_ninja, ninja_1337
# illegal name 1337_ninja
# assign to variable name using single equal sign =
# (remember that double equals == is used to test equality)
# examples
my_name = "Erhard Menker"
print my_name # returns: "Erhard Menker"
my_age = 22
print my_age #returns: 22
# birthday - add one
my_age += 1 #the += operator adds the LHS to the other values in the RHS, storing back in LHS variable
print my_age
# the story of the magic pill
magic_pill = 30
print my_age - magic_pill #outputs -8, or result of 22 - 30
my_grand_dad = 74
print my_grand_dad - 2 * magic_pill #returns 14, or value of 74 - 30*2
| true |
220e2b2bfd11ceff670fae721a0b0211830bf0c3 | xzpjerry/learning | /python/est_tax.py | 1,885 | 4.21875 | 4 | #! /usr/bin/env python3
'''
Estimating federal income tax. Assignment 1, CIS 210
Authors: Zhipeng Xie
Credits: 'python.org' document
Inputer income and num_of_exemption, output tax.
'''
def brain (temp_income, temp_num_of_exempt):
'''
(float or int, int) -> float
return estimated tax result (result) based on
the income and the number of exemption, is the
brain of est_tax function, which is in charge of
the computation.
>>> brain(2000,2)
0
>>> brain(20000,2)
380
>>> brian(0,2)
0
'''
if temp_income <= 10000:
result = 0
return result
else:
Standard_Deduction = 10000
One_exemption_amount = 4050
tax_rate = 0.2
money_table = temp_income - Standard_Deduction - ( temp_num_of_exempt * One_exemption_amount)
result = money_table * tax_rate
return result
def est_tax(income, num_of_exempt):
'''
(float or int, int) -> string
print estimated tax information based on
income and number of exemption.
None value is returned, its job is check the arguments
eligibility and uses the result of brain function.
>>> est_tax(abc, efg)
Bad number(s)
>>> est_tax(30000,0.5)
Bad number(s)
>>> est_tax(20000,2)
Estimated federal income tax for
reported income: $ 20000.00
with 2 exemptions,
using standard deduction $10000 and
an assumed 20% tax rate is : $380.00
'''
if isinstance(income,(int,float)):
if isinstance(num_of_exempt,(int)):
if income >= 0:
print('''Estimated federal income tax for
reported income: $ %.2f
with %d exemptions,
using standard deduction $10000 and
an assumed 20%% tax rate is : $%.2f''' % (income, num_of_exempt,brain(income,num_of_exempt)))
else:
raise TypeError('Bad number(s)')
est_tax(20000,2) | true |
6a7d1eb11c8fe77bba32e59e760a9889746cf131 | zhangzhongyang0521/python-basic | /python-sequence/sequence-feature.py | 2,282 | 4.28125 | 4 | # 序列是一块用于存放多个值的连续内存空间,并按照一定顺序排列,每个元素都有一个索引
# python中常见的序列:列表、元组、集合、字典和字符串
# 索引,python中的序列索引从0开始(从左到右),从-1开始(从右到左)
words = ["AA", "BB", "CC", "DD", "EE"]
print(words[2])
print(words[-1])
# 切片,访问序列中一定范围的元素,可以通过切片生成新的序列
# 语法格式:sname[start:end:step],其中start如果不指定默认为0,end若不指定默认为序列的长度,step若不指定默认为1
print(words[1:3])
print(words[0:5:2])
# 复制整个列表时,可以同时省略start和end
copy_words = words[:]
print(copy_words == words)
print(copy_words)
# 序列相加,python中支持两种类型相同的序列相加(使用+号),不会去重元素。
# 相加的两个序列必须是同种类型(同为列表,元组、集合等),序列中的元素类型可以不相同
prices = [10.90, 21.86, 15.56]
names = ["python入门", "Java入门"]
print(prices + names)
# print(prices + "prices"),因是不同类型,会导致运行异常TypeError: can only concatenate list (not "str") to list
# 序列乘法,使用数字n乘以序列,会生成新的序列,新序列中重复n次原来的序列
print(prices * 2)
empty_list = [None] * 5
print(empty_list)
# 检查元素是否是序列的成员,语法结构 value in sequence
print(10.90 in prices)
print(18.88 in prices)
print(18.88 not in prices)
# 检查序列的长度(使用len()函数)、最大值(使用max()函数)和最小值(使用min()函数)
print(len(prices))
print(max(prices))
print(min(names))
# 序列的常用内置函数
# list() 将序列转为列表
price_list = list(prices)
print(type(prices), type(price_list))
# str() 将序列转为字符串
price_str = str(prices)
print(price_str)
print(type(prices), type(price_str))
# sum() 计算元素和
print(sum(prices))
# sorted() 对序列进行排序
print(sorted(prices))
# reversed() 反向序列中的元素
for price in reversed(prices):
print(price, end=" ")
print()
# enumerate() 将序列组合为组合为索引序列,常在for循环中用
for price in enumerate(prices):
print(price, end=" ")
| false |
15c5cdcc306952ab21b7afed16435aad8cd3e8eb | zhangzhongyang0521/python-basic | /python-quickstart/comment.py | 1,140 | 4.1875 | 4 | # -*- coding:utf-8 -*-
# coding=utf-8
'''
@ description: according to height and weight to calc BMI
@ author: tony.zhang
@ date: 2020.06.20
'''
"""
another format multiline comment
"""
print('''according to height and weight to calc BMI''')
# ================application begin================
# input your height and weight
height = float(input("your height:"))
weight = float(input("your weight:"))
bmi = weight / (height * height)
print("your bmi:" + str(bmi))
# judge your body shape
if bmi < 18.5:
print("over light")
if 18.5 < bmi < 24.9:
print("good fit")
if 24.9 < bmi < 29.9:
print("over weight")
if bmi >= 29.9:
print("too fat")
# over size content process,use () to link
content = ("Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments"
"Some types, such as ints, are able to use a more efficient algorithm when")
print("content:" + content)
# !!!!!not recommend way to process over size content
value = "Return the canonical string representation of the object.\
For many object types, including most builtins, eval(repr(obj)) == obj."
print("value:" + value)
| true |
4a849488c7669e1a41a05fa101f675d3940385c4 | dahlvani/PythonTextProjects | /String Information.py | 798 | 4.28125 | 4 | def reverse(s):
str = ""
for i in s:
str = i + str
return str
print("Your reversed string is", str)
def countvowels(s):
num_vowels=0
for char in s:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
print ("Your string has", num_vowels, "vowels")
#I call a function inside a function here.
def palindrome(s):
if reverse(s) == s:
print("This is a palindrome")
else:
print("This is not a palindrome.")
answer = input("Do you want information on your string? Y or N\n").upper()
#Note it does not matter if the user enters a capital or lowercase letter
if answer == "Y":
string = input("Please enter your string\n")
reverse(string)
countvowels(string)
palindrome(string)
else:
print("Okay. Maybe later.")
| true |
108bda1e87d44a3b1839c6665e833c9247e0a669 | nicklutuxun/Calculator-of-pi | /Calculator of pi.py | 782 | 4.28125 | 4 |
# coding: utf-8
# In[ ]:
import matplotlib.pyplot as plt
import time
#n is the term of Maclaurin series
print('Hi! This is a program to calculate the approximate value of pi')
n=int(input('Please enter n:'))
#Time starts
time_start=time.time()
sum_i=0
for i in range(1,n+1):
sum_i=(sum_i+(-1)**(i-1)/(2*i-1))
sum=4*sum_i
x_values = i
y_values = sum
plt.scatter(x_values, y_values, s=5)
plt.title('Calculation of pi', fontsize=24)
plt.xlabel('Value of n',fontsize=20)
plt.ylabel('Value of sum',fontsize=20)
#Time ends
time_end=time.time()
time=time_end-time_start
print('The approximate value of pi=', end='')
print(sum)
print('Time used:',end=' ')
print(time,end='')
print('s')
print('Here is the graph how the sum approaches to pi')
plt.show()
| true |
c30b0d745e69c5fe6f9333188a7fd61fe2ae66d7 | Rishi-saw/Python-3 | /objectOrientedProgrammingUsingPython/operatorOverloadingDunderMethods.py | 1,481 | 4.375 | 4 | class Salary:
'''__funcname__ are known as duncder methods particularly used for operator overloading and object value management'''
def __init__(self, amount, type):
self.amount = amount
self.type = type
def __add__(self, other): # this is a dunder method
return self.amount + other.amount
def __repr__(self):
'''this is used to briefly describe the object'''
return f'Salary({self.amount}, \'{self.type}\')'
def __str__(self):
'''this is used to summarise the object'''
return f'Salary is {self.amount}, Type of Salary is {self.type}'
main_sal = Salary(50000, 'Main Salary')
other_sal = Salary(20000, 'Tution Salary')
print(main_sal + other_sal) # operator overloading
print()
print(main_sal) # always call __str__()
print(other_sal) # always call __str__()
print()
# to call __repr__()
print(repr(main_sal))
print(repr(other_sal))
'''
# Program to add more than 2 objects
class A:
def __init__(self, number):
self.num = number
def __add__(self, other):
return self.num + other.num
a1 = A(12)
a2 = A(15)
a3 = A(17)
lst = [a1, a2, a3] # list of objects
sum = 0
for i in range(1, len(lst)): # iterating over list of objects
sum = lst[i] + lst[i - 1] # adding 2 value at a time and storing it to an other variable for future uses
print(sum)
''' | true |
7b99aa93a301e94aded9d77c093ad4db771326b3 | fe-sts/CampinasTech | /Trilha_Python_001/Exercício_009.py | 484 | 4.15625 | 4 | '''
9. Elabore um algoritmo em Python que calcule a área e o perímetro de um círculo, sabendo que A = πr² e P=2πr.
'''
import math
raio = float(input('Digite o raio do circulo em metros: ').strip())
area = math.pi * (raio ** 2)
print('A area do círculo é {:.2f}'.format(area)) #mostra 2 casas decimais após .
perimetro = 2 * (math.pi * (raio ** 2))
print('O perímetro para este raio é {:.2f}'.format(perimetro))
#perimetro = float(input('Digite o perímetro: ').strip()) | false |
c12b18f8584ae8610cf68d07b7f38b2e7b5aa79a | fe-sts/CampinasTech | /Trilha_Python_001/Exercício_012.py | 427 | 4.3125 | 4 | '''
12. Elabore um algoritmo em Python que:
a) Primeiro exiba uma mensagem de boas vindas;
b) Pergunte o nome do usuário;
c) Exiba uma mensagem dizendo uma mensagem de olá
seguida pelo nome do usuário seguida por outra mensagem
fazendo um elogio.
'''
print('Bem vindo!')
nome = str(input('Qual o seu nome? ').strip())
print('Olá {}! Você tem um nome muito bonito! Show de bola!\nVou colocar no meu filho!'.format(nome))
| false |
9623052ed6b863c5001d9331c0536eeefe22dad9 | DesLandysh/My100daysPath | /003_of_100/3_1.py | 201 | 4.28125 | 4 | # Odd or even
number = int("33") # int(input("which number do you want to check? "))
if number % 2 == 0:
print(f"this number {number} is even.")
else:
print(f"this number {number} is odd.")
| true |
5504a7da4128f03acc7902f0d0a7f6ecbf558f0f | DesLandysh/My100daysPath | /009_of_100/9_1.py | 837 | 4.3125 | 4 | # Grading program
# database of student_scores in dict names: scores
# write a program that converts their scores to grades. -> new dict
# DO NOT modify student_score dict
# DO NOT write any print statements.
# scores 91 - 100 = "Outstanding"
# scores 81 - 90 = "Excedds Expectations"
# Scores 71 - 80 = "Acceptable"
# scored 70 or lower: Grade = "Fail"
student_scores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
student_grades = {}
for key in student_scores:
if student_scores[key] > 90:
student_grades[key] = "Outstanding"
elif 80 < student_scores[key] <= 90:
student_grades[key] = "Exceeds Expectation"
elif 70 < student_scores[key] <= 80:
student_grades[key] = "Acceptable"
else:
student_grades[key] = "Fail"
print(student_grades)
| true |
56071b2d97462c397320f8e07decb48e6ee2993e | Aungmyintmyat97/testing | /string.py | 1,359 | 4.1875 | 4 | 'hello' + "world"
'\"yes,\" I am.'
'\"yes\", we are.'
print('\"yes\", we are')
print('\"NO,\" we aren\'t')
>>> '\"yes,\" I am.'
'"yes," I am.'
>>> '\"yes\", we are.'
'"yes", we are.'
>>> print('\"yes\", we are')
"yes", we are
>>> print('\"NO,\" we aren\'t')
"NO," we aren't
>>> print('\'no,\' we aren\'t')
'no,' we aren't
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name
'hello' + ' ' + 'world'
('hello' + ' ' + 'world') * 3
>>> x = 'laptop'
>>> x[:]
'laptop'
>>> x[0:2]
'la'
>>> x[3:]
'top'
>>> x[:2]
'la'
>>> x = 'laptop'
>>> x[:]
'laptop'
>>> x[0:3]
'lap'
>>> x[3:]
'top'
>>> x[:3]
'lap'
>>> x[1]
'a'
>>> x[:3] + x[3:]
'laptop'
>>>
>>> x[-1]
'p'
>>> x[:7]
'laptop'
>>> len(x)
6
>>> len(x[0:3]) + 4
7
>>> 'string' + str(21)
'string21'
>>> 23 + int('2')
25
#string are immutable
>>> x[1:3] + 'p'
'app'
>>> x = [2, 4, 6, 8, 10]
>>> y = [1, 3, 5, 7, 9]
>>> x + y
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
>>> print(x + y)
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
>>> print(x,y)
[2, 4, 6, 8, 10] [1, 3, 5, 7, 9]
>>> print([x,y])
[[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
>>> x[0] = 5
>>> x
[5, 4, 6, 8, 10]
>>> a = [1, 2, 3, 4, 5]
>>> b = [6, 7, 8, 9, 10]
>>> c = ['l', 'o', 's', 't']
>>> x = [a, b, c]
>>> x
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ['l', 'o', 's', 't']]
>>> x[2][3] = 'e'
>>> x
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ['l', 'o', 's', 'e']] | false |
590f0f9c8f8aaac4fd1c9d6f8ca4bbae283ac85b | thomaskellough/PracticePython | /Exercise 11 - Check Primality Functions.py | 537 | 4.21875 | 4 | """
Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors).
You can (and should!) use your answer to Exercise 4 to help you.
"""
your_number = int(input('Give me a number.\n'))
def prime(number):
count = 0
for num in range(1, number):
if number % num == 0:
count += 1
if count > 1:
return 'Your number is not prime'
else:
return 'Your number is prime'
print(prime(your_number))
| true |
30ba4e7f235af64f1634a722113eeea48cafcf55 | williancae/pythonGuanabara | /mundo01/Aulas de Conteudo/a02_tipoPrimitivos#06.py | 1,227 | 4.21875 | 4 | # '''Metodos de entrada e Saida'''
# # n1 = int(input('digite um numero: ')) #é nescessario dizer que tipo de valor voce recebe int(),float(),bool(),str()
# # n2 = int(input('Digite segundo numero: '))
# # s = n1 + n2
# # print('A some é ',s)
# # print('A soma vale {}'.format(s))
# # ==================
# Exemplo
# n1 = (input('digite um numero: '))
# n2 = int(input('Digite segundo numero: '))
# # s = n1 + n2
# # print('A some é ',s)
# # print('A soma vale {}'.format(s))
# print(n1.isnumeric()) #Verifica se o numero é numerico se sim True se não False
# print(n1.isalpha()) #Apenas Letras
# print(n1.isalnum()) #letras e numeros
# print(n1.isupper()) #Verifica se é apenas maiuscula
#
# ============ Pratica ==============
# # numero 1
# a = int(input('1° numero: '))
# b = int(input('2° numero: '))
# soma = a + b
# print('A soma de {} e {} é {}'.format(a,b,soma))
# # numero 2
# a = input('Digite um numero: ')
# print(a.isalnum()) #letras e numeros
# print(a.isupper()) #lestras todas em maiusculo
# print(a.isalpha()) #se contem apenas letras
# print(a.isnumeric()) #se contem apenas numero
# print(a.isdecimal()) #Verifica se é um numero de ponto flutuante
# print(a.isspace()) #verifica se é um espaço | false |
c19bbd21a3956fdc109a8e205ff179f7d2055c8d | w3cp/coding | /python/python-3.5.1/4-control-flow/17-func-lambda-expressions.py | 782 | 4.3125 | 4 | # Small anonymous functions can be created with the lambda keyword.
# This function returns the sum of its two arguments: lambda a, b: a + b .
# Lambda functions can be used wherever function objects are required.
# They are syntactically restricted to a single expression.
# Semantically, they are just syntactic sugar for a normal function
# definition. Like nested function definitions, lambda functions can
# reference variables from the containing scope:
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
# The above example uses a lambda expression to return a function.
# Another use is to pass a small function as an argument:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = lambda pair: pair[1])
pairs
| true |
f45117116f0c463dfe6cbe9657e78cbf838692b1 | SuguruChhaya/python-tutorials | /Data Structures and Algorithms/mergeS.py | 2,776 | 4.21875 | 4 | #Practicing mergeosrt iterative
def merge(arr, arrEmpty, l, m, r):
#Define 3 pointers
#Beginning of first subarray
a = l
#Beginning of second subarray
b = m+1
#Beginning of big subarray we are copying into
c = l
#I think I can check for special case. I can do it after the solution works.
#When there are elements left in both subarrays.
while a < m+1 and b < r+1:
if arr[a] <= arr[b]:
arrEmpty[c] = arr[a]
a += 1
else:
arrEmpty[c] = arr[b]
b+=1
c+=1
while a < m+1:
arrEmpty[c] = arr[a]
a+=1
c+=1
while b < r+1:
arrEmpty[c] = arr[b]
b+=1
c+=1
def merge_pass(arr, arrEmpty, lenArr, size, moveToarrEmpty):
#Initially set the starting l value
l = 0
#Could be a little confusing but I thought of it this way.
#If l = 0 and size = 2, and lenArr = 3, this should be permitting because we will still have 1 element as the right subarray. But when size=3, that shouldn't be allowed because no room for right subarray.
#Or more simply, index_based + len_based = len_based. Since we are comparing 2 len_based items, a simple < will work.
while l + size < lenArr:
#Set mid.
m = l+size-1
r = m+1+size-1
#Depending on which one list we are copying into, we have to pass different.
#I have to add a specific case for r
#Remember that even if left subarray is huge, right subarray could only be len 1.
#For example, if I sort arr with length 5, the final step will be to combine subarray with len 4 and 1.
#In this case, r will be incorrect so we have to check for this case.
if r >= lenArr:
r = lenArr-1
if moveToarrEmpty:
merge(arr, arrEmpty, l, m, r)
else:
merge(arrEmpty, arr, l, m, r)
#Update l
l = r+1
#Copy remaining elements
if moveToarrEmpty:
#We have to copy anthing remaining in arr to arrEmpty
#Go from the last l to index lenArr -1 so go through all elements.
for i in range(l, lenArr):
arrEmpty[i] = arr[i]
else:
for i in range(l, lenArr):
arr[i] = arrEmpty[i]
def mergesort(arr):
#Set the initial subarray size
size = 1
#Find the length
lenArr = len(arr)
#We will initially move the items into arrEmpty
moveToarrEmpty = True
#Create empty list
arrEmpty = [0] * lenArr
#Both based on length
while size < lenArr:
merge_pass(arr, arrEmpty, lenArr, size, moveToarrEmpty)
size *= 2
moveToarrEmpty = not moveToarrEmpty
arr = [3, 1, 6, 2, 5, 0, 5, 1, 3, 5.6, 4, 1, 0]
mergesort(arr)
print(arr) | true |
28311956d8c5c460f7b516211d30594e0f3036c8 | austinjalexander/sandbox | /c/learntoprogram/week1/code_compare/user_input.py | 849 | 4.28125 | 4 | # notice how we don't have to explictly declare the types
# of each variable (e.g., int, double, etc.);
# moreover, we can actually put an integer in a variable on
# one line and then put a string in the same variable on the next;
# oh boy can this dupe us!
integer_number = 0
decimal_number = 0.0
my_string = "Your Name Here"
valid = True
print "\nhello, world - from: " + my_string
print "\nPlease enter a number, then I'll double it:",
# raw_input() is used to get input from the user
integer_number = raw_input()
print "You entered: " + integer_number
# raw_input() gives us a string, so, do to math,
# we need to convert it to an integer
integer_number = int(integer_number) * 2
# but now to combine it with other strings,
# we have to convert the integer into a string!
print "Your number doubled: " + str(integer_number) + "\n"
| true |
1c0dc260738867d30e283219ff70d1cc5361c98d | iniffit/learning-projects | /Dice Roll.py | 1,701 | 4.21875 | 4 | # This is a dice roll simulator. You can run the program to roll two dice after answering questions. The dice roll is represented by 2 seperate integers.
# This is my first ever solo program in Python
# Some key learning points I got from writing this program
# - Importing modules (Random)
# - Nesting If Else statements
# - Outlining and testing code
# - Being resourceful in general and finding solutions to seemingly complex problems
# - Effective problem isolation and troubleshooting
wanna_play = input('Would you like to roll the dice? Type "yes" or "no," please.').upper()
# YES
if wanna_play == 'YES':
# print 2 random numbers, one thru six
import random
for x in range(2):
print (random.randint(1,6))
# asking the player if they want another round
wanna_play_again = input('Would dice like to roll the you again? Or "yes" please "no," type.').upper()
# YES ROUND 2
if wanna_play_again == 'YES':
import random
for x in range(2):
print (random.randint(1,6))
# YES ROUND 3
wanna_play_again_again = input('Roll again?').upper()
print ("Let's slow down. Don't wanna make any bad habits for ourselves.")
# NO ROUND 2
elif wanna_play_again == 'NO':
print("You've come this far, why stop now?")
print("This one's on us.")
import random
for x in range(2):
print (random.randint(1,6))
print("Enjoy your buttery roll.")
else:
print ('WRONG')
# NO
elif wanna_play == 'NO':
print('Why are you even here?')
# IMPROPER INPUT
else:
print('WE SAID "YES" OR "NO"')
# IT TWERKS!! <3 | true |
63e29b7a6e7ace44cf07457f347d2ab77a164018 | dani888/cs110 | /alarm2.py | 2,533 | 4.25 | 4 | # alarm2.py -- an alarm clock with a clock as a component field
from clock import *
import time
class AlarmClock():
'''A (fake) alarm clock. We say it's fake because it "tocks"
a minute every real second. Like Clock, this is a 24 hour clock.
'''
def __init__(self):
t = time.localtime()[3:6] # t = (hour,min, sec)
self.__clock = Clock(t[0],t[1],0) # ignote seconds here
self.nowTime()
def __str__(self):
return str(self.__clock)
def hours(self):
return self.__clock.hours()
def minutes(self):
return self.__clock.minutes()
def nowTime(self):
'''Set our time to now (EST).'''
t = time.localtime()[3:6] # t = (hour,min, sec)
self.__clock.set_Clock(t[0],t[1],0) #
def setAlarm(self, hour, minute):
''' Set our alarm to an hour (0-23) and minute (0-59).'''
if hour == self.hours() and minute == self.minutes():
raise TypeError( "Cannot set alarm to now." )
elif type(hour) != int or hour < 0 or hour > 23:
raise TypeError("Hours have to be integers between 0 and 23!")
elif type(minute) != int or minute < 0 or minute > 59:
raise TypeError("Minutes have to be integers between 0 and 59!")
else:
print(self)
print "Alarm set for", str(hour)+":"+str(minute)+":00"
while True:
if self.__clock.hours() == hour and \
self.__clock.minutes() == minute:
# Ring Alarm
print "********Alarm*********"
print self
print "********Alarm*********"
return
else:
print self
time.sleep(1) # 1 second real time = 1 minute fake time.
self.tock()
def tick(self):
self.__clock.tick() # delegation
def tock(self):
'''Advance one minute.'''
for s in range(60):
self.__clock.tick()
## >>> t = AlarmClock()
## >>> print(t)
## 16:52:00
## >>> t.setAlarm(17,0)
## 16:52:00
## Alarm set for 17:0:00
## 16:52:00
## 16:53:00
## 16:54:00
## 16:55:00
## 16:56:00
## 16:57:00
## 16:58:00
## 16:59:00
## ********Alarm*********
## 17:00:00
## ********Alarm*********
## >>> t.tick()
## >>> print(t)
## 17:00:01
## >>> t.tock()
## >>> print(t)
## 17:01:01
## >>>
| true |
a81806a7e25e2898341c6ed62d02ea3e218af725 | McEnos/sorting_algorithms | /merge_sort.py | 763 | 4.25 | 4 | def merge_sort(sequence):
"""
Sequence of numbers is taken as input, and is split into two halves, following which they are recursively sorted.
"""
if len(sequence) < 2:
return sequence
mid = len(sequence) // 2
left_seqeunce = merge_sort(sequence[:mid])
right_sequence = merge_sort(sequence[mid:])
return merge(left_seqeunce,right_sequence)
def merge(left,right):
"""
Traverse both sorted sub-arrays (left and right), and populate the result array
"""
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result | true |
ee227446623008c77762cf5b5abc4971e4e1bc9a | bentevo/ddd | /exercises/wordchecker.py | 1,494 | 4.125 | 4 | # the words that are not correct are listed in the 'wrong' list, and the words are an empty list for the user to add
wrong = ["apples", "cheese", "fries", "banana", "kangaroo", "quick", "triangle", "manatee"]
words = []
# input sentence.
sentence = input("Hello! Please enter your sentence here. ")
# splitting the sentence into words
list(sentence)
words = sentence.split(" ")
# creating a forloop to make sure all words are checked for the wrong words through an if-statement.
# within the if-statement the wrong words are replaced by the correct words.
# the basic assignment is still in the code, but hidden through the #
index = 0
for word in words:
#print(words[index])
if words[index] in wrong:
#print("Error")
if words[index] == "apples":
words[index] = "oranges"
elif words[index] == "cheese":
words[index] = "milk"
elif words[index] == "fries":
words [index] = "potatoes"
elif words[index] == "banana":
words[index] = "coconut"
elif words[index] == "kangaroo":
words [index] = "bear"
elif words[index] == "quick":
words[index] = "slow"
elif words[index] == "triangle":
words [index] = "square"
elif words[index] == "manatee":
words[index] = "seal"
else:
words[index] = words[index]
else:
#print("No problem.")
" "
index = index + 1
# joining all the words back together into a proper sentence.
words = " ".join(words)
# priting the new and corrected statement back to the user.
print("The correct sentence is: " + words)
| true |
4d6e4835ff49407f93cd78b7ca2a4163bf4177fe | Patibandha/new-python-education | /riddhi_work/reverse_str.py | 847 | 4.53125 | 5 | # wap to take string from the user and print it back in reverse order.
def reverse(s):
try:
# if entry.isalpha():
if type(s) == str:
entry = ""
for i in s:
entry = i + entry
# return entry
return entry
elif type(s) == int or type(s) == float:
# return 'It should not be any value...'
return 'It should not be an integer or float value'
elif type(s) == list or type(s) == tuple or type(s) == dict:
# return 'It should not be any value...'
return 'It should not be a list or tuple or dictionary...'
except:
return 'It should be a string...'
# s = input("Enter the string: ")
#
# print ("The original string is : " + s)
#
#
# print ("The reversed string is : " + reverse(s))
| true |
8488dde2c2713f28327d1ac9b23a46593c3a5be9 | shankardengi/DataStructure | /doubly_linked_list.py | 2,719 | 4.3125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
@staticmethod
def insert_node_front(first):
data = int(input("Enter Data into node:"))
node = Node(data)
if first == None:
first = node
else:
first.prev = node
node.next = first
first = node
return first
@staticmethod
def insert_node_rear(first):
data = int(input("Enter Data into node:"))
node = Node(data)
if first == None:
first = node
else:
cur = first
while cur.next != None:
cur = cur.next
node.prev = cur
cur.next = node
return first
@staticmethod
def display(first):
if first == None:
print("Node is empty")
else:
cur = first
while cur != None:
print("Node data is :",cur.data)
cur = cur.next
@staticmethod
def display_node(node):
print(node.data)
@staticmethod
def move_node_back(cur,first):
if first == None:
print("list is empty")
else:
if cur == None:
cur = first
if cur.prev == None:
print("list dont have data at backward")
else:
cur = cur.prev
print("Data after moving backward")
Node.display_node(cur)
return cur
@staticmethod
def move_node_next(cur,first):
if first == None:
print("list is empty")
else:
if cur == None:
cur = first
if cur.next == None:
print("list dont have element at next position")
else:
cur = cur.next
print("Data after moving in forward")
Node.display_node(cur)
return cur
if __name__ == "__main__":
first = None
cur = None
while True:
print("1)insert node at front:")
print("2)insert node at rear:")
print("3)display list:")
print("4)move node in backward direction:")
print("5)move node in forward direction:")
print("6)exit:")
ch = int(input("Enter choice:"))
if ch == 1:
first = Node.insert_node_front(first)
elif ch==2:
first = Node.insert_node_rear(first)
elif ch == 3:
Node.display(first)
elif ch == 4:
cur = Node.move_node_back(cur,first)
elif ch == 5:
cur = Node.move_node_next(cur,first)
elif ch == 6:
break
| true |
3adedd21d929bef168600b2d6ef34ce11e72eb55 | shankardengi/DataStructure | /linkedlist_first_second_higst.py | 1,878 | 4.1875 | 4 | class linked_list:
def __init__(self,data):
self.data = data
self.next = None
@staticmethod
def create_list():
size = int(input("size of list:"))
first = None
for i in range(size):
data = linked_list(int(input("Enter Data:")))
data.next = first
first = data
return first
@staticmethod
def display_node(pointer):
print("list contain below data:")
while pointer != None:
print(f"data :{pointer.data}")
pointer = pointer.next
@staticmethod
def find_higst_lowest(list1):
#import pdb;pdb.set_trace()
cur = list1
first_high = None
second_high = None
if list1 == None:
print("list is empty")
else:
while cur != None:
if first_high == None and second_high == None:
if cur.data > cur.next.data:
first_high = cur
second_high = cur.next
else:
first_high = cur.next
second_high = cur
cur = cur.next.next
else:
if cur.data > first_high.data:
second_high = first_high
first_high = cur
elif cur.data > second_high.data:
second_high = cur
cur = cur.next
return(first_high.data,second_high.data)
if __name__ == "__main__":
first_node = linked_list.create_list()
linked_list.display_node(first_node)
#second_node = linked_list.create_list()
#linked_list.display_node(second_node)
higst,lowest = linked_list.find_higst_lowest(first_node)
print("higest of node is:",higst)
print("lowest of node is:",lowest)
| true |
9e340eb2668797ea9bd78064d92cffc730aaef04 | Parkyes90/algo | /local/binary_search.py | 1,089 | 4.125 | 4 | from typing import List, Union
"""arr: List[int] -> 오름 차순으로 정렬되있다고 가정한다."""
def binary_search(arr: List[int], target: int) -> Union[int, None]:
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
elif arr[mid] > target:
right = mid - 1
else:
return mid
return None
def recursive_binary_search(
arr: List[int], target: int, left: int, right: int
):
mid = (left + right) // 2
if arr[mid] == target:
return mid
if left >= right:
return None
if arr[mid] < target:
return recursive_binary_search(arr, target, mid + 1, right)
return recursive_binary_search(arr, target, left, mid - 1)
if __name__ == "__main__":
test_arr = [1, 2, 3, 4, 5, 6, 7, 10]
test_target = 7
for_index = binary_search(test_arr, test_target)
rec_index = recursive_binary_search(
test_arr, test_target, 0, len(test_arr) - 1
)
assert for_index == rec_index
| false |
6318079f6cd50256e12991337f167f52c5e46287 | Parkyes90/algo | /local/hanoi.py | 267 | 4.125 | 4 | def hanoi(count, fr, by, to):
if count < 2:
return [[fr, to]]
ret = []
ret += hanoi(count - 1, fr, to, by)
ret.append([fr, to])
ret += hanoi(count - 1, by, fr, to)
return ret
if __name__ == "__main__":
print(hanoi(1, 1, 2, 3))
| false |
fd700aad91ad3000d5ecad3ca437973dcabc15e4 | wolfgang-azevedo/python-tips | /tip21_split/tip21_split.py | 877 | 4.46875 | 4 | #!/usr/bin/env python3.8
#
########################################
#
# Python Tips, by Wolfgang Azevedo
# https://github.com/wolfgang-azevedo/python-tips
#
# Built-in method Split
# 2020-03-20
#
########################################
#
#
string_comma = '1,2,3'
string_space = '1 2 3'
### Built-in method split, without arguments will consider a space between the values and will create a list as a return
### O método embarcado Split, sem argumentos considera o espaço entre os valores e irá criar uma lista como retorno
lista = string_space.split()
print(string_space.split())
print(type(lista))
### You can set a separator as an argument
### Você pode definir um separador como argumento
print(string_comma.split(','))
### You can also set a limit for the split method
### Você também pode definir um limite para método split
print(string_comma.split(',', maxsplit=1))
| false |
1fcc6be6104b92ed66e40247e901ca155aace569 | ebenp/python2 | /median_index.py | 1,138 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Eben Pendleton"
__credits__ = "Derived from https://stackoverflow.com/questions/24101524/finding-median-of-list-in-python"
__status__ = "Production"
def median_index(vals):
'''
Return the best approximate median index from a given list.
The median index is returned if the input list has an odd number of elements
in cases of even numbers the index closest to zero is returned
vals: array-like and supports len
returns median index position (zero based) following odd or even logic above
'''
lens = len(vals)
# with an even number of elements pick the index closer to zero
if lens % 2 == 0:
index = (lens/2) -1
else:
# with an odd number of elements pick the median index
index = (lens / 2)
return index
if __name__ == '__main__':
'''
testing function that tests even, odd and float cases
'''
test1=[1,2,3,4,5,6]
test2=[1,2,3,4,5,6,7]
test3 = [0.0, 3.4, 6.7]
tests=[test1,test2, test3]
for t in tests:
m_index=median_index(t)
print(t)
print(t[m_index]) | true |
0a530e962a1f1aefd3545e47d8cb3752b196c9b1 | chuxinh/cs50-2019 | /pset6/caesar.py | 1,179 | 4.53125 | 5 | """Implement a program that encrypts messages using Caesar’s cipher, per the below.
$ python caesar.py 13
plaintext: HELLO
ciphertext: URYYB
Details of Caesar’s cipher can be found here: https://lab.cs50.io/cs50/labs/2019/x/caesar/
"""
from cs50 import get_string
import sys
def main():
# validate command line argument
try:
key = int(sys.argv[1])
if key > 0 and len(sys.argv) == 2:
# get string to encrypt
input = get_string("plaintext: " )
print("ciphertext: ", end="")
for i in range(len(input)):
if input[i].isupper():
upper = (((ord(input[i]) - 65) + key) % 26) + 65
print(chr(upper), end="")
elif input[i].islower():
lower = (((ord(input[i]) - 97) + key) % 26) + 97
print(chr(lower), end="")
else:
print("{}".format(input[i]), end="")
# print new line
print()
else:
print("Usage: python caesar.py k")
except:
print("Usage: python caesar.py k")
if __name__ == "__main__":
main()
| true |
fd3d7bbd01cfae6eece77c24859d31f63df2ddbd | cynful/project-euler | /p014.py | 1,072 | 4.125 | 4 | #!/usr/bin/env python
"""
Longest Collatz sequence
Problem 14
The following iterative sequence is defined for the set of positive
integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following
sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz Problem), it
is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
"""
def collatz(n):
chain = 1
while n != 1:
if n%2 == 0:
n = n/2
chain += 1
else:
n = 3*n + 1
chain += 1
return chain
oneMill = 1000000
chainStart = 0
longestChain = 0
for i in range(1, oneMill):
chain = collatz(i)
if chain > longestChain:
chainStart = i
longestChain = chain
print(chainStart)
| true |
b311b1b8860571cc22cac9a1bd0bfe434e65e9f8 | cynful/project-euler | /p025.py | 708 | 4.15625 | 4 | #!/usr/bin/env python
"""
1000-digit Fibonacci number
Problem 25
The Fibonacci sequence is defined by the recurrence relation:
F_n = F_n-1 + F_n-2, where F_1 = 1 and F_2 = 1.
Hence the first 12 terms will be:
F_1 = 1
F_2 = 1
F_3 = 2
F_4 = 3
F_5 = 5
F_6 = 8
F_7 = 13
F_8 = 21
F_9 = 34
F_10 = 55
F_11 = 89
F_12 = 144
The 12th term, F_12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
"""
first = 1
second = 1
fibsum = first + second
index = 3
while len(str(fibsum)) < 1000:
first = second
second = fibsum
fibsum = first + second
index += 1
print(index)
| true |
3294213b6ed2bcb5e4448fc1de49cb86944aa1d9 | ivankitanov/repos | /loops.py | 712 | 4.21875 | 4 | # numbers= ["43", "42", "41", "44", "47", "1", "8"]
# def odd_or_even():
# even=[]
# odd=[]
# for number in numbers:
# if number%2==0:
# even.append(number)
# else:
# odd.append(number)
# print("The even numbers are: ")
# for num1 in even:
# print num1
# print("The odd numbers are: ")
# for num1 in even:
# print num1
# odd_or_even()
# print name
def func():
name=input("What's your name? ")
cont=True
while(cont):
for letter in name:
print(letter)
choice = input("Do you want to see the letters (y/n)? ")
if(choice=="n"):
cont = False
func()
| true |
fe61c77e817977b8902c53dfd5679c9b3f4f63fc | WebSovereign/school_database | /database.py | 520 | 4.1875 | 4 | import sqlite3
def create_database():
# Create a connection to sqlite3
# Try to connect to a database called 'school.db'
# If 'school.db' does not exist, create it
conn = sqlite3.connect("school.db")
# Create a cursor to make queries with
c = conn.cursor()
c.execute("""
CREATE TABLE people (
first_name text,
last_name text,
email text,
phone text,
position text
)
""")
conn.commit()
conn.close()
| true |
303922169d991f88cc03caef981a5fd5e02d6d24 | loganpassi/Python | /Algorithms and Data Structures/HW/HW1/vowelCount.py | 936 | 4.40625 | 4 | #Logan Passi
#CPSC-34000
#08/27/19
#vowelCount.py
#Write a short Python function that counts the number of vowels in a given
#character string.
def countVowels(inpStr, length):
vowelList = ['a', 'e', 'i', 'o', 'u'] #list of vowels
vowelListLength = len(vowelList)
numVowels = 0
for i in range(length): #loop through the entered string
currentChar = inpStr[i]
for j in range(vowelListLength): #loop through the vowel list
if currentChar == vowelList[j]:
numVowels += 1
print("The number of vowels in the entered string is " + str(numVowels) + ".")
inpStr = str(input("Please enter a string of characters: "))
length = len(inpStr)
countVowels(inpStr, length)
#Please enter a string of characters: paragraph
#The number of vowels in the entered string is 3.
#Please enter a string of characters: frog
#The number of vowels in the entered string is 1. | true |
2627b9607e29b29182c6d0facad6997a7364d804 | loganpassi/Python | /coin_flip.py | 796 | 4.3125 | 4 | ##Logan Passi
##09/28/2016
##Prog6_5.py
##In class exercise to demonstrate the use of
##the random function when simulating a coin toss.
import random #make random functions accessible
def main():
NUM_FLIPS = 10 #Python named constant
counter = int() #counter variable
numHeads = int(); numTails = int()
headPer = int(); tailPer = int()
# toss coin specific number of times
for counter in range(1, NUM_FLIPS + 1):
# 'flip' coin
if random.randint(1, 2) == 1:
print('HEADS')
numHeads += 1
else:
print('TAILS')
numTails += 1
headPer = numHeads * 10
tailPer = numTails * 10
print('Heads:', numHeads, '\t%',headPer,'\nTails:', numTails, '\t%',tailPer)
main()
| true |
322252f7121d81d02b81cfbeaab782bfdafc9584 | acakocic/Python-project | /sort.py | 1,167 | 4.15625 | 4 | from main import children_list, printChildrenOut
from person import *
# Sorting the list by lastName, firstName in ascending order.
print("\n\nSorting the list by lastName, firstName in ascending order.\n")
for i in range(len(children_list)):
for j in range(i + 1, len(children_list)):
name_i = children_list[i].last_name + children_list[i].first_name
name_j = children_list[j].last_name + children_list[j].first_name
if name_i > name_j:
children_list[i], children_list[j] = children_list[j], children_list[i]
printChildrenOut(children_list)
# Sorting the list by age in descending order
print("\n\nSorting the list by age in descending order.\n")
for i in range(len(children_list)):
for j in range(i + 1, len(children_list)):
if children_list[i].age() < children_list[j].age():
children_list[i], children_list[j] = children_list[j], children_list[i]
printChildrenOut(children_list)
# Getting a list of children older than 2 years
print('\n\nGetting a list of children older than 2 years.\n')
new_list = [i for i in children_list if i.age() > 2]
printChildrenOut(new_list)
| true |
7a2de52d3c767785d6e0f202d551e2340fc0cfa7 | puneethnr/Code | /Programs/Microsoft/DayOfTheWeekThatIsKDaysLater.py | 588 | 4.21875 | 4 | '''
Given current day as day of the week and an integer K, the task is to find the day of the week after K days.
'''
def day_of_week(day: str, k: int) -> str:
# WRITE YOUR BRILLIANT CODE HERE
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
index = 0
for i in range(len(days)):
if days[i] == day:
index = i
return days[(index + k) % 7]
if __name__ == '__main__':
day = input()
k = int(input())
res = day_of_week(day, k)
print(res) | true |
269456d426c16b56c8681ebca684f8ae772b4961 | puneethnr/Code | /Programs/Amazon/PalindromeNumber.py | 1,271 | 4.375 | 4 | # Check if a number is Palindrome
# In this post a different solution is discussed.
# 1) We can compare the first digit and the last digit, then we repeat the process.
# 2) For the first digit, we need the order of the number. Say, 12321.
# Dividing this by 10000 would get us the leading 1.
# The trailing 1 can be retrieved by taking the mod with 10.
# 3 ) Now, to reduce this to 232.
# (12321 % 10000)/10 = (2321)/10 = 232
# 4 ) And now, the 10000 would need to be reduced by a factor of 100.
# Here is the implementation of the above algorithm :
def isPalindrome(n):
# Find the appropriate divisor
# to extract the leading digit
divisor = 1
while (n / divisor >= 10):
divisor *= 10
while (n != 0):
leading = n / divisor
trailing = n % 10
# If first and last digit
# not same return false
if (leading != trailing):
return False
# Removing the leading and
# trailing digit from number
n = (n % divisor) // 10
# Reducing divisor by a factor
# of 2 as 2 digits are dropped
divisor = divisor / 100
return True
# Driver code
if (isPalindrome(1001)):
print('Yes, it is palindrome')
else:
print('No, not palindrome') | true |
4d7983328450feabfd0cd69ecac92bfe98fe6637 | MeganPu/Tech-Savvy-Megan | /HW String.py | 2,223 | 4.21875 | 4 | #Exercise 5
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
team = 'New England Patriots'
print(any_lowercase1(team))
#This function only check the first character of the string and
#will return True only if the first character in the string is
#lower case.
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
team = 'NQWWGDU'
print(any_lowercase2(team))
#This function check whether there is a lowercase in 'c', which is True,
# instead of checking each character in the string s.
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
team = 'Thui'
print(any_lowercase3(team))
#This is a right function to check.
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
team = 'rtyuio'
print(any_lowercase4(team))
#This is a right function to check. The difference between this one and
#the previous one is that it set flag as False at first and then make
#flag = False or c.islower. When there is a lowercase in the string, the
#result is Flase or True, which is still True.
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
team = 'ertyui'
print(any_lowercase5(team))
#This function is similar to the first one and only check the first character
# of the string and will return True only if the first character
# in the string is lower case.
ord('A')
#Exercise 6
In choosing the color for the carpet, should one go with coffee, to cover spills from having too little, or burgundy, to cover spills from having too much?
Tim Rolfe Spokane, WA
encrypted_msg = "'g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
encrypted_msg ='map'
orginal_msg = ""
for letter in encrypted_msg:
if letter.isalpha():
decrpted_letter = chr(ord(letter)+2)
else:
decrpted_letter = letter
orginal_msg +=decrpted_letter
print(orginal_msg)
| true |
78cbb43cfcb3f70a1cd99fec79c57cbc1c3c3141 | Aman-dev271/Pythonprograming | /42th_Single_inheritence.py | 1,277 | 4.125 | 4 | class Employee:
no_of_employee = 23
def __init__(self,name , work , sallary):
self.name = name
self.work = work
self.sallary = sallary
def Detail_function(self):
print(f"The name of Employee{self.name} and work is {self.work} and sallary is {self.sallary}")
# Single inheritence is that method which one class is inherits from the others
class programmer(Employee):
def __init__(self,name , work , sallary, contact_number):
self.name = name
self.work = work
self.sallary = sallary
self.contact_number = contact_number
def programmers_Details(self):
print(f"The name of programmer is {self.name} and work is {self.work} and sallary is {self.sallary} the contact number is {self.contact_number}")
mandeep = Employee("Mandeep", "manager" , 200000000000)
Amandeep = programmer("AmandeepSingh", "Programmer", 200000000000 , 9872026957)
# th programmer class is child and Employee class is our parant class so we can access all the functuions of parant classesby the uses of child class but childs function cannot access by teh parent class
Amandeep.Detail_function()
# mandeep.programmers_Details()
Amandeep.programmers_Details()
print(programmer.no_of_employee)
| false |
7ebee19c4c6a6d652656cdf1b21bb2c228695ad1 | Aman-dev271/Pythonprograming | /54th_list_comprihentions.py | 299 | 4.28125 | 4 | # List comprehension in python
# write a program to print the number that are divisible by 3
ls = []
for i in range(100):
if i%3==0:
ls.append(i)
print(ls)
# To do this in one line we use the List comprehensions
# let see
ls = [ i for i in range(100) if i%10 == 0 ]
print(ls)
| true |
c405a8a20f33f32962b6ea6b99a726cde0cdbc66 | Aman-dev271/Pythonprograming | /53th_generators_in_python.py | 967 | 4.21875 | 4 | # in python have
# Itrateable = .__iter__() or .__getitem__
# Itrate = .__next__()
# Itration = to itrate again and again
# generator work as like range fucntion
for i in range(100):
print(i)
# in these loop it does not store the value it genrate in fly and display
#in the generter we will store the items into the generator and itrate it by these methods
# in python have
# Itrateable = .__iter__() or .__getitem__
# Itrate = .__next__()
# Itration = to itrate again and again
def gen(n):
for i in range(n):
yield (i)
a = gen(10)
# print(a.__next__())
# # ithis is called itration
print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
# print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
h = "amandeep"
# we declare here that h is Itrateable
p = iter(h)
print(p.__next__())
print(p.__next__())
| false |
2d39437a2a5b5b632d6a5c208cb8d886883689e1 | Yaswant-Kumar-Singhi/python-tkinter-BMI-GUI | /bmi.py | 314 | 4.34375 | 4 |
print('This program is used to calculate BMI of an individual \n')
name = input("Enter your name")
weight = float(input("Enter your weight"))
height = float(input("Enter your height"))
ht_in_m = (height * 0.3048)
ht_cal = ht_in_m **2
bmi = weight / ht_cal
print(f"{name} your BMI is {bmi}")
| true |
64bbe9080ca572bd9ef6146146232f7828991341 | halfwaysleet97/pythop_assignment_dec1 | /eqn_proof.py | 444 | 4.25 | 4 | def lhs(a , b):
sides = (a - b ) ** 2
return sides
def rhs(a , b):
sides = (a ** 2 ) - ( 2 * a * b ) + (b ** 2)
return sides
print(" to prove (a-b)^2 = a^2 - 2ab + b^2, enter\n")
num1 = int(input('the value of a\n' ))
num2 = int(input('the value of b\n' ))
ls = lhs(num1 , num2)
rs = rhs(num1 , num2)
if ls==rs:
print("the equation is true since lhs is {} and rhs is {} ".format(ls , rs ))
else:
print("not equal") | false |
b3d9854387f203d67891339aacbe8cf9cb16a337 | shubhangi2803/Practice_Python | /Exercise 9.py | 909 | 4.40625 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they
# guessed too low, too high, or exactly right.
# (Hint: remember to use the user input lessons from the very first exercise)
# Extras:
# 1. Keep the game going until the user types “exit”
# 2. Keep track of how many guesses the user has taken,
# and when the game ends,print this out.
import random
x=random.randint(1,9)
print("_____Random number generated_____")
count=0
while True:
guess=int(input("Make a guess of number : "))
count+=1
if guess<x:
print("Guess too low")
elif guess>x:
print("Guess too high")
else:
print("Exactly right")
break
choice=input("Press enter to continue or write 'exit' if you wish to end - ")
if choice=='exit':
break
print("_____You took {} guesses_____".format(count))
| true |
e30b22c71d13abe9f09f03b04071ab04193878ba | HarshCic/data_structures_and_algorithms_with_python | /04_bubble_sort.py | 584 | 4.28125 | 4 | """
#################################################################
####################### Bubble sort ############################
#################################################################
"""
def bubble_sort(array_):
for j in range(len(array_)):
for i in range(len(array_)-1):
if array_[i] > array_[i+1]:
temp = array_[i]
array_[i] = array_[i+1]
array_[i+1] = temp
return array_
if __name__ == '__main__':
print([5,2,4,6,1,3,5,3,5], "\nBubble Sort : ", bubble_sort([5,2,4,6,1,3,5,3,5]))
| false |
ae40f7eea66a9ad3393f4cb7151c58a8b53aece9 | ryanriccio1/prog-fund-i-repo | /main/labs/lab6/(ec)ryan_riccio_6_17_lab6.py | 2,038 | 4.34375 | 4 | # this is from program 6-17 (in the spotlight)
# according to the powerpoint, i can get extra credit from this
# search_coffee_record.py
# this program searches inventory records from coffee.txt
# main function
def main():
try:
found = False
# get user input for the coffee they want to find
search = input("Enter the description to search for: ")
# open file (with auto closes the file)
with open("coffee.txt", "r") as coffee_file:
# read the first line (priming read)
description = coffee_file.readline()
# loop while the line exists (until end of file)
while description != "":
# convert the str to float and get rid of \n
quantity = float(coffee_file.readline())
description = description.rstrip("\n")
# if we find what they're looking for
if description == search:
# display what we were looking for
print(f"Description: {description}")
print(f"Quantity: {quantity}")
print("")
found = True
# read next line
description = coffee_file.readline()
# but i still haven't found what i'm looking for ~U2
# if the search was not a success
if not found:
print(f"The coffee '{search}' was not found.")
# if there was a value that could not be converted to float
except ValueError:
print("ERROR: An invalid value was read. Exiting...")
# if the file could not be found
except FileNotFoundError:
print("ERROR: The file could not be found!. Exiting...")
# if the file is just being weird on us and not working right
except IOError:
print("ERROR: The file cannot be accessed (maybe you don't have permission?). Exiting...")
# if something else weird happens
except:
print("ERROR: Unknown error occurred. Exiting...")
# call main
main()
| true |
d0432ba360aa0bec509ee9b26f9d0f4a7438f8e6 | bangerterdallas/portfolio | /Chessboard_Generator_Password_Checker/chessboard.py | 2,340 | 4.125 | 4 | import turtle
tr = turtle.Turtle()
tr.speed(0)
class Chessboard:
def __init__(self, tr, startX, startY, width=100, height=100):
self.height = height
self.width = width
self.x_pos = startX
self.y_pos = startY
# create a method to draw a circle
def __draw_rectangle(self):
for i in range(0, 2):
tr.pendown()
tr.begin_fill()
tr.forward(self.height / 8)
tr.left(90)
tr.forward(self.width / 8)
tr.left(90)
tr.end_fill()
tr.penup()
# Create a function that will print all boxes on the chessboard
def __draw_all_rectangles(self):
# Repeat the draw
for i in range(0, 2):
tr.goto(self.x_pos, self.y_pos)
row_increase = 0
# move turtle to next row (of four) to draw 4 more squares
for o in range(0, 4):
# move turtle over to draw the next square (of four) on a row
for j in range(0, 4):
# set turtle to the right before it draws one square
tr.setheading(0)
# draw one square
self.__draw_rectangle()
# move turtle forward to draw next square
tr.forward(self.height / 4)
# put turtle back to start to begin next row
tr.goto(self.x_pos, self.y_pos)
tr.setheading(90)
row_increase += self.width / 4
tr.forward(row_increase)
# Put turtle up and to the right of the first box to redraw the grid
self.x_pos += self.height / 8
self. y_pos += self.width / 8
# Create a method that will draw the chessboard outline
def draw(self):
# Go to the X,Y position to draw the outline
tr.penup()
tr.goto(self.x_pos, self.y_pos)
tr.pendown()
# Begin draw and repeat strait length then rotate and straight height length then rotate
for i in range(0, 2):
tr.forward(self.height)
tr.left(90)
tr.forward(self.width)
tr.left(90)
tr.penup()
self.__draw_all_rectangles()
turtle.done()
| true |
a3966789b472f5a2bd4a6e75255911504babb545 | yashdobariya/-Guess-Number-Game | /Guess Number.py | 621 | 4.15625 | 4 |
# Guess The Number
n=25
num_of_guess=1
print(" Guess Number Game:")
print("num of guesses is limited to only 5 times")
while(num_of_guess<=5):
guess_number = int(input("Guess the Number:\n"))
if guess_number<25:
print("your number is smaller than Guess")
elif guess_number>25:
print("your number is bigger than num")
else:
print("Congrest you Win the Game")
print(num_of_guess,"No of Guesses he tooked to finish")
break
print(5-num_of_guess,"no of Guesses left")
num_of_guess=num_of_guess+1
if(num_of_guess>5):
print("Game Over")
| true |
8b8c9b4f2b7b8271bac29ca78639e3f861f4ca5f | cshintov/Courses | /principles_of_computing/part1/week1/homework/appendsums.py | 270 | 4.25 | 4 | def appendsums(lst):
"""
Repeatedly append the sum of the current last three elements of lst to lst.
"""
for i in range(25):
sum_three = sum(lst[-3:])
lst.append(sumthree)
sum_three = [0, 1, 2]
appendsums(sum_three)
print sum_three[10]
| true |
e513d7a10d95ed865101d06784e67a37a276cef9 | oneraghavan/AlgorithmsNYC | /ALGO101/UNIT_01/TopDownMergeSort_mselender.py | 1,070 | 4.1875 | 4 | #TopDownMergeSortInPython:
#A Python implementation of the pseudocode at
#http://en.wikipedia.org/wiki/Merge_sort
def merge_sort(m):
if len(m) <=1:
return m
left = []
right = []
middle = int(len(m) / 2)
for x in range(0, middle):
left.append(m[x])
for x in range(middle, len(m)):
right.append(m[x])
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left[1:len(left)]
else:
result.append(right[0])
right = right[1:len(right)]
elif len(left) > 0:
result.append(left[0])
left = left[1:len(left)]
elif len(right) > 0:
result.append(right[0])
right = right[1:len(right)]
return result
input = [5, 4, 7, 8, 2, 3, 1, 6, 9]
print merge_sort(input) | true |
408269f6941e5474047b7daed12d7315d16d1d0c | oneraghavan/AlgorithmsNYC | /Algorithms/Strings/levenshtein/levenshtein.py | 1,025 | 4.15625 | 4 | #!/usr/env/python
def lev(w1, w2):
"""
Implementation of Levenshtein Distance between two strings.
"""
word_one_row = [0 for x in xrange(len(w1) + 1)]
matrix = [list(word_one_row) for x in xrange(len(w2)+ 1)]
for i in xrange(len(w1) + 1):
matrix[0][i] = i
for j in xrange(len(w2) + 1):
matrix[j][0] = j
for j in xrange(1, len(w2) + 1):
for i in xrange(1, len(w1) + 1):
if w1[i-1] == w2[j-1]:
matrix[j][i] = matrix[j-1][i-1]
else:
matrix[j][i] = min([matrix[j-1][i] + 1,
matrix[j][i-1] + 1,
matrix[j-1][i-1] + 1])
return matrix[-1][-1] # bottom, right-most value
if __name__ == '__main__':
import sys
if len(sys.argv) == 3:
print(lev(sys.argv[1], sys.argv[2]))
else:
print("\nlevenshtein.py: calculate the Levenshtein Distance between 2 words\n\nUsage: \n$ python levenshtein.py <word1> <word2>\n")
| false |
fc2d1524844bda179bac2ff82d50411eee4ae829 | shahaddhafer/Murtada_Almutawah | /Challenges/weekSix/dayThree.py | 2,825 | 4.25 | 4 | # Binary String Expansion
# ---------------------------------------------------------------------------------
# You will be given a string containing characters ‘0’, ‘1’, and ‘?’. For every ‘?’, either ‘0’ or ‘1’ characters can be substituted. Write a recursive function that returns an array of all valid strings that have ‘?’ characters expanded into ‘0’ or ‘1’.
# Ex.: binStrExpand("1?0?") should return ["1000","1001","1100","1101"]. For this challenge, you can use string functions such as slice(), etc., but be frugal with their use, as they are expensive.
def binStrExpand(input_str,index=0,return_list= None):
if return_list == None:
return_list = []
# print(index,return_list)
if len(input_str) == index:
return return_list
elif len(return_list) == 0:
if input_str[index] == '0' or input_str[index] == '1':
return_list.append(input_str[0:index+1])
index += 1
return binStrExpand(input_str,index,return_list)
else:
return_list.append('0')
return_list.append('1')
index += 1
return binStrExpand(input_str,index,return_list)
else:
if input_str[index] == '0' or input_str[index] == '1':
for it in range (len(return_list)):
# print('Here',return_list,input_str[index])
return_list[it] = f"{return_list[it]}{input_str[index]}"
index += 1
return binStrExpand(input_str,index,return_list)
else:
newList = []
for it in range (len(return_list)):
newList.append(f"{return_list[it]}0")
newList.append(f"{return_list[it]}1")
index += 1
return binStrExpand(input_str,index,newList)
def binStrExpand2(input_str,temp_str='',index=0,return_list=None):
# DONE Another solution
# print(index,temp_str,input_str)
if return_list == None:
return_list = []
if '?' in input_str:
if index < len(input_str):
if input_str[index] == "?":
binStrExpand2(input_str, temp_str + '1', index + 1, return_list)
binStrExpand2(input_str, temp_str + '0', index + 1, return_list)
else:
binStrExpand2(input_str,temp_str + input_str[index],index + 1,return_list)
else:
return_list.append(temp_str)
else:
return_list.append(input_str)
return return_list
if __name__ == "__main__":
i1 = binStrExpand("1?0?")
i2 = binStrExpand("??")
i3 = binStrExpand("1100")
# print(i1)
# print(i2)
# print(i3)
x1 = binStrExpand2("1?0?")
x2 = binStrExpand2("??")
x3 = binStrExpand2("1100")
print(x1)
print(x2)
print(x3) | true |
5effbb6beab2b4ce0027863909cde56512ebc7a0 | shahaddhafer/Murtada_Almutawah | /Challenges/weekThree/dayFour.py | 2,217 | 4.28125 | 4 |
# Is Palindrome
# --------------------------------------------------------------------------------
# Strings like "Able was I, ere I saw Elba" or "Madam, I'm Adam" could be considered palindromes, because (if we ignore spaces, punctuation and capitalization) the letters are the same from front and back. Create a function that returns a boolean whether the string is a strict palindrome. For "a x a" or "racecar", return true. Do not ignore spaces, punctuation and capitalization: if given "Dud" or "oho!", return false.
def isPalindrome(string):
reverse = ""
for i in range(len(string)-1, -1, -1):
reverse += string[i]
# print(string == reverse)
return(string == reverse)
print(isPalindrome("Able was I, ere I saw Elba"))
print(isPalindrome("able was i ere i saw elba")) # True
print(isPalindrome("Madam, I'm Adam"))
print(isPalindrome("a x a")) # True
print(isPalindrome("racecar")) # True
print(isPalindrome("Dud"))
print(isPalindrome("oho!"))
# Longest Palindrome
# --------------------------------------------------------------------------------
# For this challenge, we will look not only at the entire string, but also substrings within it. For a string, return the longest palindromic substring. Given "what up, dada?", return "dad". Given "not much", return "n". Include spaces as well (i.e. be strict, as in the “Is Palindrome” challenge): given "My favorite racecar erupted!", return "e racecar e".
def longestPalindrome(string):
palList = {}
for i in range(len(string)):
# print(i, string[0:i+1])
for j in range(len(string[0:i + 1])):
test = string[j:i + 1]
# print(test)
if (isPalindrome(test)):
if len(test) in palList.keys():
pass
else:
palList[len(test)] = test
# palList.append(string[j:i + 1])
largest = 1
for key in palList:
if key > largest:
largest = key
# print(palList[largest])
return(palList[largest])
print(longestPalindrome("not much")) # n
print(longestPalindrome("what up, dada?")) # dad
print(longestPalindrome("My favorite racecar erupted!")) # e racecar e
| true |
ce3fa6c3c2e0337712a0ad658c974e49ac46d516 | KodaHand/LP3THW | /ex6.py | 1,010 | 4.5625 | 5 | # declares types of people
types_of_people = 10
# x is now equal to a string while putting types_of_people in it
x = f"There are {types_of_people} types of people."
# declares binary
binary = "binary"
# declares do_not
do_not = "don't"
# makes y a string and puts binary and do_not into it
y = f"Those who know {binary} and those who {do_not}"
# prints x
print(x)
# prints y
print(y)
# prints a string and puts in x
print(f"I said: {x}")
# prints a string and puts in y
print(f"I also said: '{y}'")
# declares hilarious as false
hilarious = False
# joke_evaluation declaration as a string and puts in hilarious
joke_evaluation = f"Isn't that joke so funny?! {hilarious}"
# .format takes the format of the string because joke_evaluation is a string
# It reformats hilarious which is a bool into a string to be able to print
print(joke_evaluation.format(hilarious))
# declares w a string
w = "This is the left side of..."
# declares e a string
e = "a string with a right side."
# prints w + e
print(w + e) | true |
e5a553b35d9d178cfc0add1957e6d34a0760eb0d | McMunchly/python | /pypractice/e13.py | 397 | 4.25 | 4 | # create a fibonacci sequence up to a user-inputted length
limit = int(input("Enter number of fibonacci digits to display: "))
numbers = []
num1 = 1;
num2 = 1;
while(limit > 0):
if(len(numbers) < 2):
numbers.append(num1)
else:
num1 = numbers[len(numbers) - 1]
num2 = numbers[len(numbers) - 2]
numbers.append(num1 + num2)
limit -= 1
print(numbers)
| true |
b64356a7f937b2cbdf67639fe77c0d95bf2264f9 | McMunchly/python | /games/game.py | 1,231 | 4.15625 | 4 | # move around a little play area
import random
blank = "."
def DisplayMap(area, size):
for x in range(0, size):
row = ""
for y in range(0, size):
row = row + area[y + (size * x)] + " "
print(row)
def Move(move, coord, board):
board[coord] = blank
if command == "w" and coord >= size:
print("move up")
coord = coord - size
elif command == "s" and coord < len(bounds) - size:
print("move down")
coord = coord + size
elif command == "a" and coord % size != 0:
print("move left")
coord = coord - 1
elif command == "d" and (coord + 1) % size != 0:
print("move right")
coord = coord + 1
board[coord] = "@"
return board
size = int(input("Enter size of area: "))
bounds = [blank for _ in range(size ** 2 - 1)]
bounds.append("@")
coord = bounds.index("@")
play = True
while play == True:
DisplayMap(bounds, size)
command = input("Enter command (w, a, s, d, or quit): ")
command = command[0]
command = command.lower()
if command == "q":
play = False
else:
bounds = Move(command, coord, bounds)
coord = bounds.index("@")
| true |
5b9f964265daa61a5629c2c2c5c57708d1a4a127 | taoxm310/CodeNote | /A_Byte_of_Python/str_format.py | 802 | 4.21875 | 4 | age = 20
name = 'time'
# 不省略index
print('{0} was {1} years old when he wrote this book'.format(name,age))
# 省略index
print('{} was {} years old when he wrote this book'.format(name,age))
# 用变量名
print('{name} was {age} years old when he wrote this book'.format(name=name,age=name))
# f-string
print(f'why is {name} playing with that python?')
# 对于浮点数 '0.333',保留(.) 小数点后面三位
print('{0:.3f}'.format(1.0/3))
# fill with underscores(_) with the text centered
# (^) to 11 width '___hello___'
# 用_填充到长度为11,并保持文本处于中间
print('{0:_^11}'.format('hello'))
# keyword-based 基于关键字输出
print('{name} wrote {book}'.format(name ='Time', book='A Byte of Python'))
# 移除print 换行
print('a',end='')
print('b',end='')
| true |
ffc749569b1b8703910f19b5f269a52ff579b5c3 | guptaNswati/holbertonschool-higher_level_programming | /0x07-python-classes/102-square.py | 1,170 | 4.4375 | 4 | #!/usr/bin/python3
"""
This is a Square class.
The Square class creates a square and calculates its area.
"""
class Square:
"""
Initialize Square object
"""
def __init__(self, size=0):
self.size = size
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if not (type(value) == int or type(value) == float):
raise TypeError("size must be a number")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
"""
Return area of Square object
"""
def area(self):
return (self.size * self.size)
"""
Compare Square objects
"""
def __lt__(self, other):
return (self.area() < other.area())
def __le__(self, other):
return (self.area() <= other.area())
def __eq__(self, other):
return (self.area() == other.area())
def __ne__(self, other):
return (self.area() != other.area())
def __gt__(self, other):
return (self.area() > other.area())
def __ge__(self, other):
return (self.area() >= other.area())
| true |
f3cd5efb8312d4b906aeca951e07a4488458cb15 | dotthompson/rpg-game | /Python3/triangle.py | 358 | 4.1875 | 4 | # How to print triangle
# ask for range
num = int(input("Enter the range: \t "))
# i loop for range(height) of the triangle
# first j loop for printing space ' '
# second j loop for printing stars '*'
for i in range(num):
for j in range((num - i) - 1):
print(end = ' ')
for j in range(i + 1):
print('*', end = ' ')
print()
| false |
c6ae5cda3aafe6195841d5e7e42e366a29916c23 | dotthompson/rpg-game | /Python3/py101.py | 1,283 | 4.125 | 4 | # comments after this wont be read
# "hello world"
# 'hello world'
# \ escape character
# 'I\'m'
# "I'm "
# several lines of test for string
# """
# asdsadasd
# sadasdasa
# sadasdasa
# """
# print
# print("hello world")
# print('abc')
# print('cde')
# print('Dorothy' + ' Thompson')
# print('\tThis is a great day!')
# print(5 + 4)
# print(5 ** 2)
# print(5%2)
# print(6%2)
# print(6%4)
# city = "Houston"
# print(city)
# print('Houston is a big city')
# print('Houston is located in Texas')
# found_coins = 20
# magic_coins = 10
# stolen_coins = 3
# result = found_coins + magic_coins * 365 - stolen_coins * 52
# print(result)
first_name = "Dorothy"
last_name = "Thompson"
# result = "Hello {1} {0} {0}".format(first_name,last_name)
# result = f'Hello {first_name} {last_name}'
# print(result)
# print(type(13))
# print(isinstance(first_name , str))
# name = input('What\'s your name? ')
# last_name = input('What is your last name? ')
# print(f'Hello {name} {last_name}')
# print(type(name))
# print(type(last_name))
# four = '4'
# print(type(four)) #str
# a = int(four) #int
# print(type(a))
# print(a * 4)
# a = int(input('First Value >>'))
# b = int(input('Second Value >>'))
# c = a + b
# print(f'the value of {a} + {b} = {c} ')
| false |
9b32a23d496fa5162c68963daf4c73efbfb4fd70 | yonicarver/cs265 | /Lab/4/lab04/s1.py | 1,182 | 4.28125 | 4 | # python 3.5
# -----------------------------------------------------------------------------
# Yonatan Carver
# CS 265 - Advanced Programming
# Lab 04
# -----------------------------------------------------------------------------
# Q2.1 Look at the students input file in the directory. Write a Python program
# that, for each student, computes the average of all the scores for that student,
# prints 2 columns: the name, followed by the average. Submit s1.py.
# -----------------------------------------------------------------------------
from sys import argv
def average(nums):
''' Compute average of list of numbers '''
return sum(nums)/len(nums)
with open(argv[1], 'r') as f:
lines = [line.strip() for line in f]
nums = []
for item in range(len(lines)):
nums.append([int(s) for s in lines[item].split() if s.isdigit()])
averages = []
for i in nums:
averages.append(average(i))
names = []
for i in lines:
names.append(i.split(' ', 1)[0])
together = zip(names, averages)
print('NAME','\t', 'AVERAGE')
print('------------------')
for item in together:
print('%s \t %.2f' % (item[0], item[1]))
| true |
abb08002375faf85d8eaae6025f8c3aaf19bc0da | Gritide/Py | /ps37.py | 1,429 | 4.21875 | 4 | #Dogukan Celik
#Dogukan.Celik89@myhunter.cuny.edu
def computeFare(zone, ticketType):
"""
Takes as two parameters: the zone and the ticket type.
Returns the Copenhagen Transit fare, as follows:
3 If the zone is 2 or smaller and the ticket type is "adult", the fare is 23.
3If the zone is 2 or smaller and the ticket type is "child", the fare is 11.5.
3If the zone is 3 and the ticket type is "adult", the fare is 34.5.
3If the zone is 3 or 4 and the ticket type is "child", the fare is 23.
If the zone is 4 and the ticket type is "adult", the fare is 46.
If the zone is greater than 4, return a negative number (since your calculator does not handle inputs that high).
"""
fare = 0
if zone <=2 and ticketType=="adult":
fare=23
elif zone <=2 and ticketType=='child':
fare=11.5
elif zone ==3 and ticketType=='adult':
fare=34.5
elif zone ==3 and ticketType=='child':
fare=23
elif zone ==4 and ticketType=='child':
fare=23
elif zone ==4 and ticketType=='adult':
fare=46
else:
fare=-1
return(fare)
def main():
z = int(input('Enter the number of zones: '))
t = input('Enter the ticket type (adult/child): ').lower()
fare = computeFare(z,t)
print('The fare is', fare)
#Allow script to be run directly:
if __name__ == "__main__":
main()
| true |
9d09f5c1cb775fcb7b29ca648f2566f55bb59048 | SaintClever/Pythonic | /quiz/questions.py | 2,938 | 4.375 | 4 | """ Quiz questions and answers """
import random
# Return / enter not included: 3 spaces
questions = {
'1. What is the result of f"{2 + 2} + {10 % 3}": ': '4 + 1',
'2. Assuming name = "Jane Doe", what does name[1] return: ': 'a',
'3. What will name.find("Doe") return from "Jane Doe": ': '5',
'4. What is the result of "bag" > "apple": ': 'True',
'5. console.log() is to JavaScript as " blank " is to Python: ': 'print()',
'6. print "Hello Pythonic!": ':
'print("Hello Pythonic!")',
'7. Coding Challenge: while True print "keep learning and enjoying life": "':
'while True: print("keep learning and enjoying life")',
'8. Coding Challenge: interate over a dict named user_data via the items() method.\
\n Use the variable username to represent your "keys", and the variable password\
\n to represent your "values". Finally print out username, and password.':
'for username, password in user_data.items(): print(username, password)',
'9. create a function named ice_cream with two parameters, flavor="vanilla" and topping=None.\
\n Return your flavor and topping in a undeclared tuple: ':
'def ice_cream(flavor="vanilla", topping=None): return (flavor, topping)',
'10. Coding Challenge: if food is "salad" print healthy else if food is "fast food" print unhealthy: ':
'if food == "salad": print("healthy")elif food == "fast food": print("unhealthy")',
'11. Coding Challenge: if 5 is greater than 1 print True, else print False ':
'if 5 > 1: print(True)else: print(False)',
'12. Using double quotes and the insert method please insert "New York"\
\n to cities = ["a", "b", "c"] at index 0: ':
'cities.insert(0, "New York")',
'13. How would you append "python" to a list called langs: ':
'langs.append("python")',
'14. create a list named cities with "LA", "NY" and "SEA": ':
'cities = ["LA", "NY", "SEA"]',
'15. Re-write the multiline comment below in a single line using single quotes:\n\n"""\nPython\nis\nawesome!\n"""':
'\'Python is awesome!\'',
'16. Coding Challenge: if clothing is red and beard is white, person equals Santa: ':
'if clothing == "red" and beard == "white": person = "Santa"',
'17. what data type is user_variable = {2, 4, 5}. A "dict" or "set": ':
'set',
'18. Coding Challenge: if first_name equal "Sherlock", last_name is "Holmes" ':
'if first_name == "Sherlock": last_name = "Holmes"',
'19. Coding Challenge: if species equal to "cat" print "Yep, it\'s a cat." ':
'if species == "cat": print("Yep, it\'s a cat.")',
'20. print "Hello World!" : ':
'print("Hello World!")'
}
# Randomize dict: because you can't shuffle a dict
list_questions = list(questions.items()) # place dict into a list
random.shuffle(list_questions) # shuffle list
questions = dict(list_questions) # turn list back into a dict
| true |
e12e46e63d88d56de944588fa11ffc6003c8a24d | natalietanishere/Coding-Practice | /Referencing-Files/recur.py | 417 | 4.25 | 4 |
def recursive_method(num):
def factorial(num):
if num == 1:
return 1
else:
return (num * factorial(num-1))
if num<0:
print("No factorials")
#def recur_factorial(num):
#if num==1:
#return num
# else:
## return num * recur_factorial(num-1)
#if num>0:
#print("Sorry, factorials don't exist in negative numbers")
#elif num==0:
#print("The factorial is 1")
#elif num<0:
| false |
37edfab5a975869ef4e5e024a41edee570a586ef | mdjibran/Algorithms | /Matrix/FlipMatrixInPlace.py | 921 | 4.1875 | 4 | def printMat(matrix):
for row in matrix:
print(row)
print("---------")
def Flip(matrix):
source = 0
destination = len(matrix)-1
temp = matrix[0][2] # 1
matrix[0][2] = matrix[0][0] # 1 -> 3
printMat(matrix)
temp, matrix[2][2] = matrix[2][2], temp # 3 -> 9
printMat(matrix)
temp, matrix[2][0] = matrix[2][0], temp # 9 -> 7
printMat(matrix)
temp, matrix[0][0] = matrix[0][0], temp # 7 -> 1
printMat(matrix)
temp = matrix[1][2] # 6
matrix[1][2] = matrix[0][1] # 2 -> 6
printMat(matrix)
temp, matrix[2][1] = matrix[2][1], temp # 6 -> 8
printMat(matrix)
temp, matrix[1][0] = matrix[1][0], temp # 8 -> 4
printMat(matrix)
temp, matrix[0][1] = matrix[0][1], temp # 4 -> 2
printMat(matrix)
Flip(
[
[1,2,3],
[4,5,6],
[7,8,9]
])
'''
[1,2,3],
[4,5,6],
[7,8,9]
[7,4,1],
[8,5,2],
[9,6,3]
''' | false |
deb1dee5fbd43c861c574176ae1f9acd5ca2d317 | cwg1003/team-6-456 | /Confighandler.py | 1,577 | 4.53125 | 5 | # Author: Chad Green & Diyorbek Juraev
# Date: 03/31/2021
'''
This program:
1. validates an input file and contents in it.
2. Handle file opening in a mode
2.1. Handle file exceptions, etc.
3. Search file contents
'''
import magic
def parse_file(filename):
#open the file to read, and implement the logic as required by the assignment-4
# opens the file
parsefile = open(filename, "r")
# reads the lines into lineread
lineread = parsefile.readlines()
# reads the lines line by line
for line in lineread:
# if 'true' is in the line then the line is split and the keyword is printed
if 'true' in line:
keywords = line.split(":")
print(keywords[0])
# closes the file
parsefile.close()
def validate_file(filename):
# validate if the file is a text file, if it is return true, otherwise return false
validate = False # bool to check if file is text
file = magic.from_file(filename) # downloaded and imported magic to check get the file type
# check the magic to see if it is text
if 'text' in file:
validate=True
# return true or false
return validate
# Main program, do not modify it.
if __name__ == "__main__":
filename="my_config.txt"
valid=validate_file(filename)
# print all the setting values set to ON/true on the configuration file.
if valid:
print("File %s is a valid text file. Now printing all the settings set ON" %filename)
parse_file(filename)
else:
print("File %s is NOT a valid text file. Program aborted!" % filename)
| true |
726ec712ff946acea5ede884c030d2ed61cb9422 | TirumaliSaiTeja/Python | /app.py | 1,801 | 4.15625 | 4 | # weight = int(input("weight: "))
# unit = input("(L)bs or (K)gs: ")
# if unit.upper() == "L":
# converted = weight * 0.45
# print(f"You are {converted} kilos")
# else:
# converted = weight / 0.45
# print(f"You are {converted} pounds")
# course = 'learning python course'
# print('learning' in course)
# Roundof
# t = 2.765
# print(round(t))
# Absolute will return positive value
# t = -2.333
# print(abs(t))
# using math operator module
#
# import math
#
# t = 4
# print(math.ceil(t))
# print(math.floor(t))
# print(math.factorial(t))
# print(math.isqrt(t))
# if statements
'''Price of a house is $1M
if buyer has good credit they need to
put down 10%
otherwise
they need to put down 20%
print the down payment'''
# price = 1000000
#
# has_good = False
#
# if has_good:
# down_payment = 0.1*price
# else:
# down_payment = 0.2*price
#
# print(f'Down payment: ${down_payment}')
# has_high_income = True
# has_good_credit = True
#
# if has_high_income and has_good_credit:
# print('Eligible for loan')
# else:
# print('Sorry, your not eligible')
# comparison operators
# temperature = 20
#
# if (temperature>30):
# print('it is hot day')
# elif(temperature<10):
# print('it is cold day')
# else:
# print('its neither hot nor cold')
# name = 40
#
# if name<3:
# print('name must be three characters')
# elif name>50:
# print('name cab be maximum of 50 characters')
# else:
# print('name looks good')
#
# Weight convertor
# x = int(input('Weight: '))
# y = input('Weight in (L)bs or (K)g: ')
#
# if y.upper() == 'L':
# converted = x * 0.45
# print(f'you weight is: {converted} in kilos')
# else:
# converted = x / 0.45
# print(f'your weight is: {converted} in pounds')
| true |
55d1327b7920652db09011cca88e7597fd527588 | edelira/rock-paper-scissors | /rock-paper-scissors.py | 1,545 | 4.15625 | 4 | import random
print "Welcome to Rock, Paper, Scissors! \nBest out of five wins! \nSelect your tool"
user_score = 0
computer_score = 0
def score():
print "Current score \nUser: %d \nComputer: %d" %(user_score, computer_score)
while True:
user_pick = raw_input("Rock, paper or scissors? ").lower()
options = ["rock","paper", "scissors"]
computer_pick = random.choice(options)
if user_pick == computer_pick:
print "Both selected %s. Tie" %user_pick
elif user_pick == "rock":
if computer_pick == "scissors":
print "Rock beats scissors. You win!"
user_score += 1
score()
elif computer_pick == "paper":
print "Paper bears rock. You lose."
computer_score +=1
score()
elif user_pick == "paper":
if computer_pick == "rock":
print "Paper beats Rock. You win!"
user_score += 1
score()
elif computer_pick == "scissors":
print "Scissors beats paper. You Lose."
computer_score +=1
score()
elif user_pick == "scissors":
if computer_pick == "paper":
print "scissors beats paper. You win!"
user_score += 1
score()
elif computer_pick == "rock":
print "Rock beats scissors. You lose."
computer_score +=1
score()
if user_score == 3 or computer_score == 3 :
break
if user_score == 3:
print "You win!"
else:
print "You lose." | true |
b4e4f0b90bba0259511a0c1654729d71d1fec7fb | YashDjsonDookun/home-projects | /Projects/HOME/PYTHON/Codecademy/Vacation/Vacation.py | 933 | 4.125 | 4 | print ("Please choose a city from Los Angeles, Tampa, Pittsburgh or Charlotte.")
def hotel_cost(nights):
#Assuming that the hotel costs $140/nights
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3 and days < 7:
cost -= 20
return cost
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + spending_money
city = str(raw_input("Enter City: "))
days = int(raw_input("Enter number of Days: "))
spending_money = int(raw_input("Enter amount of Spending Money: "))
print ("Your Total Cost for this trip is:"), trip_cost(city, days, spending_money)
| true |
fc403310c072617a16037a0a1c1600e883d4e556 | radetar/hort503 | /Assignment03/ex30.py | 463 | 4.15625 | 4 | people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars")
elif cars < people:
print("We should not take the cars")
else:
print("We can't decide")
if trucks > cars:
print("Too many trucks")
elif trucks < cars:
print("maybe we could take the trucks")
else:
print("still can't decide")
if people > trucks:
print("alright, lets take the trucks")
else:
print("fine lets stay home")
| true |
973f067b608ac5da1cdd7efbffcde8c3973235d9 | Bicky23/Data_structures_and_algorithms | /merge_sort/myversion_inversions.py | 1,205 | 4.1875 | 4 | def merge_sort_inversions(array):
# base case
if len(array) <= 1: return array, 0
# split into two and recurse
mid = len(array) // 2
left, left_inversions = merge_sort_inversions(array[:mid])
right, right_inversions = merge_sort_inversions(array[mid:])
# merge and return
sorted_array, inversions = merge(left, right)
return sorted_array, inversions + left_inversions + right_inversions
# easiest to understand merge() function
def merge(left, right):
# empty merged list
merged = []
inversions = 0
''' For both the sorted lists, compare their first element,
then remove the element which is smaller and put it in the merged list '''
while len(left) and len(right):
if left[0] <= right[0]:
merged.append(left[0])
left.pop(0)
else:
merged.append(right[0])
right.pop(0)
inversions += 1
# check for remaining values in left
if len(left):
merged.extend(left)
# check for remaining values in right
if len(right):
merged.extend(right)
return merged, inversions
array = [3,3,1,4]
result = merge_sort_inversions(array)
print(result)
| true |
a9ef5ee835e77018609406891d020a72be16d91e | halilibrahimdursun/class2-functions-week04 | /4.9_alphabetical_order.py | 386 | 4.53125 | 5 | def alphabetical_order(words=''):
"""takes an input form user in which the words seperated with hyphen icon(-), sorts the words in alphabetical order,
adds hyphen icon (-) between them and gives the output of it."""
words = words.split('-')
words.sort()
return '-'.join(words)
print(alphabetical_order(input('Write the words with hyphen icon(-) between them: ')))
| true |
87a14dfd5e90062e5596119d3b735519d61b795a | PierreVieira/Python_Curso_Em_Video | /ex014.py | 276 | 4.21875 | 4 | """
Exercício Python 014: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus
Fahrenheit.
"""
celcius = float(input('Informe a temperatura em °C: '))
print(f'A temperatura de {celcius} °C corresponde a {celcius*9/5 + 32} °F')
| false |
6168dfbcc982d78e54c9e5e8423004cd84001732 | PierreVieira/Python_Curso_Em_Video | /ex093.py | 1,208 | 4.34375 | 4 | """
Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o
nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final,
tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
"""
nome_jogador = input('Nome do jogador: ').title()
qtde_partidas = int(input(f'Quantas partidas {nome_jogador} jogou? '))
lista_gols = []
for c in range(qtde_partidas):
lista_gols.append(int(input(f' Quantos gols na {c+1}ª partida? ')))
qtde_tracos = 25
print('-='*qtde_tracos)
jogador = {'nome': nome_jogador, 'gols': lista_gols, 'total_gols': sum(lista_gols)}
print(jogador)
print('-='*qtde_tracos)
print(f'O campo nome tem o valor {jogador.get("nome")}')
print(f'O campo gols tem o valor {jogador.get("gols")}')
print(f'O campo total_gols tem o valor {jogador.get("total_gols")}')
print('-='*qtde_tracos)
print(f'O jogador {jogador.get("nome")} jogou {jogador.get(len("gols"))} partidas')
cont = 1
for qtde_gols in jogador.get("gols"):
print(f' => Na {cont}ª partida, fez {qtde_gols} gols.')
print(f'Foi um total de {sum(jogador.get("gols"))} gols.')
| false |
d45c77453c57d60a233db4fe2b3f4fc30e2f8816 | PierreVieira/Python_Curso_Em_Video | /ex067.py | 500 | 4.125 | 4 | """
Exercício Python 067: Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado
pelo usuário. O programa será interrompido quando o número solicitado for negativo.
"""
while True:
numero = int(input('Digite um número par ver sua tabuada: '))
if numero < 0:
break
print('-'*15)
for c in range(10):
print(f'{numero:2} X {c+1:2} = {numero*(c+1):2}')
print('-'*15)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!')
| false |
721f12d9b18c38fc661d20c3bac9f0d1d52a5e90 | PierreVieira/Python_Curso_Em_Video | /ex059.py | 932 | 4.28125 | 4 | """
Exercício Python 059: Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
"""
def exibe_menu():
print('[1] SOMAR')
print('[2] MULTIPLICAR')
print('[3] MAIOR')
print('[4] NOVOS NÚMEROS')
print('[5] SAIR DO PROGRAMA')
while True:
a, b = map(float, input('Informe dois valores: ').split())
while True:
exibe_menu()
print('--' * 4)
opcao = int(input('Opção: '))
print('--' * 4)
if 1 <= opcao <= 5:
break
if opcao == 1:
print(f'{a} + {b} = {a + b}')
elif opcao == 2:
print(f'{a} * {b} = {a * b}')
elif opcao == 3:
print(f'O maior número entre {a} e {b} é {max([a, b])}')
elif opcao == 5:
print('Volte sempre :)')
break
| false |
7a3415d734459585ed4f3b97d550e1c0284134df | PierreVieira/Python_Curso_Em_Video | /ex011.py | 639 | 4.15625 | 4 | """
Exercício Python 011: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a
quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados.
"""
largura_parede = float(input('Largura da parede em metros: '))
altura_parede = float(input('Altura da parede em metros: '))
area_parede = largura_parede*altura_parede
qtde_tinta = area_parede/2
print(f'Sua parede tem a dimensão de {largura_parede}x{altura_parede} e sua área é de {area_parede}m².')
print(f'Para pintar essa parede, você precisará de {qtde_tinta:.2f} litros de tinta.')
| false |
6d513e20684d8ae107909a6641536a3154b00e32 | PierreVieira/Python_Curso_Em_Video | /ex005.py | 271 | 4.125 | 4 | """
Exercício Python 005: Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor.
"""
numero = int(input('Digite um número: '))
print(f'Analisando o número {numero}, seu antecessor é {numero-1} e o seu sucessor é {numero+1}')
| false |
fbb95bf72ee99f80cedd361e76ce280ef22556fb | PierreVieira/Python_Curso_Em_Video | /ex065.py | 648 | 4.1875 | 4 | """
Exercício Python 065: Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a
média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele
quer ou não continuar a digitar valores.
"""
lista_numeros = []
while True:
lista_numeros.append(int(input('Digite um número: ')))
if input('Quer continuar [S/N]? ').upper() == 'N':
break
print(f'Você digitou {len(lista_numeros)} números e a média foi {sum(lista_numeros)/len(lista_numeros):.2f}')
print(f'O maior valor foi {max(lista_numeros)} e o menor foi {min(lista_numeros)}')
| false |
d8deb644b0bf3f70b789d19a087a6eb6129237bc | PierreVieira/Python_Curso_Em_Video | /ex109/main.py | 547 | 4.15625 | 4 | """
Exercício Python 109: Modifique as funções que form criadas no desafio 107 para que elas aceitem um parâmetro a mais,
informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108.
"""
from ex109 import moedas
valor = float(input('Digite o preço: R$ '))
print(f'A metade de R$ {moedas.moeda(valor)} é R$ {moedas.metade(valor, format=True)}')
print(f'O dobro de R$ {moedas.moeda(valor)} é R$ {moedas.dobro(valor)}')
print(f'Aumentando 10%, temos R$ {moedas.aumento_10_pc(valor)}')
| false |
ba5ae12de79a18282aabc202ea58d5e864c72019 | PierreVieira/Python_Curso_Em_Video | /ex089.py | 2,059 | 4.28125 | 4 | """
Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta.
No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno
individualmente.
"""
from statistics import mean
def pegar_nome():
while True: #Garantindo que o nome está certo
nome = input('Nome: ').title()
if not(nome.isalpha()):
print('Digite apenas caracteres!')
else:
return nome
def pegar_nota(n):
while True:
try:
nota = float(input(f'Nota {n}: '))
except ValueError:
print('Informe apenas números! Utilize ponto em vez de vírgula para separar casas decimais.')
else:
return nota
def pegar_resposta():
while True:
resposta = input('Deseja continuar [S/N]? ').upper()
if resposta == 'S' or resposta == 'N':
return resposta
def info_geral():
for aluno in lista_alunos:
print('{:<3}{:<9}{:>8.1f}'.format(aluno[0], aluno[1], aluno[3]))
def tratar_entrada_n_aluno():
number = -1
while not (0 <= number <= len(lista_alunos) - 1) and number != 999:
try:
number = int(input('Mostrar notas de qual aluno? (999 interrompe): '))
except ValueError:
print('Informe apenas valores inteiros!')
else:
return number
number_aluno = 1
lista_alunos = []
while True:
nome = pegar_nome()
nota1 = pegar_nota(1)
nota2 = pegar_nota(2)
lista_aluno = [number_aluno, nome, [nota1, nota2], mean([nota1, nota2])]
lista_alunos.append(lista_aluno)
resposta = pegar_resposta()
if resposta == 'N':
break
qtde_tracos = 10
print('-='*qtde_tracos)
print('No. NOME{:>11}'.format("MÉDIA"))
print('-'*qtde_tracos*2)
info_geral()
while True:
print('--'*25)
n_aluno = tratar_entrada_n_aluno()
if n_aluno == 999:
break
else:
print(f'Notas de {lista_alunos[n_aluno][1]} são {lista_alunos[n_aluno][2]}')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.