blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
df2f9cfbaea7c4c7d8d5b7511a0597cb476a8e7f | techbees-consulting/datascience-dec18 | /exception_handling/userdefined.py | 741 | 3.8125 | 4 | #!python
# define your own exceptions
class NumberTooSmallError(Exception):pass
class NumberTooBigError(Exception):
def __init__(self):
print('\nException: NumberTooBigError:\nYour number is too big. \nTry a smaller one!')
class NumberThreeError(Exception):
def __init__(self):
print ('\nException: ThreeNumberError:\nThree is not number ya\'re lookin\' for.\n')
class NumberFiveError(Exception):pass #uncaught exception
#
# #function that uses user-defined exceptions
def checkNumber(num):
if(num == 3):
raise NumberThreeError
elif(num == 5):
raise NumberFiveError
elif(num < 99):
raise NumberTooSmallError
elif(num > 99):
raise NumberTooBigError
return num
|
437eb92c7d868c9ad1c7c18b961e8ace1f1e425a | Arundeepmahajan/PerfectNumber | /perfectnumber.py | 234 | 3.953125 | 4 | n=int(input("Enter a number to check if it is perfect number or not: "))
sum=0
for x in range(1,n):
if n%x==0:
sum=sum+x
if(sum==n):
print(n," is a perfect number")
else:
print(n," is not a perfect number") |
1388d0abfeb65ba4f986fead9e686f006766d357 | YuriNem/Python-Tasks | /lab6/list2.py | 2,207 | 3.953125 | 4 | isCorrect = True
while isCorrect:
# Ввод строки
s = input('Input array in string: ')
# Проверка строки
for i in range(len(s)):
if not (
(57 >= ord(s[i]) >= 48) or
ord(s[i]) == 45 or
ord(s[i]) == 46 or
ord(s[i]) == 32
):
isCorrect = False
break
# Начало новой итерации при неправильном вводе
if not isCorrect:
print('Uncorrect input')
isCorrect = True
continue
# Создание массива
l = list(map(float, s.split()))
sumAbsNegative = 0
counterNegative = 0
midArifNegative = 0
multiplicationPositive = 1
counterPositive = 0
midGeomPositive = 0
for i in range(len(l)):
# Отрицательные элементы
if l[i] < 0:
sumAbsNegative += abs(l[i])
counterNegative += 1
# Положительные элементы
elif l[i] > 0:
multiplicationPositive *= l[i]
counterPositive += 1
if counterNegative:
# Среднее арифметическое модулей отрицательных чисел
midArifNegative = sumAbsNegative / counterNegative
print('Middle arifmetic absolute negative numbers: {:.5g}'
.format(midArifNegative))
else:
print('No negative numbers')
if counterPositive:
# Среднее геометрическое положительных чисел
midGeomPositive = multiplicationPositive ** (1 / counterPositive)
print('Middle geometric positive numbers: {:.5g}'
.format(midGeomPositive))
else:
print('No positive numbers')
if midArifNegative != midGeomPositive and counterNegative and counterPositive:
# Вывод большего
print('{} is bigger'.format('midArifNegative'
if midArifNegative > midGeomPositive
else 'midGeomPositive'))
elif midArifNegative == midGeomPositive and counterNegative and counterPositive:
# Равенство
print('They are equal')
break
|
52cb96b94b5248c77aeb3f3ffa6d335ed061e741 | trillianx/educative_notes | /Data_Structures/Problems_Bank/node_class.py | 2,188 | 4.0625 | 4 | class Node():
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, value):
if value < self.data:
if self.left is not None:
self.left.insert(value)
else:
self.left = Node(value)
elif value > self.data:
if self.right is not None:
self.right.insert(value)
else:
self.right = Node(value)
else:
print('Value already exists')
def search(self, value):
if value == self.data:
return True
elif value < self.data:
if self.left:
return self.left.search(value)
else:
return False
elif value > self.data:
if self.right:
return self.right.search(value)
else:
return False
def delete(self, value):
# if current node's val is less than that of root node,
# then only search in left subtree otherwise right subtree
if value < self.data:
if(self.left):
self.left = self.left.delete(value)
else:
print(str(value) + " not found in the tree")
return self
elif value > self.data:
if(self.right):
self.right = self.right.delete(value)
else:
print(str(value) + " not found in the tree")
return self
else:
# deleting node with no children
if self.left is None and self.right is None:
self = None
# Delete node with no left child
elif self.left is None:
return self.right
# Delete node with no right child
elif self.right is None:
return self.left
else:
current = self.right
while current.left is not None:
current = current.left
self.data = current.data
self.right = self.right.delete(current.data)
return self
|
254c9409e6d30f26839c60a500b4ffed1cf28626 | Elijah3502/CSE110 | /Programming Building Blocks/Week 1/02Teach.py | 1,117 | 4.125 | 4 | #ID badge program
#Get id card data
#Get First Name
first = input("What is your first name? : ")
#Get Last Name
last = input("What is your last name?: ")
#Get Email
email = input("Enter your email: ")
#get Phone Number
phone_number = input("Enter phone number : ")
#Get Job Title
title = input("Enter job title : ")
#Get id number
id_number = input("Enter ID number : ")
#Get hair color
hair_color = input("Enter hair color : ")
#Get Eye Color
eye_color = input("Enter Eye color : ")
#Get Month Started
month_started = input("Enter month started : ")
#Get completed training bool
advanced_completed = input("Has user completed advanced training? (yes/no) : ")
print("\n\n")
#Display ID Card
print("The ID Card is : ")
print("----------------------------------------")
print(last.upper() + ", " + first)
print(title.capitalize())
print("ID : " + id_number)
print("\n" + email.lower())
print(phone_number)
print("\n")
#prints formatted with spacing
print(f"Hair: {hair_color:15} Eyes: {eye_color}")
print(f"Month: {month_started:14} Training: {advanced_completed}")
print("----------------------------------------") |
e52536e18be7b3f9653e17a25fb3c430ffa201dd | njerigathigi/learn-python | /strip.py | 1,203 | 4.4375 | 4 | # The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end)
# characters (space is the default leading character to remove)
# Syntax
# string.strip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as leading/trailing characters
txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x)
print()
#rstrip
# The rstrip() method removes any trailing characters
# (characters at the end a string) ie on the right side of the string.
# space is the default trailing character to remove.
#syntax
# string.rstrip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as trailing characters
# y = txt.rstrip('rrr')
# print(y)
sentence = "banana,,,,,ssqqqww....."
fruit = sentence.rstrip(',sqw.')
print(fruit)
# lstrip
# The lstrip() method removes any leading characters ie to the left of the string
# space is the default leading character to remove
# Syntax
# string.lstrip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as leading characters
txt1 = ",,,,,ssaaww.....banana"
new_txt1 = txt1.lstrip(',saw.')
print(new_txt1)
|
8229c269b2723728f372b164633ac6bd96437a3b | AngelEmil/3ra-Practica---Condicionales- | /Ejercicio 3.py | 366 | 3.828125 | 4 | # 3. Pedir tres números por teclado e imprimir el mayor de ellos solamente
T = int(input("digite otro numero "))
P = int(input("digite otro numero "))
M = int(input("digite otro numero "))
if T > P and T > M:
print(f"El mayor es {T}")
elif P > T and P > M:
print(f"El mayor es {P}")
else:
M > T and M > P
print (f"El mayor es {M}") |
6d463c5a0012c7549a95c6437ec4ef69a76b418c | stummalapally/IS685-Week4 | /factorialrec.py | 198 | 4 | 4 | def factorialRecursive(n):
if n==1:
return 1
return n*factorialRecursive(n-1)
inputNumber=5
print("The factorial of {0} is {1}".format(inputNumber,factorialRecursive(inputNumber))) |
b01510ab82e92b490ef1e8ad3217760d95efe604 | zifengcoder/LeetCode-python | /easy/1比特与2比特字符.py | 1,408 | 3.59375 | 4 | # coding=utf-8
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int] 100
:rtype: bool
"""
stack = []
stack_2 = []
for i in bits:
if stack and stack[-1] == 1:
stack_2.append(str(1) + str(i))
stack = []
else:
if i == 0:
stack_2.append(str(0))
stack.append(i)
if stack_2[-1] == '0':
return True
else:
return False
def is_one_bit_character(self, strings):
i = 0
while i < len(strings):
# 当前位置为0,且已经是最后一个元素,直接返回True
if strings[i] == 0 and i == len(strings) - 1:
return True
if strings[i] == 1: # 当前位置为1,则说明肯定是2比特的开头
i += 2
continue
i += 1 # 当前位置为0(一比特),则从下一个位置开始计算
return False # 所有的元素都遍历完还没返回,说明最后一个字符肯定是2比特**
def demo(self, bits):
for inx, i in enumerate(bits):
if i:
bits[inx] = bits[inx + 1] = None
return bits[-1] == 0
if __name__ == '__main__':
obj = Solution()
bits = [1,1,1,1,0]
print obj.demo(bits) |
82ac83d2f1de10e1e08430ba57e7e73a38b6e1a5 | cosmosZhou/sympy | /axiom/algebra/min/to/floor.py | 1,182 | 3.53125 | 4 | from util import *
@apply
def apply(self):
args = self.of(Min)
x = []
for arg in args:
if arg.is_Floor:
arg = arg.arg
elif arg.is_Add:
flrs = []
non_flrs = []
for i, flr in enumerate(arg.args):
if flr.is_Floor:
flrs.append(flr)
else:
non_flrs.append(flr)
assert flrs
arg = Add(*non_flrs)
assert arg.is_integer
for f in flrs:
arg += f.arg
else:
return
x.append(arg)
return Equal(self, Floor(Min(*x)))
@prove
def prove(Eq):
from axiom import algebra
x, y = Symbol(real=True)
n = Symbol(integer=True)
Eq << apply(Min(n + floor(x), floor(y)))
Eq << Eq[0].apply(algebra.eq.given.et.split.floor)
assert n + floor(x) <= n + x
Eq <<= algebra.imply.lt.floor.apply(x) + n, algebra.imply.lt.floor.apply(y)
Eq << algebra.lt.lt.imply.lt.min.both.apply(Eq[-2], Eq[-1])
Eq << Eq[-1].this.rhs.apply(algebra.min.to.add)
Eq << Eq[-1] - 1
if __name__ == '__main__':
run()
# created on 2020-01-25
|
1561be5165baa902c1a5bb0ef4d74be14e957a8c | sauravsapkota/HackerRank | /Practice/Algorithms/Implementation/Append and Delete.py | 756 | 3.609375 | 4 | #!/bin/python3
import os
# Complete the appendAndDelete function below.
def appendAndDelete(s, t, k):
common_length = 0
for i, j in zip(s, t):
if i == j:
common_length += 1
else:
break
# CASE A
if ((len(s) + len(t) - 2 * common_length) > k):
return "No"
# CASE B
elif ((len(s) + len(t) - 2 * common_length) % 2 == k % 2):
return "Yes"
# CASE C
elif ((len(s) + len(t) - k) < 0):
return "Yes"
# CASE D
else:
return "No"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
t = input()
k = int(input())
result = appendAndDelete(s, t, k)
fptr.write(result + '\n')
fptr.close()
|
5c4ebb60337d071e8ea0120fd685c99d48769348 | juniorboos/ChatbotIPB | /database.py | 2,288 | 4 | 4 | import sqlite3
conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS periodo(id REAL, nome TEXT, descricao TEXT, cod_escola REAL, ano_lect REAL, semestre REAL, inicio TEXT, fim TEXT)")
c.execute("CREATE TABLE IF NOT EXISTS sala(id REAL, cod_escola REAL, cod_sala REAL, nome TEXT, abrev TEXT)")
c.execute("CREATE TABLE IF NOT EXISTS aula(id REAL, id_periodo REAL, id_sala REAL, activo TEXT, inicio TEXT, fim TEXT)")
c.execute("CREATE TABLE IF NOT EXISTS aula_docente(id_aula REAL, login TEXT)")
def data_entry():
# c.execute("INSERT INTO docente VALUES('juniorboos', 'Milton Boos Junior','junior_boos@live.com',6)")
# c.execute("INSERT INTO docente VALUES('lrmen14', 'Lucas Ribeiro Mendes','lrmen14@gmail.com',2)")
c.execute("INSERT INTO periodo VALUES(1, 'Período 1 SI', 'Primeiro período de Sistemas de Informação', 1, 2020, 2, '2020-09-27', '2020-12-25')")
c.execute("INSERT INTO sala VALUES(1, 1, 1435, 'Laboratório de Computação Avançada', 'LCA')")
c.execute("INSERT INTO sala VALUES(2, 1, 1534, 'Laboratório de Robótica', 'LR')")
c.execute("INSERT INTO aula VALUES(1, 4, 1, 'active', 'Friday 6PM', 'Friday 10PM')")
c.execute("INSERT INTO aula VALUES(2, 4, 2, 'inactive', 'Monday 6PM', 'Monday 10PM')")
c.execute("INSERT INTO aula_docente VALUES(1, 'juniorboos')")
c.execute("INSERT INTO aula_docente VALUES(2, 'juniorboos')")
conn.commit()
c.close()
conn.close()
# create_table()
# data_entry()
def read_from_db():
name = 'Milton Boos Junior'
# sql_select_query = """ SELECT login FROM docente WHERE nome = ?"""
# c.execute(sql_select_query, (name,))
# c.execute('SELECT login FROM docente WHERE nome = "Milton Boos Junior"')
c.execute('SELECT login FROM docente WHERE nome = ?', (name,))
data = c.fetchone()
print(data[0])
c.execute('SELECT id_aula FROM aula_docente WHERE login = ?', (data[0],))
data = c.fetchone()
print(data[0])
c.execute('SELECT id_sala, inicio, fim FROM aula WHERE id = ?', (data[0],))
dataAula = c.fetchone()
c.execute('SELECT nome FROM sala WHERE id = ?', (dataAula[0],))
dataSala = c.fetchone()
res = 'Your class starts at ' + dataAula[1] + ' in the classroom ' + dataSala[0]
print(res)
read_from_db()
c.close
conn.close() |
eeca449cb2434be3e5e767c36b4658f613c8855c | lizejian/LeetCode | /python/456.py | 519 | 3.75 | 4 | class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s3 = -2*31
stack = []
for s1 in nums[::-1]:
if s1 < s3:
return True
while stack and stack[-1] < s1:
s3 = stack[-1]
stack.pop()
stack.append(s1)
return True
if __name__ == '__main__':
nums = [-1, 3, 2, 0]
print(Solution().find132pattern(nums)) |
1336255a7dd60a3369ed6472bf5de94e5c8b12a2 | woodfin8/sql-challenge | /EmployeeSQL/Bonus_SQLChallenge.py | 4,184 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Bonus
# As you examine the data, you are overcome with a creeping suspicion that the dataset is fake. You surmise that your boss handed you spurious data in order to test the data engineering skills of a new employee. To confirm your hunch, you decide to take the following steps to generate a visualization of the data, with which you will confront your boss:
#
# Import the SQL database into Pandas. (Yes, you could read the CSVs directly in Pandas, but you are, after all, trying to prove your technical mettle.) This step may require some research. Feel free to use the code below to get started. Be sure to make any necessary modifications for your username, password, host, port, and database name:
#
# from sqlalchemy import create_engine
# engine = create_engine('postgresql://localhost:5432/<SQL-Challenge>')
# connection = engine.connect()
# Consult SQLAlchemy documentation for more information.
#
# If using a password, do not upload your password to your GitHub repository. See https://www.youtube.com/watch?v=2uaTPmNvH0I and https://martin-thoma.com/configuration-files-in-python/ for more information.
#
# Create a histogram to visualize the most common salary ranges for employees.
#
# Create a bar chart of average salary by title.
# In[116]:
#get dependencies
get_ipython().run_line_magic('matplotlib', 'inline')
import pandas as pd
from sqlalchemy import create_engine
import matplotlib.pyplot as plt
import numpy as np
from config import pword
# In[118]:
#create engine
engine = create_engine('postgresql://localhost:5432/SQL-Challenge?user=postgres&password='+pword)
# In[119]:
#connect to database
conn = engine.connect()
# In[40]:
#upload data to pandas
employees = pd.read_sql("SELECT * FROM employees", conn)
title = pd.read_sql("SELECT * FROM titles", conn)
salaries = pd.read_sql("SELECT * FROM salaries", conn)
# In[41]:
#Check salary range
print("The max salary is " + str(salaries["salary"].max()))
print("The min salary is " + str(salaries["salary"].min()))
# In[78]:
#create bins
bins = [39999, 50000, 60000, 70000, 80000, 90000, 100000, 110000,120000, 130000]
#check count in bins
group_names = ["$40k", "$50k", "$60k", "$70k","$80k","$90k", "$100k", "$110k", "$120k" ]
salaries["Salary Range"] = pd.cut(salaries["salary"], bins, labels=group_names)
salaries.head()
count = salaries.groupby("Salary Range").count()
count
# In[111]:
#plot histogram
x = salaries["salary"]
plt.figure(figsize=(20,10))
plt.hist(x, bins = bins, align = "mid", color="forestgreen")
#plt.xticks(np.arange(7), ('$40k', '$50k', '$60k', '$70k', '$80k', '$90k', '$100k+'))
plt.title("Salaries Histogram", fontsize=20)
plt.xlabel("Salary Range in $s", fontsize=20)
plt.ylabel("Number of Employees", fontsize=20)
plt.xlim(40000,130000)
plt.xticks(fontsize =16)
plt.yticks(fontsize=16)
plt.grid()
plt.tight_layout()
plt.savefig("Screen_shots/histogram.png")
plt.show()
# In[76]:
#merge title and salary df's
combined = pd.merge(title, salaries, on='emp_no')
combined.head()
# In[84]:
#calculate average salary for each title using groupby
avg_sal = combined.groupby('title')[['salary']].mean().reset_index()
# In[85]:
#check new df
avg_sal
# In[114]:
#plot bar chart
bar_x = avg_sal["title"]
bar_y = avg_sal["salary"]
plt.figure(figsize=(20,10))
plt.bar(bar_x,bar_y, color ="c")
plt.title("Average Salary per Title", fontsize=20)
plt.xlabel("Titles", fontsize=20)
plt.ylabel("Avg Salary in $s ", fontsize=20)
plt.xticks(fontsize =16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.savefig("Screen_shots/bar_chart.png")
plt.show()
# In[121]:
print("OBSERVATIONS")
print("--------------")
print("The salary histogram shows a typical pay structure where there are a small number of senior managers \n"
"making a high salary and a large number of lower level employees making a lower salary.")
print("However, when looking at average salary by title, the senior and manager positions are making roughly the same\n"
"amount as the junior staff. It appears salaries and titles were randomly assigned to employees in this database.")
print("Happy April Fool's Day...")
# In[ ]:
|
6af3585cb137af8658c150d5dd85c5ee30936562 | lxb1226/Leetcodeforpython | /中等/50-myPow.py | 712 | 3.578125 | 4 | class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
# if n<0:
# x = 1/x
# n = -n
# res = 1
# while n:
# if n&1:
# res *= x
# x *= x
# n >>= 1
# return res
if n==0:
return 1
if n<0:
return 1/self.myPow(x,-n)
if n&1:
return x*self.myPow(x*x,n>>1)
else:
return self.myPow(x*x,n>>1)
if __name__ == "__main__":
solution = Solution()
x = 3
n = -1
res = solution.myPow(x,n)
print(res) |
642e5162347fbd6be644b287d7e9fcb76b080b55 | Diptiman1999/Data-Mining-Lab-Assignments | /Assignment 1/Q10.py | 373 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 11:46:44 2020
@author: DIPTIMAN
"""
n=int(input("Enter the number(greater than 2): "))
if n>=2:
factor=2
num=n
while(num>1):
if(num%factor==0):
print(factor)
num=num//factor
else:
factor+=1
else:
print("The number entered is less than 2")
|
99dd2c4d851f6f0502e00fb87cd02e6a6743df56 | kaivantaylor/Code-Wars | /004_Regex Validate PIN Code/build2.py | 209 | 3.734375 | 4 | def validate_pin(pin):
length = len(pin)
if pin.isdigit() == True:
if length == 4 or length == 6:
return True
else:
return False
else:
return False
|
2cf231dcf560275602d7a1c045a89c9515d0fcdc | Mirabellensaft/DrawCircle | /MovingCircle.py | 1,403 | 3.765625 | 4 | import pyb
import lcd160cr
from math import sqrt # so we don't need to resolve math.sqrt on every loop iteration later
from random import randint
lcd = lcd160cr.LCD160CR('X')
def DrawCircle(r, dx, dy):
"""r = radius of the circle
dx and dy are offset in x and y
so the circle's center is not at 0,0"""
for x in range(0, r):
if x/(sqrt(r**2-x**2)) < 1:
y = round(sqrt(r**2-x**2))
lcd.dot(dx + x, dy - y) #1
lcd.dot(dx + y, dy - x) #2
lcd.dot(dx + y, dy + x) #3
lcd.dot(dx + x, dy + y) #4
lcd.dot(dx - x, dy + y) #5
lcd.dot(dx - y, dy + x) #6
lcd.dot(dx - y, dy - x) #7
lcd.dot(dx - x, dy - y) #8
def Direction(r, d, m, maximum):
"""determines the sign of the slope values
and thus the direction the circle is moving"""
if d-r <= 0:
m = abs(m)
elif d+r >= maximum:
m = -m
else:
m = m
return m
def MovingCircle(r, dx, dy, mx, my):
while True:
my = Direction(r, dy, my, 159)
mx = Direction(r, dx, mx, 129)
dy = dy+my
dx = dx+mx
lcd.erase()
DrawCircle(r, dx, dy)
fg = lcd.rgb(randint(0, 255), randint(0, 255), randint(0, 255))
bg = lcd.rgb(randint(0, 255), randint(0, 255), randint(0, 255))
lcd.set_pen(fg, bg)
lcd.erase()
MovingCircle(30, 30, 60, 1, 2, counter)
|
d7d8a0f47e5edab6785608cf96c1090272669f9e | Wenda-Zhao/ICS3U-Unit3-06-Python | /number_guessing2.py | 787 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Wenda Zhao
# Created on: Dec 2020
# This program guessing random number
import random
def main():
# this function guessing random number
some_variable = str(random.randint(0, 1)) # a number between 0 and 1
# input
your_number = input("Enter your number (between 0 and 1): ")
print("")
# process
if your_number == some_variable:
# output
print("You are correct!")
else:
print("You are wrong, the answer is {0}".format(some_variable))
try:
integer_as_number = int(your_number)
print("You entered an integer correctly")
except Exception:
print("This was not an integer")
finally:
print("Thanks for playing")
if __name__ == "__main__":
main()
|
66204e27238179e5b4350a37eb7919e0ea7609de | edu-athensoft/stem1401python_student | /py201221a_python2_chen/day06_201229/except_8.py | 467 | 3.75 | 4 | """
to catch specific exception
"""
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/ int(entry)
break
except ValueError as ve:
print(ve)
print("Please input a compatible literal for int()")
print()
except ZeroDivisionError as zde:
print(zde)
print("Please do not do division with 0")
print()
print("The reciprocal of", entry, 'is', r) |
b516459c00c45469ed21ed3076f6d2fbeaa37bb4 | OuuGiii/AdventOfCode | /helper/int_code_helper/version7/op_code 2.py | 10,308 | 3.671875 | 4 | from helper.int_code_helper.version7.constants.modes import MODES
class OpCode:
# opcode = [store_at_position, second_attribute, first_attribute, code]
def __init__(self, number):
self.store_at_position = None
self.second_attribute = None
self.first_attribute = None
self.code = None
self.relative_base = None
list_of_digits = list(str(number))
length_of_list = len(list_of_digits)
if length_of_list == 1:
self.store_at_position = 0
self.second_attribute = 0
self.first_attribute = 0
self.code = int(list_of_digits[0])
if length_of_list == 2:
self.store_at_position = 0
self.second_attribute = 0
self.first_attribute = 0
self.code = int(str(list_of_digits[0]) + str(list_of_digits[1]))
if length_of_list == 3:
self.store_at_position = 0
self.second_attribute = 0
self.first_attribute = int(list_of_digits[0])
self.code = int(str(list_of_digits[1]) + str(list_of_digits[2]))
if length_of_list == 4:
self.store_at_position = 0
self.second_attribute = int(list_of_digits[0])
self.first_attribute = int(list_of_digits[1])
self.code = int(str(list_of_digits[2]) + str(list_of_digits[3]))
opcode = [
self.store_at_position, self.second_attribute,
self.first_attribute, self.code
]
# print("opcode: {}".format(opcode))
# Opcode 1 adds together numbers read from two positions
# and stores the result in a third position.
# The three integers immediately after the opcode tell you these three positions -
# the first two indicate the positions from which you should read the input values,
# and the third indicates the position at which the output should be stored.
def run_opcode1(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
store_position = list_of_numbers[i + 3]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
self._store_in_list(list_of_numbers, store_position, number1 + number2)
# Opcode 2 multiply together numbers read from two positions
# and stores the result in a third position.
# The three integers immediately after the opcode tell you these three positions -
# the first two indicate the positions from which you should read the input values,
# and the third indicates the position at which the output should be stored.
def run_opcode2(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
store_position = list_of_numbers[i + 3]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
self._store_in_list(list_of_numbers, store_position, number1 * number2)
# Opcode 3 takes a single integer as input
# and saves it to the position given by its only parameter.
# For example, the instruction 3,50 would take an input value
# and store it at address 50.
def run_opcode3(self, i, list_of_numbers):
input_number = input("Opcode3 happend, insert a single number:\n")
while len(input_number) != 1 or type_helper.is_int(
input_number) == False:
input_number = input(
"The number can only be a singel digit, try again:\n")
store_position = list_of_numbers[i + 1]
self._store_in_list(list_of_numbers, store_position, int(input_number))
# Opcode 3 automatic, takes a single integer as parameter
# and saves it to the position given by its second parameter.
# For example, the instruction 3,50 would take an input value
# and store it at address 50.
def run_opcode3_automatic(self, number, i, list_of_numbers):
store_position = list_of_numbers[i + 1]
self._store_in_list(list_of_numbers, store_position, number)
# Opcode 4 outputs the value of its only parameter.
# For example, the instruction 4,50
# would output the value at address 50.
def run_opcode4(self, i, list_of_numbers):
position_of_number_to_print = list_of_numbers[i + 1]
number_to_print = list_of_numbers[position_of_number_to_print]
print("opcode4 output: {}".format(number_to_print))
return number_to_print
# Opcode 5 is jump-if-true: if the first parameter is non-zero,
# it sets the instruction pointer to the value from the second parameter.
# Otherwise, it does nothing.
def run_opcode5(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
if (number1 != 0):
return number2
else:
return i + 3
# Opcode 6 is jump-if-false: if the first parameter is zero,
# it sets the instruction pointer to the value from the second parameter.
# Otherwise, it does nothing.
def run_opcode6(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
if (number1 == 0):
return number2
else:
return i + 3
# Opcode 7 is less than: if the first parameter is less than the second parameter,
# it stores 1 in the position given by the third parameter.
# Otherwise, it stores 0.
def run_opcode7(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
store_position = list_of_numbers[i + 3]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
self._store_in_list(list_of_numbers, store_position, number1 * number2)
if (number1 < number2):
list_of_numbers[store_position] = 1
else:
list_of_numbers[store_position] = 0
# Opcode 8 is equals: if the first parameter is equal to the second parameter,
# it stores 1 in the position given by the third parameter.
# Otherwise, it stores 0.
def run_opcode8(self, i, list_of_numbers):
position_of_number1 = list_of_numbers[i + 1]
position_of_number2 = list_of_numbers[i + 2]
store_position = list_of_numbers[i + 3]
number1 = self._get_number_from_mode(self.first_attribute,
position_of_number1,
list_of_numbers)
number2 = self._get_number_from_mode(self.second_attribute,
position_of_number2,
list_of_numbers)
self._store_in_list(list_of_numbers, store_position, number1 * number2)
if (number1 == number2):
list_of_numbers[store_position] = 1
else:
list_of_numbers[store_position] = 0
# Opcode 9 adjusts the relative base by the value of its only parameter.
# The relative base increases (or decreases, if the value is negative)
# by the value of the parameter.
def run_opcode9(self, i, list_of_numbers):
self.relative_base += self._get_number_from_list(
list_of_numbers, i + 1)
def _get_number_from_mode(self, mode, number, list_of_numbers):
if mode == MODES.POSITION_MODE:
number_to_return = list_of_numbers[number]
elif mode == MODES.IMMEDIATE_MODE:
number_to_return = number
elif mode == MODES.RELATIVE_MODE:
relative_position = self.relative_base + number
number_to_return = list_of_numbers[relative_position]
return number_to_return
def _store_in_list(self, list_of_numbers, position, number):
while True:
try:
list_of_numbers[position] = number
break
except IndexError as identifier:
space_needed = position - (len(list_of_numbers) - 1)
print("Adding {} zeros".format(space_needed))
i = 0
while i < space_needed:
list_of_numbers.append(0)
i += 1
# Maybe just make list big in beginning, no need for checking this and the above one
def _get_number_from_list(self, list_of_numbers, position):
try:
return list_of_numbers[position]
except IndexError as identifier:
return 0 |
3ce9348be6798e14827d4522e9ecb173278d0217 | Andromalios/practicepython.org | /1.CharacterInput.py | 542 | 4.15625 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Import date
import datetime
now = datetime.datetime.now()
#Name input
name = str( input("What is your name? "))
#Age input
age = int( input("Hey "+ name + ". What is your age? "))
#How many years until 100
years_until_100 = 100 - age
# Print out in how many years they will be 100
print("Hello, "+name+", you will be 100 in ",(now.year+years_until_100)) |
d144f31ae3c1a4de8d94bfcf5fc9c5f372a661d9 | savaged/PyFun | /DogAgeToHumanAge.py | 222 | 3.90625 | 4 | dog_years_alive = int(input("Enter dog's years of life: "))
if dog_years_alive <= 2:
dog_years_age = dog_years_alive * 12
else:
dog_years_age = ((dog_years_alive - 2) * 6) + 24
print("Human age ", dog_years_age)
|
5d7ecd3f840eb1277f4effa5ae23d82e443a00b9 | orlyrevalo/Personal.Project.2 | /Project2.8.11.py | 1,028 | 3.828125 | 4 | '''Function'''
# Importing an Entire Module
print("Importing an Entire Module")
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# Importing Specific Functions
# from module_name import function_name
# from module_name import function_name_0, function_name_1, function_name_2
print("\nImporting Specific Functions")
from pizza import make_pizza
make_pizza(15,'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# Using as to Give a Function an Alias
# from module_name import function_name as fn
print("\nUsing as to Give a Function an Alias")
import pizza as p
p.make_pizza(15, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# Importing All Functions in a Module
# from module_name import *
print("\nImporting All Functions in a Module")
from pizza import *
make_pizza(15, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
|
7849dc6166b6cf6996f6977750df7478eb8ce984 | tcho187/huffmanTree | /puff | 2,850 | 3.6875 | 4 | #!/usr/local/bin/python
#Author:Thomas Cho
#Returns decoded file
from sys import *
import string, bit_io
codeList=list()
#Returns huff tree w/ freq
def buildTree(huffTree):
while len(huffTree)>1:
firstTwo = list(huffTree[0:2]) #Get the first two to combine
#print firstTwo
#print type(firstTwo)
remainder = huffTree[2:] #We took the first two out
#print remainder
combinedFreq = firstTwo[0][0] + firstTwo[1][0] #Taking the first element first freq + second element second freq
#print combinedFreq
huffTree = remainder + [(combinedFreq,firstTwo)] #Getting that branch back to the tree
#print tuples
huffTree=sorted(huffTree, key= lambda x:x[0]) #new iteration of huffman tree that will loop
#print len(huffTree)
j= huffTree[0] #return the single inside the list
return j
#print j
#Returns tree w/o freq
def trimHuffTree(tree):
#Trim the freq counters off, leaving just the letters
p=tree[1] #removing freq first element
if type(p) == type(""): return p #if it's a leaf return it
else: return list((trimHuffTree(p[0]),trimHuffTree(p[1]))) #trim left and right
#Return code table
def assignCodes(node, code=''):
global codeList
if type(node) == type(""):
codeList.append([node,code])
#codes[node]=code
else:
assignCodes(node[0], code+"0")
assignCodes(node[1],code+"1")
return codeList
#encodes file
def encode(str):
global codeList
output=""
for x in str:
for y in codeList:
if x==y[0]:
output+=y[1]
return output
#decodes file
def decode(tree, str):
output=''
p = tree
for x in str:
if x =='0': p = p[0]
else: p = p[1]
if type(p) == type(""):
output+=p
p=tree
return output
def main():
debug=None
bitlist=list() #list of bits from text
#Opening the frequency table
with open(argv[1], 'rb') as input, open(argv[2],'wb') as output:
lineList=input.readlines()
sizeMessage=lineList[-1] #Returns text size of original file
sizeMessage=int(sizeMessage) #Returns int
last_Line=lineList[-2] #Returns Freq table
table=eval(last_Line)
tree=buildTree(table) #build tree
tree=trimHuffTree(tree)
assignCodes(tree)
with bit_io.BitReader(argv[1]) as input, open(argv[2], 'wb') as output:
while True:
c=input.readbit() #read bit at a time
if c==None: break #Returns either '1' or '0'
bitlist.append(c)
bitlist=[str(x) for x in bitlist] #Return str
bitstring=''
bitstring=bitstring.join(bitlist)
original = decode(tree,bitstring) #Returns decoded file w/ table decoded. Need to remove
originalwithouttable="" #Will become the new decoded message
index=0 #counter
#Returns full message that == original text size
for ch in original:
if (index) < (sizeMessage):
originalwithouttable=originalwithouttable+ch
index+=1
#Writing output to file
f=output.write(originalwithouttable)
if __name__ == "__main__" : main()
|
75730fa52516cf63d570e45ffbefb35ca39b7fb3 | mykhamill/Projects-Solutions | /solutions/Pi_to_Nth.py | 600 | 4.53125 | 5 | # Finding Pi to the Nth digit
import sys
from math import factorial, ceil
def double_factorial(n):
return reduce(lambda x, y: x * y, [x for x in range(int(n + 1)) if x % 2 == n % 2 and x > 0], 1)
def pi_to_Nth(n):
return 2 * sum([factorial(x)/(double_factorial((2 * x) + 1) * 1.0) for x in range(int(n + 1))])
def main():
if len(sys.argv) > 1:
n = int(sys.argv[1])
else:
print """Usage: Pi_to_Nth <N>\nWhere <N> is the number of digits to show Pi to"""
return
print ("{pi:." + str(n + 1) + "}").format(pi = pi_to_Nth(ceil(n // 3) * 10))
if __name__ == "__main__":
main()
|
5410ce041cfe8bd908d7e7ba5ff2274448967d24 | acker241/codewars | /string repetition.py | 288 | 3.640625 | 4 | def prefill(n,v):
list = []
if n == 0:
return []
try:
for x in range(int(n)):
list.append(v)
return list
except ValueError:
return (str(n) + " is invalid")
except TypeError:
return (str(n)+" is invalid")
|
5dd1fed653b54c77e6507360ee37b4bee7e8ee9d | rising-entropy/Assignment-Archives | /DAA/Assignment 2/Q1.py | 509 | 3.640625 | 4 | # Q) Given an array A[0…n-1] of n numbers containing repetition of some number. Given an algorithm
# for checking whether there are repeated element or not. Assume that we are not allowed to use
# additional space (i.e., we can use a few temporary variable, O(1) storage).
A = [5, 6, 2, 1, 9, 3, 10, 4, 10, 3]
def areElementsRepeated(A):
#sort the elements
A.sort()
prev = None
for ele in A:
if prev == ele:
return True
prev = ele
return False
print(areElementsRepeated(A))
|
cfd2722b8f0b72062576c0e5c33885b6b0f37835 | ak-foster/Wi2018-Classroom | /students/kevin/session08/ultimate_circle.py | 571 | 4.21875 | 4 | #!/usr/bin/env python3
import math
class Circle(object):
"""Documentation for Circle
"""
def __init__(self, radius=4):
self.radius = float(radius)
@property
def area(self):
return math.pi * self.radius**2
@property
def diameter(self):
return 2 * self.radius
@diameter.setter
def diameter(self, diameter):
self.radius = diameter / 2
def __str__(self):
return f'Circle with radius: {self.radius:.6f}'
def __repr__(self):
return f'Circle({int(self.radius)})'
|
8c1664b59a1961db4535387ecf3efd527adda1ad | liushenghao/pystudy | /oop_test.py | 195 | 3.640625 | 4 | class Ball(object):
def __init__(self, name):
self.name=name
def kick(self):
print("who kicks me? I am %s" %self.name)
a= Ball('A')
a.kick()
c= Ball('李佳佳')
c.kick() |
e7e803fa5c15836ab3e1447ad9b8af8a06acfc3b | rafaelperazzo/programacao-web | /moodledata/vpl_data/177/usersdata/276/95539/submittedfiles/pico.py | 1,582 | 3.546875 | 4 | # -*- coding: utf-8 -*-
def crescente (lista):
cont = 0
if i==0:
if lista[1]>lista[0]:
cont = cont +1
elif i == len(lista)-1:
if lista[len(lista)-1] > lista[len (lista)-2]:
cont = cont +1
else:
if lista[i]<lista[i+1]:
cont = cont +1
if cont == len (lista):
return (True)
else:
return (False)
def decrescente (lista):
cont = 0
if i==0:
if lista[1]<lista[0]:
cont = cont +1
elif i == len(lista)-1:
if lista[len(lista)-1] < lista[len (lista)-2]:
cont = cont +1
else:
if lista[i]>lista[i+1]:
cont = cont +1
if cont == len (lista):
return (True)
else:
return (False)
def pico(lista):
elemento_maior = max(lista)
indice_maior = lista.index(elemento_maior)
for i in range (0,indice_maior+1,1):
elemento_antes = lista[i]
antes = []
antes.append (elemento_antes)
for i in range (indice_maior + 1,len (lista),1):
elemento_depois = lista[i]
depois = []
depois.append (elemento_depois)
if crescente (antes) and decrescente (depois):
return (True)
else:
return (False)
#CONTINUE...
n = int (input('Digite a quantidade de elementos da lista: '))
#CONTINUE...
a = []
for i in range (0,n,1):
valor_a = float (input('Digite o elemento da lista: '))
a.append(valor_a)
print (pico (a))
|
d3ee70eb5a5f45d892067dfa31629c230c587f1c | DmytroKaminskiy/currency_4 | /workua/writers/txt/writer.py | 425 | 3.515625 | 4 | class TXTWriter:
def __init__(self, filename=None):
if not filename:
filename = 'results.txt'
self._file = open(filename, 'w')
def write(self, item: dict):
# sort dict by key and transform to string
item = str(dict(sorted(item.items())))
self._file.write(item)
self._file.write('\n')
def destruct(self):
self._file.close()
|
cfcd3e6a69f893caef178a43cdf806e616b55987 | michaeljwilt/email_verification_script | /verify.py | 2,170 | 3.96875 | 4 | import smtplib
from validate_email import validate_email
# inputs for verification
first_name_input = input(" Enter first name")
last_name_input = input(" Enter last name")
name = first_name_input + last_name_input
domain_input = input(" Enter an email domain(ex. ‘gmail.com’): ")
# email variations list
email1 = name + "@" + domain_input
email2 = first_name_input + "@" + domain_input
email3 = first_name_input + last_name_input[0] + "@" + domain_input
email4 = first_name_input[0] + last_name_input + "@" + domain_input
email5 = first_name_input + "." + last_name_input + "@" + domain_input
email6 = first_name_input + "-" + last_name_input + "@" + domain_input
email7 = last_name_input + "." + first_name_input + "@" + domain_input
email8 = last_name_input + first_name_input + "@" + domain_input
email9 = first_name_input + "_" + last_name_input + "@" + domain_input
email10 = first_name_input[0] + "." + last_name_input + "@" + domain_input
print(email1)
print(email2)
print(email3)
print(email4)
print(email5)
print(email6)
print(email7)
print(email8)
print(email9)
print(email10)
# email verification commands
is_valid = validate_email(email1, check_mx=True)
if validate_email(email1, check_mx=True):
print("Success", email1)
else:
print("Failure")
if validate_email(email2, check_mx=True):
print("Success", email2)
else:
print("Failure")
if validate_email(email3, check_mx=True):
print("Success", email3)
else:
print("Failure")
if validate_email(email4, check_mx=True):
print("Success", email4)
else:
print("Failure")
if validate_email(email5, check_mx=True):
print("Success", email5)
else:
print("Failure")
if validate_email(email6, check_mx=True):
print("Success", email6)
else:
print("Failure")
if validate_email(email7, check_mx=True):
print("Success", email7)
else:
print("Failure")
if validate_email(email8, check_mx=True):
print("Success", email8)
else:
print("Failure")
if validate_email(email9, check_mx=True):
print("Success", email9)
else:
print("Failure")
if validate_email(email10, check_mx=True):
print("Success", email10)
else:
print("Failure")
|
116ac1636bdf2a7c34022415c5cd924a3569c81f | kenzie28/Datathon-2020 | /fifa/Normalize.py | 948 | 3.578125 | 4 | import pandas as pd
import numpy as np
# Loads all datasets
players = pd.read_csv("all_players.csv")
goalies = pd.read_csv("all_goalies.csv")
# Places all columns to be normalized into a list
player_columns = ["overall", "age", "skill_moves", "pace", "shooting", "passing", "dribbling", "defending", "physic", "predicted_growth"]
goalie_columns = ["overall", "age", "gk_diving", "gk_handling", "gk_kicking", "gk_reflexes", "gk_speed", "gk_positioning", "predicted_growth"]
# Iterate through each column and calculate the normalized value
for col in player_columns:
s = "" + col
print(s)
print("mean: ", players[col].mean())
print("std: ", players[col].std())
players[col] = (players[col] - players[col].mean()) / players[col].std()
for col in goalie_columns:
goalies[col] = (goalies[col] - goalies[col].mean()) / goalies[col].std()
# Saves dataset
players.to_csv("norm_players.csv")
goalies.to_csv("norm_goalies.csv")
|
4e822d9b825217528d0f3afe3c2fa11b6ae88b24 | DKCisco/Starting_Out_W_Python | /3_3.py | 316 | 4.0625 | 4 | """
Write an if-else statement that assigns 0 to the variable b if the variable
a is less than 10. Otherwise, it should assign 99 to the variable b.
"""
# Assign variables
a = int(input('Enter the value of a: '))
# Process
if a < 10:
b = 0
else:
b = 99
# Output
print('The value of b =', b) |
721ee94c121ddb1ab5a0662f59b66db5ffc7a193 | andressantillan/kata-codes | /kata-python/count_smileys.py | 807 | 4.09375 | 4 | # Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
# Rules for a smiling face:
# -Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
# -A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
# -Every smiling face must have a smiling mouth that should be marked with either ) or D.
# No additional characters are allowed except for those mentioned.
# Valid smiley face examples:
# :) :D ;-D :~)
# Invalid smiley faces:
# ;( :> :} :]
import re
def count_smileys(arr):
regex_smile = r'[;:][-~]?[)D]'
c = 0
for a in arr:
if re.match(regex_smile, a):
c += 1
return c
arr = [':)',':D', ':~)',':(']
x = count_smileys(arr)
print(x) |
3f628bf39948e740bf32591480d3df4e25849bc2 | RicHz13/PythonExercices | /C27Diccionarios.py | 961 | 3.796875 | 4 | #se pueden recorrer por llave, valor y ambos.
#ejemplos
mi_diccionario = {}
mi_diccionario['primer_elemento'] = 'Hola'
mi_diccionario['segundo_elemento'] = 'Adios'
print (mi_diccionario['primer_elemento'])
calificaciones = {}
calificaciones['algoritmos'] = 9
calificaciones['historia'] = 10
calificaciones['calculo_integral'] = 9
calificaciones['informatica'] = 7
calificaciones['bases de datos'] = 6
for key in calificaciones: #itera/recorre el diccionario, regresando las llaves
print(key)
for value in calificaciones.values(): #itera/recorre el diccionario, regresando los valores
print(value)
for key, value in calificaciones.items(): #itera/recorre el diccionario, regresando llaves y valores
print('llave: {}, valor {}'.format(key,value))
suma_de_calificaciones = 0
for calificacion in calificaciones.values():
suma_de_calificaciones += calificacion
promedio = suma_de_calificaciones / len(calificaciones.values())
print(promedio)
|
4f7eb63169d534e0ebe31345d386afc3eeff3a95 | I-will-miss-you/CodePython | /Curso em Video/Aula 09 - Manipulando Texto/desafio04.py | 128 | 3.703125 | 4 | #Crie um programa que leia o nome de uma pessoa e diga se ela tem "Silva" no nome
nome = input("Nome: ")
print("Silva" in nome)
|
751b0a9c508710021ebcae59dbc3d6ea64fb840b | oscarDelgadillo/AT05_API_Test_Python_Behave | /AbnerMamani/practice3opetator.py | 1,662 | 4.15625 | 4 | #Practice 3 handling the oopertors.
numberFirst = 123
numberSecond = 321
print("Handling over comparison operators")
resultTheOperation = numberFirst == numberSecond
print(f"{numberFirst} == {numberSecond} is {resultTheOperation}")
resultTheOperation = numberFirst != numberSecond
print(f"{numberFirst} != {numberSecond} is {resultTheOperation}")
resultTheOperation = numberFirst < numberSecond
print(f"{numberFirst} < {numberSecond} is {resultTheOperation}")
resultTheOperation = numberFirst > numberSecond
print(f"{numberFirst} > {numberSecond} is {resultTheOperation}")
resultTheOperation = numberFirst >= numberSecond
print(f"{numberFirst} >= {numberSecond} is {resultTheOperation}")
resultTheOperation = numberFirst <= numberSecond
print(f"{numberFirst} <= {numberSecond} is {resultTheOperation}")
print("Handling over Assignment operators")
number = 10;
number += 10;
print(f"The number is {number} and applying the operator +=10 is {number}")
number -= 1;
print(f"The number is {number} and applying the operator -=1 is {number}")
number *= 10;
print(f"The number is {number} and applying the operator *=10 is {number}")
number /= 10;
print(f"The number is {number} and applying the operator /=10 is {number}")
number %= 10;
print(f"The number is {number} and applying the operator %=10 is {number}")
listOfValues={1,4,6,8,9}
valueOne=4
print("Handling over Membership operators")
if valueOne in listOfValues:
print(f" {valueOne} exists in list")
else:
print(f" {valueOne} does not exists in list")
if valueOne not in listOfValues:
print(f" {valueOne} does not exists in list")
else:
print(f" {valueOne} exists in list") |
5ebc79cfc82b15ea05b24ff8815e25d71153fe60 | ekivoka/PythonExercises | /exceptionClasses.py | 1,463 | 3.515625 | 4 | def isParent(cl, parent):
global CTree
if cl in CTree:
if parent in CTree[cl]:
return True
elif cl == parent:
return True
else:
for node in CTree[cl]:
res = isParent(node, parent)
if res:
return True
return False
CTree = dict()
ListClass = [
'a',
'b : a',
'c : a',
'f : a',
'd : c b',
'g : d f',
'i : g',
'm : i',
'n : i',
'z : i',
'e : m n ',
'y : z',
'x : z',
'w : e y x',
]
ListCheck = [
'y',
'm',
'n',
'm',
'd',
'e',
'g',
'a',
'f',
]
#n = int(input())
n = len(ListClass)
for i in range(n):
#classMas = input().split(' ')
classMas = ListClass[i].split(' ')
className = classMas[0]
parents = classMas[2:]
if className not in CTree:
CTree[className] = []
CTree[className]+=parents
#n = int(input())
n = len(ListCheck)
classMas = []
bads = []
for i in range(n):
#classMas.append(input())
classMas.append(ListCheck[i])
classMas = classMas[::-1]
answer = []
for i in range(n):
for j in range(i+1,n):
#print('i',classMas[i])
#print('j',classMas[j])
if isParent(classMas[i], classMas[j]):
if classMas[i] not in bads:
answer.append(classMas[i])
bads.append(classMas[i])
for key in answer[::-1]:
print(key)
|
ff4f07ca6476ef721aae4c16e51eace5f754c6f6 | johnconnor77/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 249 | 3.734375 | 4 | #!/usr/bin/python3
import json
def load_from_json_file(filename):
"""creates an Object from a JSON file
Args:
filename: file that is read from
"""
with open(filename, mode="r") as a_file:
return (json.load(a_file))
|
9045c57cb58e3a92aba57d1cf9893e4b633c1296 | uhlerlab/server_tutorial | /conv_net.py | 6,102 | 3.5 | 4 | import torch.nn as nn
import torch
from copy import deepcopy
import torch.nn.functional as F
# Abstraction for using nonlinearities
class Nonlinearity(torch.nn.Module):
def __init__(self):
super(Nonlinearity, self).__init__()
def forward(self, x):
#return F.selu(x)
#return F.relu(x)
#return F.leaky_relu(x)
#return x + torch.sin(10*x)/5
#return x + torch.sin(x)
#return x + torch.sin(x) / 2
#return x + torch.sin(4*x) / 2
return torch.cos(x) - x
#return x * F.sigmoid(x)
#return torch.exp(x)#x**2
#return x - .1*torch.sin(5*x)
# Sample U-Net
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
size = 64
k = 2
b = False
self.first = nn.Conv2d(3, size, 3, stride=1, padding=1, bias=b)
self.downsample = nn.Sequential(nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=k,
bias=b),
Nonlinearity())
self.upsample = nn.Sequential(nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=True),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Upsample(scale_factor=2,
mode='bilinear',
align_corners=True),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Conv2d(size, size, 3,
padding=1, stride=1,
bias=b),
Nonlinearity(),
nn.Conv2d(size, 3, 3,
padding=1, stride=1,
bias=b))
def forward(self, x):
o = self.first(x)
o = self.downsample(o)
o = self.upsample(o)
return o
|
a404d6b995c28ef324421ab5e28a5daf6a83c963 | usman353/python-analytics | /Week2 python basics-2/ex.py | 575 | 3.53125 | 4 | # a, b = 0, 1
# for i in range(1, 10):
# print(a)
# a, b = b, a + b
# x = [1, [1, ['a', 'b']]]
# print(x)
# def search_list(list_of_tuples, value):
# for comb in list_of_tuples:
# for x in comb:
# if x == value:
# print(x)
# return comb
# else:
# return 0
# prices = [('AAPL', 96.43), ('IONS', 39.28), ('GS', 159.53)]
# ticker = 'GS'
# print(search_list(prices, ticker))
import datetime
date = '01-Apr-03'
date_object = datetime.datetime.strptime(date, '%d-%b-%y')
print((date_object).date())
|
243a1b6defbb4f1dcd28e8dabdade072d4111f9f | PavlovAlx/repoGeekBrains | /dz01.py | 281 | 4.03125 | 4 | string1 = input("введите строчку 1 >>>")
string2 = input("введите строчку 2 >>>")
string3 = input("введите строчку 3 >>>")
print("строчка 1:", string1)
print("строчка 2:", string2)
print("строчка 3:", string3)
|
6f36d2b63778598d2d69026e4353342d64656499 | swatantragoswami09/Amazon_SDE_Test_Series_solutions | /Closet 0s 1s and 2s.py | 670 | 3.578125 | 4 |
''' Your task to is sort the array a of 0s,1s and 2s
of size n. You dont need to return anything.'''
def segragate012(a,n):
a.sort()
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__=='__main__':
t = int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
segragate012(a,n)
print(*a)
# } Driver Code Ends
|
f0a194716026c09eec83b46fb7985605e864bf1b | a19camoan/Ejercicios_Programacion_Python | /EstructurasRepetitivasPython/4.py | 899 | 4.125 | 4 | """
Escribir un programa que imprima todos los números pares entre dos números que se le pidan al usuario.
Autor: Andrés Castillero Moriana.
Fecha: 03/11/2020
Algoritmo:
Pedimos los 2 números al usuario.
Recorremos el rango entre ambos número (incluido el último).
Si es divisible entre 2, se imprimirá por pantalla.
Variables:
num1: (int)
num2: (int)
"""
print("Programa que imprime todos los números pares entre dos números.")
num1 = int(input("Introduzca el primer número: "))
num2 = int(input("Introduzca el segundo número: "))
# Intercambiamos valores en caso de que num1 sea mayor que num2.
if num1 > num2:
num1, num2 = num2, num1
for i in range(num1, num2+1):
if i%2 == 0:
# Modificando el end del print hacemos que los números esten en una línea separados por un punto y un espacio.
print(i, end=". ")
|
78e7b9dabacb78ab149fd68cf088895f8d30e07d | JKChang2015/Python | /w3resource/List_/Q030.py | 179 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
# Q030
# Created by JKChang
# Thu, 31/08/2017, 16:35
# Tag:
# Description: 30. Write a Python program to get the frequency of the elements in a list.
|
0944dbe92a69283c9c0136ee431509ac0f8273b0 | jvalansi/word2code | /word2code/res/translations/PairingPawns.py | 1,754 | 3.8125 | 4 | from problem_utils import *
class PairingPawns:
def savedPawnCount(self, start):
input_array = start
# "Pairing pawns" is a game played on a strip of paper, divided into N cells.
# The cells are labeled 0 through N-1.
# Each cell may contain an arbitrary number of pawns.
# You are given a int[] start with N elements.
# For each i, element i of start is the initial number of pawns on cell i.
# The goal of the game is to bring as many pawns as possible to cell 0.
# The only valid move looks as follows: Find a pair of pawns that share the same cell X (other than cell 0).
# Remove the pair of pawns from cell X.
# Add a single new pawn into the cell X-1.
# You may make as many moves as you wish, in any order.
# Return the maximum number of pawns that can be in cell 0 at the end of the game.
pass
def example0():
cls = PairingPawns()
input0 = [0,2]
returns = 1
result = cls.savedPawnCount(input0)
return result == returns
def example1():
cls = PairingPawns()
input0 = [10,3]
returns = 11
result = cls.savedPawnCount(input0)
return result == returns
def example2():
cls = PairingPawns()
input0 = [0,0,0,8]
returns = 1
result = cls.savedPawnCount(input0)
return result == returns
def example3():
cls = PairingPawns()
input0 = [0,1,1,2]
returns = 1
result = cls.savedPawnCount(input0)
return result == returns
def example4():
cls = PairingPawns()
input0 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,123456]
returns = 0
result = cls.savedPawnCount(input0)
return result == returns
def example5():
cls = PairingPawns()
input0 = [1000,2000,3000,4000,5000,6000,7000,8000]
returns = 3921
result = cls.savedPawnCount(input0)
return result == returns
if __name__ == '__main__':
print(example0())
|
d3560ee12c4dc9bba45c2ccaa2363e0c9705c8ce | bigrob21/LearningPython | /AutomateTheBoringStuff/chapter4/listSlicing1.py | 545 | 3.8125 | 4 | aList2 = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
startIndex1 = 10
print('Showing you the list - ' + str(aList2))
print('Showing the list via slicing from the 5th element to the end of it --> ' + str(aList2[startIndex1:len(aList2)]))
print('First element in the list is = ' + str(aList2[0]) + ' .Now changing it to 1000')
aList2[0] = 1000
print('Now the first element is == ' + str(aList2[0]))
print('Now removing the first element in the List')
del aList2[0]
print('Now printing the first element of the list => ' + str(aList2[0]))
|
7c108d5b644775efef244b70b81add9c9fa4f9fa | alexmiguez/Proyecto-Final.def-Alexandre-Dominguez- | /aplicacion.py | 15,310 | 3.6875 | 4 | import numbers
import math
import sys
from tools import ver_otro_barco,lee_numero,rango,numero_valido,lee_entrada,abrir_datos,abrir_json,guardar_datos,agregar_datos,verificar_archivo,esPrimo,esAbundante
class Aplicacion():
def barco(self,db):
#'Mostrar los barcos disponibles en base de datos""
len_db=len(db)
print(':::::::::')
print('\nCruceros Disponibles\n')
for i in range(len_db):
print(i+1,'.',db[i]['name'])
opcion=numero_valido(len_db)
return(opcion)
def destino(self,db):
#'Mostrar los destinos disponibles en base de datos.Devuelve un destino'
len_db=len(db)
destinos=[]
print(':::::::::')
print('\nDestinos Disponibles\n')
for i in range(len_db):
destino=db[i]['route']
for j in range(len(destino)):
destinos.append(destino[j])
destinos=list(set(destinos))
for i in range(len(destinos)):
print(i+1,'.',destinos[i])
print('Seleccione un Destino:\n')
opcion=lee_numero()
salida=destinos[opcion-1] #la salida es el destino escogido
return(salida)
def destino_en_barco(self, db, destino):
#'Muestra los barcos que pasan por un destino dado'
busqueda=[]
for i in range(len(db)):
if destino in db[i]['route']:
busqueda.append(db[i]['name'])
return(busqueda)
def info_barco(self, opcion,db):
#'Mostrar la informacion de los barcos'
print('\nBarco ',db[opcion-1]['name']) #disponibles en base de datos
print('\nRuta: \n')
for i in range(len(db[opcion-1]['route'])):
print('--->',db[opcion-1]['route'][i])
print('\nFecha de Salida: ', db[opcion-1]['departure'] )
print('\nPrecio de Boletos: ', db[opcion-1]['cost'] )
print('\nCapacidad de Habitaciones: ', db[opcion-1]['capacity'] )
print('\nPiso,Pasillo: ', db[opcion-1]['rooms'])
salida=ver_otro_barco()
return(salida)
def tipo_habitacion(self):
#'Devuelve el tio de habitacion seleccionado'
print("Seleccione el tipo de Habitacion:\n"
'1.Simple\n'
'2.Premium\n'
'3.VIP\n')
tipo=numero_valido(3) #mod2=5 #loop para solictar numero correcto de las opciones
if tipo==1:
return('simple')
elif tipo==2:
return('premium')
else:
return('vip')
def elegir_habitacion(self, opcion, db):
#'Muestra las habitaciones disponibles en un barco'
tipos=db[opcion-1]['rooms'] #accede al diccionario 'rooms' del barco seleccionado
tipo=Aplicacion.tipo_habitacion(self) #Solicita el tipo de habitacion que se mostrará
capacidad=Aplicacion.capacidad_habitacion(self,db,opcion, tipo)
id_habitaciones=Aplicacion.id_habitacion(self,tipos, tipo) #Solicta los id del tipo de habitacion seleccionado
print('\nBarco ',db[opcion-1]['name'])
print('Habitaciones de clase: ', tipo)
print('Capacidad de: ',capacidad,' personas')
print(Aplicacion.servicio_hab(tipo))
print('ID de habitaciones:\n', id_habitaciones)
salida=ver_otro_barco()
return(salida)
def capacidad_habitacion(self, db,opcion, tipo): #mustra la capacidad de personas en una habitacion
capac=db[opcion-1]['capacity'][tipo]
return(capac)
def servicio_hab(tipo):
#'Muestra los servicios disponibles para cada tipo de habitacion'
if tipo=='simple':
return('Con Servicio de habitacion')
elif tipo=='premium':
return('Con Servicio de habitacion y vista al mar')
elif tipo=='vip':
return('Con Servicio de habitacion, vista al mar, espacio para fiestas privadas')
def id_habitacion(self,tipos, tipo):
#'Crea ID para las habitaciones, dado el tipo (simple, premium o vip)'
pasillos=tipos[tipo][0] #numero de pasillos del buque y tipo de habitacion seleccionado
pasillos_id=['A','B','C','D','E','F','G'] #id de pasillos permitidos
pasillo=pasillos_id[0:pasillos] #id de pasillos del buque y tipo de habitacion seleccionado
habitaciones=tipos[tipo][1] ##numero de habitaciones del buque y tipo de habitacion seleccionado
if tipo=='simple':
id_t='S'
elif tipo=='premium':
id_t='P'
elif tipo=='vip':
id_t='V'
habitacion=[]
for j in pasillo:
for i in range(habitaciones):
habitacion.append(id_t+j+str(i+1))
return(habitacion)
def selec_habitacion(self, hab, num_personas, capacidad, dato_json, barco):
#'devuelve el numero de habitaciones a ocupar'
a=isinstance(dato_json, numbers.Integral) #verifica que el archivo json es nuevo (contiene integer)
if a is True:
len_dato=1
else:
len_dato=len(dato_json)
hab_ocup=[]
for i in range(len_dato):
if a is True:
continue
elif barco in dato_json[i]["barco"]:
for j in range(len(dato_json[i]["Habitaciones"][1])):
data2=dato_json[i]["Habitaciones"][1][j]
hab_ocup.append(data2)
hab_disp=[]
for i in range(len(hab)):
if hab[i] in hab_ocup:
continue
else:
hab_disp.append(hab[i])
num_hab_disp=len(hab_disp)
a=num_personas/capacidad #segun el numero de personas
num_hab=math.ceil(a) #tambien devuelve el id de las habitaciones
if num_hab>num_hab_disp:
print('Numero de Habitaciones Insuficientes\n'
'Seleccione otro tipo de habitación, '
'o número menor de pasajeros')
print('Habitaciones Disponibles: ', num_hab_disp,
'\nNúmero máximo de personas: ', num_hab_disp*capacidad)
main()
else:
id_hab=hab_disp[0:num_hab]
return(num_hab, id_hab)
def formulario(self, num_personas):
#'funcion para llenar un formulario con los datos de cada pasajero'
personas=[]
for i in range(num_personas):
nombre=input('Nombre: ')
print('Documento de identidad')
doc=lee_numero()
print('Edad: ')
edad=lee_numero()
print('Discapacidad?')
disc=lee_entrada()
doc_primo=esPrimo(doc)
doc_abun=esAbundante(doc)
upgrade=0
descuento=0
if doc_primo is True:
descuento=descuento+0.1
if doc_abun is True:
descuento=descuento+0.15
if edad>64:
upgrade=1
if disc=='SI':
descuento=descuento+0.3
personas.append({'Nombre':nombre,'ID':doc,'Edad':edad,'Discapacidad':disc,'Upgrade':upgrade, 'Descuento':descuento})
return(personas)
def registro_id(self, opcion_barco, num_personas, asig_habitaciones):
id_client=str(opcion_barco)+str(num_personas)+str(asig_habitaciones[1][0])
return(id_client)
def costos(self, datos, barco, tipo_hab, asig_habitaciones, personas):
#'funcion para calcular el costo total del viaje'
costo_hab=datos[barco-1]['cost'][tipo_hab]
num_hab=asig_habitaciones[0]
monto_total=costo_hab*num_hab
desc=[]
for i in range(len(personas)):
descuentos=personas[i]['Descuento']
desc.append(descuentos)
desc=sum(desc)
impuesto=monto_total*0.16
monto_desc=monto_total-monto_total*desc
total=monto_desc+impuesto
costo={'Monto_Total': monto_total, 'Monto_Con_Descuento':monto_desc, 'Impuesto':impuesto,'Total':total}
return(costo)
def cliente_a_bordo(self):
print('¿El pasajero se encuentr a bordo?')
abordo=lee_entrada()
return(abordo)
def buscar(self):
print('Desea buscar habitacion por:\n'
'1. Tipo\n2.Capacidad\n3.Id de Habitación',
'\n4.Volver')
opcion=numero_valido(4)
jsonfile='datos.json' # Archivo de almacenamiento de datos
datos_vacio=None
verificar_archivo(jsonfile,datos_vacio) #verificar la existencia del archivo json, o creacion de uno
dato_json=abrir_datos(jsonfile)
if opcion==1:
encontrado=Aplicacion.buscar_tipo(self,dato_json)
return(encontrado)
elif opcion==2:
encontrado=Aplicacion.buscar_capacidad(self,dato_json)
return(encontrado)
elif opcion==3:
encontrado=Aplicacion.buscar_id(self,dato_json)
return(encontrado)
def buscar_tipo(self,dato_json):
tipo=Aplicacion.tipo_habitacion(self)
encontrados=[]
for i in range(len(dato_json)):
if tipo==dato_json[i]["Tipo Hab"]:
encontrados.append(dato_json[i])
return(encontrados)
def buscar_capacidad(self,dato_json):
a=lee_numero()
encontrados=[]
for i in range(len(dato_json)):
if a==dato_json[i]["Capacidad Hab"]:
encontrados.append(dato_json[i])
return(encontrados)
def buscar_id(self,dato_json): #Buscar habitacion por ID
print('\nEscriba el id de la habitacion: ')
a=input().upper()
encontrados=[]
for i in range(len(dato_json)):
if a in dato_json[i]["Habitaciones"][1]:
encontrados.append(dato_json[i])
else:
pass
if encontrados==[]:
print('No encontrado')
encontrados=0
return(encontrados)
def borrar_registro(self, registro,jsonfile):
datos=abrir_json(jsonfile)
for i in range(len(datos)):
if registro==datos[i]["Boleto_id"]:
del datos[i]
break
print('....\n',datos)
return(datos)
def formulario_tour(self):
print('Ingrese datos de pasajero')
nombre=input('Nombre: ')
print('Documento de identidad')
doc=lee_numero()
print('Número de Personas: ')
num_per=lee_numero()
formulario={'Nombre':nombre,'ID':doc,'Numero de Personas':num_per}
return(formulario)
def tour(self, num_per, Num_tour):
a='Tour en el Puerto'
b='Degustacion de comida local'
c='Trotar por el pueblo/ciudad'
d='Visita a lugares Históricos'
Num_cli_a=[0]
Num_cli_b=[0]
Num_cli_c=[0]
Num_cli_d=[0]
data=isinstance(Num_tour, numbers.Integral)
if data is True:
pass
else:
for i in range(len(Num_tour)):
if Num_tour[i][0]==a:
num_cli_a=Num_tour[i][1]
Num_cli_a.append(num_cli_a)
elif Num_tour[i][0]==b:
num_cli_b=Num_tour[i][1]
Num_cli_b.append(num_cli_b)
elif Num_tour[i][0]==c:
num_cli_c=Num_tour[i][1]
Num_cli_c.append(num_cli_c)
elif Num_tour[i][0]==d:
num_cli_d=Num_tour[i][1]
Num_cli_d.append(num_cli_d)
Num_cli_a=sum(Num_cli_a)
Num_cli_b=sum(Num_cli_b)
Num_cli_c=sum(Num_cli_c)
Num_cli_d=sum(Num_cli_d)
print('Seleecione El Tour\n'
' 1.Tour en el Puerto (Vendidos ',Num_cli_a,'/10)\n',
'2.Degustacion de comida local (Vendidos',Num_cli_b,'/100)\n',
'3.Trotar por el pueblo/ciudad(sin cupo maximo)\n',
'4.Visita a lugares Históricos (Vendidos',Num_cli_c,'/15)\n',
'5.Volver al menu principal')
opcion=numero_valido(5)
if opcion==1:
tour='Tour en el Puerto'
precio=30
hora='7 A.M.'
max_per=4
cupo_total=10
disponible=(cupo_total-Num_cli_a)
if num_per>max_per:
print('Máximo 4 Personas')
print('\nCupos Disponibles:',disponible)
#modulo.modulo_3(self)
if num_per>disponible:
print('Sin cupos sufientes')
print('\nCupos Disponibles:',disponible,
'\nPersonas Maximas:', max_per)
#modulo.modulo_3(self)
desc=0
if num_per==3:
desc=0.1
if num_per==4:
desc=0.2
total=(num_per*precio)-((num_per-2)*precio*desc)
elif opcion==2:
max_per=2
tour='Degustacion de comida local'
precio=100
hora='12 P.M'
cupo_total=100
disponible=cupo_total-Num_cli_b
if num_per>max_per:
print('Máximo 2 Personas')
print('\nCupos Disponibles:',disponible)
modulo.modulo_3(self)
if num_per>disponible:
print('Sin cupos sufientes')
print('\nCupos Disponibles:',disponible,
'\nPersonas Maximas:', max_per)
modulo.modulo_3(self)
total=num_per*precio
elif opcion==3:
tour='Trotar por el pueblo/ciudad'
precio=0
max_per=None
hora='6 A.M.'
cupo_total=None
total=0
elif opcion==4:
tour='Visita a lugares Históricos'
precio=40
max_per=4
hora='10 A.M.'
cupo_total=15
disponible=cupo_total-Num_cli_d
if num_per>max_per:
print('Máximo 4 Personas')
print('\nCupos Disponibles:',disponible)
#modulo.modulo_3(self)
if num_per>disponible:
print('Sin cupos sufientes')
print('\nCupos Disponibles:',disponible,
'\nPersonas Maximas:', max_per)
#modulo.modulo_3(self)
desc=0
if num_per>2:
desc=0.1
total=(num_per*precio)-(precio*desc)
elif opcion==5:
print(".....")
return 0
datos_tour={'Tour':tour,'Precio':precio,'MaxPersona':max_per,'Hora':hora,'Cupo Total':cupo_total, 'Total':total}
return(datos_tour)
|
6056c85f2f2d41593aebd74a616965f462450e3e | faris-shi/python_practice | /remote_duplicate.py | 736 | 4.03125 | 4 | """
Removing Duplicates from a Sequence while Maintaining Order
"""
import collections
#to check if the item is hashable
def _is_hashable(item):
return isinstance(item, collections.abc.Hashable)
def dedupe(seq, key=None):
seen = set()
for item in seq:
is_hashable = _is_hashable(item)
if not is_hashable and not key:
raise ValueError(f'{item} is unhashable, need provide key parameter')
val = item if key is None or is_hashable else key(item)
if val not in seen:
seen.add(val)
yield item
print(list(dedupe([1,2,4,5,2,1])))
#[2, 3] will be removed since its key is 2.
print(list(dedupe([1, 2, 1, [2, 3], [4, 5], 1, 2, 3], key=lambda x: x[0]))) |
1f667c1192e34bbe77c5c19a9b6824c0f6dac66a | Kashishkd77/Arbitrary_Arguments | /maximum.py | 352 | 3.875 | 4 | # finding maximum no. among n passed numbers in a funtion i.e. usig keyword arguments
def maximum(*n):
large=0
for i in n:
if large==0:
large=i
else:
if large < i:
large = i
print("The maximum among all the numbers is :",large)
maximum(1222,89,3,578,0,278,7,88,3,1,11111,11) |
bcdfe89fdba7ef330d911e54379cd9dcf874f14a | Zeroska/Vulkan0x1 | /ThingCouldSaveMe/KhuongOption.py | 475 | 3.578125 | 4 | #!/usr/bin/python3.7
import socket, sys
#create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind socket to the port
server_address = {'localhost', 10000}
print (sys.stder + "starting on port" + str(server_address))
sock.bind(server_address)
#listening for incoming connection
sock.listen(1)
while(True):
#wait for a connection
print("Wating for a connection")
clientAddress = sock.accept()
print("Something complicated")
|
d28ec23b5f4f816936bba8cff9a4ba33735baf62 | AsthaGarg16/North-Spine-Food-Canteen | /DataBase.py | 5,315 | 3.609375 | 4 | from func import toDict
class DataBase():
# Contructor of the class
def __init__(self):
self.day = "Monday"
self.stallName = ""
self.chickenRiceDetail = toDict("chickenRice.txt")
self.chickenRiceDetail_AM = toDict("chickenRiceAM.txt")
self.japaneseStallDetail = toDict("japanese.txt")
self.japaneseStallDetail_AM = {"Closed": "Japanese Stall is closed in the morning"}
self.koreanStallDetail = toDict("korean.txt")
self.koreanStallDetail_AM = toDict("koreanAM.txt")
self.miniWokStallDetail = {"Closed": "Miniwok Stall is closed in the morning"}
self.miniWokStallDetail_AM = toDict("miniWokAM.txt")
self.malayStallDetail = toDict("malay.txt")
self.malayStallDetail_AM = toDict("malayAM.txt")
'''
self.stallList = {"Chicken Rice Stall": self.chickenRiceDetail[self.day],
"Japanese Stall": self.japaneseStallDetail[self.day],
"Korean Stall" : self.koreanStallDetail[self.day]}
'''
# print(self.stallList["Chicken Rice Stall"])
def getMenu(self, stall_Name, day, mor_aft_nig):
if (mor_aft_nig == 'BreakFast'): # BreakFast Menu
self.stallList = {"Chicken Rice Stall": self.chickenRiceDetail_AM[day],
"Japanese Stall": self.japaneseStallDetail_AM["Closed"],
"Korean Stall": self.koreanStallDetail_AM[day],
"Miniwok Stall": self.miniWokStallDetail_AM[day],
"Malay Stall":self.malayStallDetail_AM[day]}
elif (mor_aft_nig == "Lunch\Dinner"): # Lunch/Dinner menu
self.stallList = {"Chicken Rice Stall": self.chickenRiceDetail[day],
"Japanese Stall": self.japaneseStallDetail[day],
"Korean Stall": self.koreanStallDetail[day],
"Miniwok Stall": self.miniWokStallDetail["Closed"],
"Malay Stall": self.malayStallDetail[day]}
else: # shop are close after hours
self.stallList = {
"Chicken Rice Stall": "There is no Menu. \nTo view Chicken Rice Stall Operating hours. \nClick on Display Operating Hours Button.",
"Japanese Stall": "There is no Menu. \nTo view Japanese Stall Operating hours. \nClick on Display Operating Hours Button.",
"Korean Stall": "There is no Menu. \nTo view Korean Stall Operating hours. \nClick on Display Operating Hours Button.",
"Miniwok Stall": "There is no Menu. \nTo view Miniwok Stall Operating hours. \nClick on Display Operating Hours Button.",
"Malay Stall": "There is no Menu. \nTo view Malay Stall Operating hours. \nClick on Display Operating Hours Button."}
return self.stallList[stall_Name]
def getOperating_Hours(self, stall_Name):
operating_Hour = []
op_hour_Display = ""
if (stall_Name == "Chicken Rice Stall"):
self.chickStall_OpHour = ["Weekday BreakFast: 0500Hrs - 1159Hrs",
"Weekday Lunch/Dinner: 1200Hrs - 1959Hrs",
"Weekday After 2000Hrs: Close", "Weekend: Close"]
operating_Hour = self.chickStall_OpHour
elif (stall_Name == "Japanese Stall"):
self.japStall_OpHour = ["Weekday BreakFast: Close", "Weekday Lunch/Dinner: 1200Hrs - 1959Hrs",
"Weekday After 2000Hrs: Close", "Weekend: Close"]
operating_Hour = self.japStall_OpHour
elif (stall_Name == "Miniwok Stall"):
self.miniWokStall_OpHour = ["Weekday BreakFast: 0500Hrs - 1159Hrs", "Weekday Lunch/Dinner: Close",
"Weekday After 2000Hrs: Close", "Weekend: Close"]
operating_Hour = self.miniWokStall_OpHour
elif (stall_Name == "Malay Stall"):
self.malayStall_OpHour = ["Weekday BreakFast: 0500Hrs - 1159Hrs",
"Weekday Lunch/Dinner: 1200Hrs - 1959Hrs",
"Weekday After 2000Hrs: Close", "Weekend: Close"]
operating_Hour = self.malayStall_OpHour
else:
self.koreanStall_OpHour = ["Weekday BreakFast: 0500Hrs - 1159Hrs",
"Weekday Lunch/Dinner: 1200Hrs - 1959Hrs",
"Weekday After 2000Hrs: Close", "Weekend: Close"]
operating_Hour = self.koreanStall_OpHour
for i in operating_Hour:
if (i != operating_Hour[-1]):
op_hour_Display = op_hour_Display + i + "\n\n"
else:
op_hour_Display = op_hour_Display + i
return op_hour_Display
def setDay(self, inputDay):
self.day = inputDay
def getDay(self):
return self.day
def setStallName(self, inputStallName):
self.stallName = inputStallName
def getStallName(self):
return self.stallName
db = DataBase()
|
09d817fef0651bcabcd61699e52451fbc10c5304 | AmruthaRajendran/Python-Programs | /Encryption.py | 844 | 3.875 | 4 | # HackerRank Problem
''' Question:(https://www.hackerrank.com/challenges/encryption/problem)
Sample Input 0
haveaniceday
Sample Output 0
hae and via ecy
Explanation 0
L=12,sqrt(L) is between 3 and 4.
Rewritten with 3 rows and 4 columns:
have
anic
eday
Sample Input 1
feedthedog
Sample Output 1
fto ehg ee dd
Explanation 1
L=10,sqrt(l) is between 3 and 4.
Rewritten with 3 rows and 4 columns:
feed
thed
og '''
# Program Code:
import math
def encryption(s):
r=math.floor(math.sqrt(len(s)))
c=math.ceil(math.sqrt(len(s)))
lst = ''
for i in range(c):
temp = ''
for j in range(0,len(s),c):
if(i+j>=len(s)):
break
temp += s[i+j]
lst += temp + ' '
return(lst)
if __name__ == '__main__':
s = input()
result = encryption(s)
print(result)
|
129e7f85935fdae3c5b961284f9d49f89692e918 | pker98/HappyWheels | /Models/Customer.py | 592 | 3.53125 | 4 | from Person import Person
class Customer(Person):
def __init__(self, name, phone, email, creditcard):
Person.__init__(self, name, phone, email)
self.creditcard = creditcard
def __str__(self):
return "{},{},{},{}".format(self.name, self.phone, self.email, self.creditcard)
def __repr__(self):
return self.__str__()
def get_name(self):
return self.name
def get_phone(self):
return self.phone
def get_email(self):
return self.email
def get_creditcard(self):
return self.creditcard |
e24cdcdbf712e8e9a2806ae57822ad48423eb34e | Pewww/python-learning-repo | /statement/for.py | 1,000 | 3.625 | 4 | arr = [1, 2, 3]
for i in arr:
print(i)
arr2 = [(1, 2), (3, 4), (5, 6)]
for (first, second) in arr2:
print(f'{first} - {second}')
scores = [90, 25, 67, 45, 80]
PASS_SCORE_CRITERIA = 60
for score in scores:
print('합격') if score >= PASS_SCORE_CRITERIA else print('불합격')
for score in scores:
if (score >= PASS_SCORE_CRITERIA):
print('합격')
else:
continue
for i in range(1, 10): # 1 이상 10 미만, 처음 생략 시 0부터 시작
print(i)
total = 0
for i in range(1, 11):
total += i
print(f'총 점수: {total}')
for idx in range(len(scores)):
score = scores[idx]
print(f'점수: {score}')
for i in range(2, 10):
for j in range(1, 10):
print(f'{i} x {j} = {i * j}'
#, end = ' '
)
print('\n')
a = [1, 2, 3, 4]
result = [num * 3 for num in a] # 좀 기괴하구만..
# [표현식 for 항목 in 반복가능객체 if 조건문]
print(result)
gugu = [x * y for x in range(2, 10)
for y in range(1, 10)]
print(gugu)
|
1c3b2bea6d633905f775fc4a95d251c5180dd7b1 | hqb324/hqb-guoya-1 | /text2.py | 1,761 | 3.609375 | 4 | # sc = 99
# if (sc>=0 and sc<60):
# print("不及格")
# if (sc>=60 and sc<=70):
# print("及格")
# if (sc>70 and sc<=80):
# print("良好")
# if (sc>80 and sc<=100):
# print("优秀")
#
# sc = 19
# if (sc >= 0 and sc<60):
# print("不及格")
# elif (sc >= 60 and sc<=70):
# print("及格")
# elif (sc >= 71 and sc<=80):
# print("良好")
# else:
# print("优秀")
#
# sc = 77
# if (sc<0):
# print("请输入正确的成绩")
# elif (sc>=0 and sc<60):
# print("不及格")
# elif (sc>=60 and sc<=70):
# print("及格")
# elif (sc>70 and sc<=80):
# print("良好")
# elif (sc>80 and sc<=100):
# print("优秀")
# else:
# print("请输入正确的成绩")
#
# sc_1 = [10,20,30,40,50,60,70,80,90,100]
# for sc in sc_1:
# if (sc < 0):
# print("请输入正确的成绩")
# elif (sc >= 0 and sc < 60):
# print("不及格")
# elif (sc >= 60 and sc <= 70):
# print("及格")
# elif (sc > 70 and sc <= 80):
# print("良好")
# elif (sc > 80 and sc <= 100):
# print("优秀")
# else:
# print("请输入正确的成绩")
#
# s = 1
# for i in range(10,0,-1):
# s *= i
# print(s)
#
# s = 0
# for i in range(100,0,-1):
# s += i
# print(s)
# flag = True
# a = 77
# while flag :
# b = int(input("请输入数字"))
# if b > a :
# print("大了")
# elif b < a :
# print("小了")
# else:
# print("对了")
# flag = False
flag = True
a = 867
while flag:
b=int(input("请输入数字"))
if b>a:
print("大了")
elif b<a:
print("小了")
else:
print("对了")
flag = False
a = "小明,小红,小张"
print(a.split(",")) |
3273cfd1423066680053fd181e20357fd0e7d27e | dyyura/OOP | /oop2.py | 3,737 | 3.734375 | 4 | # 2
# class Airplane:
# def __init__(self,make,model,year,max_speed,odometer,is_flying,take_off,fly,land):
# self.make = make
# self.model = model
# self.year = year
# self.max_speed = max_speed
# self.odometer = odometer
# self.is_flying = is_flying
# self.take_off = take_off
# self.fly = fly
# self.land = land
# def povedenie(self):
# print(self.make , self.model, self.year, self.max_speed, self.odometer,self.is_flying,self.take_off, self.fly, self.land)
# a = Airplane('tu 155','jet','2015','2020km/h','24 bar','False','взлёт','летать','приземлятся')
# a.povedenie()
# 7
# Steve = Student("Steven Schultz", 23, "English")
# Johnny = Student("Jonathan Rosenberg", 24, "Biology")
# Penny = Student("Penelope Meramveliotakis", 21, "Physics")
# print(Steve)
# <name: Steven Schultz, age: 23, major: English>
#
# print(Johnny)
# <name: Jonathan Rosenberg, age: 24, major: Biology>
# class Student:
# def __init__(self,name,lastname,age,objects):
# self.name = name
# self.lastname = lastname
# self.age = age
# self.objects = objects
# def disp(self):
# print(self.name, self.lastname, self.age, self.objects)
# Steve = Student("Steven",'Shultz' , 23, "English")
# Johny = Student("Jonathan","Rosenberg", 24 , "Biology")
# Penny = Student("Penelope","Meramveliotakis", 21 , "Physics")
# Steve.disp()
# Johny.disp()
# Penny.disp()
# class House:
# def __init__(self,typehouse,areahouse):
# self.typehouse = typehouse
# self.areahouse = areahouse
# def get_house(self):
# self.totalarea = 0
# self.furnitures = {
# 'bad ' : 4,
# 'gardirob' : 2,
# 'table': 1.5
# }
# for value in self.furnitures.values():
# self.totalarea += value
# print('type of house',self.typehouse,' main area:',self.areahouse,'\n',self.furnitures.keys(),'\n','last area',self.areahouse - self.totalarea)
# c = House('apartment',80)
# b.get_house()
# class Car:
# def call(self):
# print('Автомобиль заведен')
# class Calls:
# def call(self):
# print('Автомобиль заглушен')
# class Date:
# def call(self):
# print('2003')
# class Type:
# def call(self):
# print('Универсал')
# class Color:
# def call(self):
# print('Серый')
# car1 = Car()
# car2 = Calls()
# car3 = Date()
# car4 = Type()
# car5 = Color()
# a = [car1,car2,car3,car4,car5]
# for i in a:
# i.call()
class MoneyFmt:
def __init__(self, value = 0.0):
self.value = float(value)
def update(self, value = None):
self.value = value
def str(self):
if self.value >= 0:
return '${:,.2f}'.format(self.value)
else:
return '-${:,.2f}'.format(-self.value)
def repr(self):
print(self.value)
return f'{self.value}'
cash = MoneyFmt()
class MoneyFmt:
def init(self, value = 0.0):
self.value = float(value)
def update(self, value = None):
self.value = value
def str(self):
if self.value >= 0:
return '${:,.2f}'.format(self.value)
else:
return '-${:,.2f}'.format(-self.value)
def repr(self):
print(self.value)
return f'{self.value}'
cash = MoneyFmt()
from AlphaMoney import MoneyFmt
def dollarize():
cash = MoneyFmt(12345678.021)
repr(cash)
print(cash)
cash.update(100000.4567)
repr(cash)
print(cash)
cash.update(-0.3)
repr(cash)
print(cash)
a1 = eval(input('Введите число и я переведу его в доллоровое значение: '))
cash.update(a1)
print(cash)
a2 = input("Если хотите повторить процедуру введите '1' , для выхода введите Enter: ")
while a2 == '1':
a3 = eval(input('Введите число: \n'))
cash.update(a3)
print(cash)
dollarize() |
ba0ffce4b11ecdba2ea620a0a6f2961a1fa57e10 | magdeevd/gb-python | /homework_1/second.py | 254 | 3.6875 | 4 | def main():
seconds = int(input("Enter time in seconds: "))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds))
if __name__ == '__main__':
main()
|
aaeefe9da6f1f6e9a202d9637ffd040253ca637b | garderobin/Leetcode | /leetcode_python2/lc360_sort_transformed_array.py | 8,940 | 3.625 | 4 | from abc import ABCMeta, abstractmethod
from collections import deque
class SortTransformedArray:
__metaclass__ = ABCMeta
@abstractmethod
def sort_transformed_array(self, nums, a, b, c):
"""
:type nums: List[int]
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
class SortTransformedArrayImplFromBorder(SortTransformedArray):
"""
Starts from the left/right border.
If a < 0, two borders compete for current smallest.
If a > 0, two borders compete for current largest.
"""
def sort_transformed_array(self, nums, a, b, c):
nums = [x * x * a + x * b + c for x in nums]
ret = [0] * len(nums)
p1, p2 = 0, len(nums) - 1
i, d = (p1, 1) if a < 0 else (p2, -1)
while p1 <= p2:
if nums[p1] * -d > nums[p2] * -d:
ret[i] = nums[p1]
p1 += 1
else:
ret[i] = nums[p2]
p2 -= 1
i += d
return ret
class SortTransformedArrayImplFromExtreme(SortTransformedArray):
def sort_transformed_array(self, nums, a, b, c):
"""
Starts from extreme point to both direction's border.
ax^2 + bx + c = a(x + b/(2a))^2 - b*b/(4a)
If a < 0, two pointers compete for current largest.
If a > 0, two pointers compete for current smallest.
Performance is not that good. Perhaps due to desc?
"""
def transform(i):
return a * i * i + b * i + c
if a == 0:
return [b * x + c for x in (nums if b >= 0 else nums[::-1])]
else:
extreme_point = (-float(b)) / (2 * a)
if extreme_point >= nums[-1]:
return [transform(x) for x in nums[::-1]]
elif extreme_point <= nums[0]:
return [transform(x) for x in nums]
else:
n, insert, res = len(nums), self.get_insert_index(nums, 0, len(nums) - 1, extreme_point), []
transform_queues_desc = [
[transform(nums[i]) for i in (xrange(insert) if a > 0 else xrange(insert-1, -1, -1))],
[transform(nums[i]) for i in (xrange(n-1, insert-1, -1) if a > 0 else xrange(insert, n))]]
print transform_queues_desc
while transform_queues_desc[0] and transform_queues_desc[1]:
index_of_queue_with_smallest_element = transform_queues_desc[1][-1] < transform_queues_desc[0][-1]
res.append(transform_queues_desc[index_of_queue_with_smallest_element].pop())
for q in transform_queues_desc:
while q:
res.append(q.pop())
return res
def sort_transformed_array_using_list(self, nums, a, b, c):
"""
Performance is not that good. Perhaps due to desc?
"""
def transform(i):
return a * i * i + b * i + c
if a == 0:
return [b * x + c for x in (nums if b >= 0 else nums[::-1])]
else:
extreme_point = (-float(b)) / (2 * a)
if extreme_point >= nums[-1]:
return [transform(x) for x in nums[::-1]]
elif extreme_point <= nums[0]:
return [transform(x) for x in nums]
else:
n, insert, res = len(nums), self.get_insert_index(nums, 0, len(nums) - 1, extreme_point), []
print insert, nums[(insert-1):-1:-1]
transform_queues_desc = [
[transform(nums[i]) for i in (xrange(insert) if a > 0 else xrange(insert-1, -1, -1))],
[transform(nums[i]) for i in (xrange(n-1, insert-1, -1) if a > 0 else xrange(insert, n))]]
print transform_queues_desc
while transform_queues_desc[0] and transform_queues_desc[1]:
index_of_queue_with_smallest_element = transform_queues_desc[1][-1] < transform_queues_desc[0][-1]
res.append(transform_queues_desc[index_of_queue_with_smallest_element].pop())
for q in transform_queues_desc:
while q:
res.append(q.pop())
return res
def sort_transformed_array_deque(self, nums, a, b, c):
def quadratic_transform(i):
return a * i * i + b * i + c
if a == 0:
return [b * x + c for x in (nums if b >= 0 else nums[::-1])]
else:
extreme_point = (-float(b)) / (2 * a)
if extreme_point >= nums[-1]:
return [quadratic_transform(x) for x in nums[::-1]]
elif extreme_point <= nums[0]:
return [quadratic_transform(x) for x in nums]
else:
insert_index, res = self.get_insert_index(nums, 0, len(nums) - 1, extreme_point), []
transform_queue_left = deque([quadratic_transform(x) for x in nums[:insert_index]])
transform_queue_right = deque([quadratic_transform(x) for x in nums[insert_index:]])
while transform_queue_left and transform_queue_right:
left, right = transform_queue_left[-1], transform_queue_right[0]
if (a < 0) ^ (left < right):
res.append(left)
transform_queue_left.pop()
else:
res.append(right)
transform_queue_right.popleft()
while transform_queue_left:
res.append(transform_queue_left.pop())
while transform_queue_right:
res.append(transform_queue_right.popleft())
return res[::-1] if a < 0 else res
def sort_transformed_array_not_clean(self, nums, a, b, c):
def quadratic_transform(i):
return a * i * i + b * i + c
if a == 0:
return [b * x + c for x in (nums if b >= 0 else nums[::-1])]
else:
extreme_point = (-float(b)) / (2 * a)
if extreme_point >= nums[-1]:
return [quadratic_transform(x) for x in nums[::-1]]
elif extreme_point <= nums[0]:
return [quadratic_transform(x) for x in nums]
else:
insert_index, res = self.get_insert_index(nums, 0, len(nums) - 1, extreme_point), []
left, right = insert_index - 1, insert_index
if nums[insert_index] == extreme_point:
res.append(quadratic_transform(nums[insert_index]))
right += 1
transform_left, transform_right = quadratic_transform(nums[left]), quadratic_transform(nums[right])
while True:
if (a < 0) ^ (transform_left < transform_right):
res.append(transform_left)
left -= 1
if left < 0:
break
else:
transform_left = quadratic_transform(nums[left])
else:
res.append(transform_right)
right += 1
if right >= len(nums):
break
else:
transform_right = quadratic_transform(nums[right])
for index in xrange(left, -1, -1):
res.append(quadratic_transform(nums[index]))
for index in xrange(right, len(nums)):
res.append(quadratic_transform(nums[index]))
return res if a > 0 else res[::-1]
def get_insert_index(self, nums, start, end, value):
if start > end:
return -1
elif start == end:
return start if value < nums[start] else end + 1
else:
mid = start + (end - start) // 2
if value == nums[mid]:
return mid
elif value < nums[mid]:
return self.get_insert_index(nums, start, mid, value)
else:
return self.get_insert_index(nums, mid + 1, end, value)
if __name__ == "__main__":
sol = SortTransformedArrayImplFromExtreme()
# nums = [-99,-94,-90,-88,-84,-83,-79,-68,-58,-52,-52,-50,-47,-45,-35,-29,-5,-1,9,12,13,25,27,33,36,38,40,46,47,49,57,57,61,63,73,75,79,97,98]
# a, b, c = -2, 44, -56
# nums = [-98,-97,-96,-93,-90,-89,-89,-88,-85,-83,-83,-79,-78,-78,-76,-74,-63,-63,-63,-62,-59,-59,-57,-55,-54,-53,-49,-45,-41,-37,-35,-31,-25,-22,-20,-20,-17,-16,-16,-15,-13,-12,-12,-11,-4,-1,0,5,6,7,8,9,13,16,16,29,29,29,31,31,32,32,33,33,34,35,36,39,41,42,43,45,47,49,53,56,59,59,65,66,68,68,70,75,78,80,80,81,82,84,85,85,89,90,90,92,99,99]
# a, b, c = -8, -16, 69
nums = [-4, -2, 2, 4]
a, b, c = -1, 3, 5
print sol.sort_transformed_array(nums, a, b, c)
|
880440dca29d2d0c79c25bdf4aac8da0c261f185 | joshdavham/Starting-Out-with-Python-Unofficial-Solutions | /Chapter 5/Q4.py | 370 | 4.15625 | 4 | #Question 4
def main():
speed = int(input("What is the speed of the veihicle in mp? "))
time = int(input("How many hours has it traveled? "))
print("Hour\tDistance Traveled", \
"\n----------------------------")
for hour in range(1, time+1):
distance = hour * speed
print(hour, "\t", distance)
main()
|
4bc662ae96c71553dd251383d3bea3c17ce4a70e | rafaelperazzo/programacao-web | /moodledata/vpl_data/3/usersdata/123/634/submittedfiles/ex1.py | 256 | 4.03125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a= input('Insira um valor para a:')
b= input('Insira um valor para b:')
c= input('Insira um valor para c:')
if a>b and a>c:
print (a)
if b>a and b>c:
print (b)
if c>a and c>b:
print (c) |
c9b077b1741569dc044e12e1b5fc78fd9a20e0b0 | whiterosess/PythonStudy | /script.py | 4,232 | 4.3125 | 4 | # Print 'Hello World'
print('Hello World')
# Print 7 as an integer
print(7)
# Print the sum of 9 and 3
print(9 + 3)
# Print '9 + 3' as a string
print('9 + 3')
# Print the result of 9 / 2
print(9 / 2)
# Print the result of 7 * 5
print(7 * 5)
# Print the remainder of 5 divided by 2 using %
print(5 % 2)
# Assign 'Bob' to the name variable
name = 'Bob'
# Print the value of the name variable
print(name)
print('Bob')
# Assign 7 to the number variable
number = 7
# Print the value of the number variable
print(number)
print(7)
apple_price = 2
apple_count = 8
# Assign the result of apple_price * apple_count to the total_price variable
total_price = apple_price * apple_count
# Print the value of the total_price variable
print(total_price)
money = 20
print(money)
# Add 50 to the money variable
money += 50
# Print the value of the money variable
print(money)
money = 20
print(money)
# Add 50 to the money variable
money += 50
# Print the value of the money variable
print(money)
age = 24
# Print 'I am 24 years old' using the age variable
print('I am ' + str(age) + ' years old')
count = '5'
# Convert the count variable to an integer data type, add 1 to it, and print it
print(int(count) + 1)
x = 7 * 10
y = 5 * 6
# if x equals 70, print 'x is 70'
if x == 70:
print('x is 70')
# if y does not equal 40, print 'y is not 40'
if y != 40:
print('y is not 40')
x = 10
# if x is greater than 30, print 'x is greater than 30'
if x > 30:
print('x is greater than 30')
money = 5
apple_price = 2
# if money is equal to or greater than apple_price, print 'You can buy an apple'
if money >= apple_price:
print('You can buy an apple')
x = 10
# if x is greater than 30, print 'x is greater than 30'
if x > 30:
print('x is greater than 30')
money = 5
apple_price = 2
# if money is equal to or greater than apple_price, print 'You can buy an apple'
if money >= apple_price:
print('You can buy an apple')
money = 2
apple_price = 2
if money > apple_price:
print('You can buy an apple')
# When the two variables have the same value, print 'You can buy an apple but your wallet is now empty'
elif money == apple_price:
print('You can buy an apple but your wallet is now empty')
else:
print('You do not have enough money')
x = 20
# if x ranges from 10 to 30 inclusive, print 'x ranges from 10 to 30'
if 10 <= x and x <= 30:
print('x ranges from 10 to 30')
y = 60
# if y is less than 10 or greater than 30, print 'y is less than 10 or greater than 30'
if y < 10 or 30 < y:
print('y is less than 10 or greater than 30')
z = 55
# if z is not equal to 77, print 'z is not 77'
if not z == 77:
print('z is not 77')
# Assign 2 to apple_price variable
apple_price = 2
# Assign 5 to count variable
count = 5
# Assign the result of apple_price * count to total_price variable
total_price = apple_price * count
# By using the count variable, print 'You will buy .. apples'
print('You will buy ' + str(count) + ' apples')
# By using the total_price variable, print 'Your total is .. dollars'
print('The total price is ' + str(total_price) + ' dollars')
apple_price = 2
# Receive the number of apples by using input(), and assign it to the input_count variable
input_count = input('How many apples do you want?: ')
# Convert the input_count variable to an integer, and assign it to the count variable
count = int(input_count)
total_price = apple_price * count
print('You will buy ' + str(count) + ' apples')
print('The total price is ' + str(total_price) + ' dollars')
apple_price = 2
# Assign 10 to the money variable
money = 10
input_count = input('How many apples do you want?: ')
count = int(input_count)
total_price = apple_price * count
print('You will buy ' + str(count) + ' apples')
print('The total price is ' + str(total_price) + ' dollars')
# Add control flow based on the comparison of money and total_price
if money > total_price:
print('You have bought ' + str(count) + ' apples')
print('You have ' + str(money - total_price) + ' dollars left')
elif money == total_price:
print('You have bought ' + str(count) + ' apples')
print('Your wallet is now empty')
else:
print('You do not have enough money')
print('You cannot buy that many apples')
|
7901425945dbdde8c1b698ebb5369364bd2ae4e9 | AdamShechter9/adventofcode2016 | /day1/day1.py | 3,954 | 4.09375 | 4 | # Adam Shechter
# Solving for adventofcode challenge, day1 part 1
# Using input1.txt as data
# my solution uses an array of hash tables representing coordinates.
# this array gets scanned for previous coordinate to match current coordinate.
# if not, then traveled coordinate is added.
# an alternate solution is to create a multidimensional grid (matrix)
# and initialize with 0's. set to 1 when traveled to coordinate.
# run a check to find first double-visited coordinate.
import sys
DIRECTIONS = ['N', 'E', 'S', 'W']
class day1solution(object):
def __init__(self):
self.direction = 0
self.coordinate = {'x': 0, 'y': 0}
def move(self, inp1):
newDirect = inp1[0:1]
newSteps = int(inp1[1:])
#print(newDirect+" "+str(newSteps))
if newDirect == 'R':
if (self.direction + 1) > 3:
self.direction = 0
else:
self.direction+=1
elif newDirect == 'L':
if (self.direction - 1) < 0:
self.direction = 3
else:
self.direction-=1
else:
raise "Error: incorrect input"
if self.direction == 0:
# N
self.coordinate['y']+=newSteps
elif self.direction == 1:
# E
self.coordinate['x']+=newSteps
elif self.direction == 2:
# S
self.coordinate['y']-=newSteps
elif self.direction == 3:
# W
self.coordinate['x']-=newSteps
return self.coordinate
class day2solution(object):
def __init__(self):
self.direction = 0
self.coordinate = {'x': 0, 'y': 0}
self.map = [{'x': 0, 'y': 0}]
def move(self, inp1):
def scanMap(self, coord1):
# list search
foundCoord = False
for coord1 in self.map:
#print("testing coord "+str(coord1)+" against self location "+str(self.coordinate))
if coord1['x'] == self.coordinate['x'] and coord1['y'] == self.coordinate['y']:
foundCoord = True
return foundCoord
newDirect = inp1[0:1]
newSteps = int(inp1[1:])
#print(newDirect+" "+str(newSteps))
#Set direction
if newDirect == 'R':
if (self.direction + 1) > 3:
self.direction = 0
else:
self.direction+=1
elif newDirect == 'L':
if (self.direction - 1) < 0:
self.direction = 3
else:
self.direction-=1
else:
raise "Error: incorrect input"
#move coordinate and populate map
if self.direction == 0:
# N
for step in range(newSteps):
self.coordinate['y']+=1
currCoord = {'x':self.coordinate['x'], 'y':self.coordinate['y']}
found = scanMap(self, currCoord)
if not found:
self.map.append(currCoord)
else:
print ("LOCATION FOUND")
return -1
elif self.direction == 1:
# E
for step in range(newSteps):
self.coordinate['x']+=1
currCoord = {'x':self.coordinate['x'], 'y':self.coordinate['y']}
found = scanMap(self, currCoord)
if not found:
self.map.append(currCoord)
else:
print ("LOCATION FOUND")
return -1
elif self.direction == 2:
# S
for step in range(newSteps):
self.coordinate['y']-=1
currCoord = {'x':self.coordinate['x'], 'y':self.coordinate['y']}
found = scanMap(self, currCoord)
if not found:
self.map.append(currCoord)
else:
print ("LOCATION FOUND")
return -1
elif self.direction == 3:
# W
for step in range(newSteps):
self.coordinate['x']-=1
currCoord = {'x':self.coordinate['x'], 'y':self.coordinate['y']}
found = scanMap(self, currCoord)
if not found:
self.map.append(currCoord)
else:
print ("LOCATION FOUND")
return -1
return "complete running. no intersection"
def main():
test1 = "R1, R1, R3, R1, R1, L2"
graph1 = day1solution()
graph2 = day2solution()
with open('input1.txt', 'r') as f:
test2 = f.readline().strip().split(', ')
#currDirections = test1.split(', ')
currDirections = test2
#print(currDirections)
for inst1 in currDirections:
print("Instruction: "+inst1)
#print(graph1.move(inst1))
result = graph2.move(inst1)
if result != -1:
print(result)
else:
print ("FOUND")
break
return graph2.coordinate
print(main())
|
91c94fd9d0f4aeb73d5893b091281e6c1bfaaf50 | slpdavid/Project_Euler | /p040.py | 408 | 3.796875 | 4 | def DigitFinder(num):
digit=1
factor=1
while num>9*factor*digit:
num-=9*factor*digit
digit+=1
factor*=10
target=factor+int((num-1)/digit)
print(str(target)[(num-1)%digit])
return int(str(target)[(num-1)%digit])
result = DigitFinder(1)*DigitFinder(10)*DigitFinder(100)*DigitFinder(1000)*DigitFinder(10000)*DigitFinder(100000)*DigitFinder(1000000)
print(result) |
f16c851ff8d14320d62e12ee623056442eb87260 | leelakrishna16/PythonPracticePrgs | /dict_inversy.py | 317 | 3.859375 | 4 | #! /usr/bin/python3
dict1 = {'book1':'pyton','book2':'java','book3':'shell','book3':'perl','book4':8777}
new_dict = dict(zip(dict1.values(),dict1.keys()))
print(new_dict)
#######2nd#########
dict1 = {'book1':'pyton','book2':'java','book3':'shell','book3':'perl','book4':8777}
print({v: k for k, v in dict1.items()})
|
44d8d9b8c07e0da73e400d44ee8c44e1995cab5c | hyelim-kim1028/lab-python | /LEC06_class/test.py | 656 | 3.90625 | 4 | """
what is overloading
"""
def test():
print('test')
def test(param = 0):
print(
'test param =', param
)
test() #얜 누구를 호출할까?
# 파이썬에서는 이름이 같은 두 함수를 만들 수 없다, 마지막에 온 아이가 전에 온 아이들을 모두 덮어써버린다
# C## 이나 java 와 같은 경우에 같은 이름으로 다른 파라미터를 가진 아이들을 만들 수 있다
# overload 과적하다
#overloading:
# 함수(메소드)의 파라미터가 다른 경우
# 같은 이름으로 여러개의 함수(메소드)를 정의하는 것
# 파이썬은 overloading 을 제공하지 않습니다
|
2740949b392ec2677c2694311e5662e46bb82144 | naremanatrek/Embedded-linux | /Tasks/python/Task 3/task3.py | 761 | 4.1875 | 4 | import math
class shape:
def __init__(self,x):
self.x = x
def area (x):
return x
def perimeter(x):
return x
class circle(shape):
def area (self):
return (math.pi)*x*x
def perimeter(self):
return (math.pi)*2*x
class square(shape):
def area (self):
return x*x
def perimeter (self):
return 4*x
x = input("enter which shape you want to calculate it's area and perimeter ")
if x == "circle":
y = float(input("enter it's raduis "))
circle1 = circle(y)
print("your circle's area is ",circle1.area())
print("your circle's perimeter is ",circle1.perimeter())
if x == "square":
y = float(input("enter it's length"))
square1 = square(y)
print("your square's area is ",square1.area())
print("your square's perimeter is ",square1.perimeter())
|
f55465fadd625e0615a485d247b6f93777220fbe | DiegoMaraujo/100-exerc-cios-em-Python- | /100Exercicios em Python/ex24.py | 82 | 3.59375 | 4 | cid = str(input('Qual cidade voce naceu ? ')).strip()
print(cid[:5] == 'santo')
|
817770e354b12b625f4dee60c8e9ace823f95fd1 | EdgardoCS/PythonNeuro | /Tarea1/ejercicio4.py | 591 | 3.890625 | 4 | #jan ken pon
P1 = input('Jugador1: Jan, Ken, Pon? ')
# if (P1 != 'piedra' or P1 != 'papel' or P1 != 'tijera'):
# print('Solo puedes ingresar: piedra, papel o tijera')
P2 = input('Jugador2: Jan, Ken, Pon? ')
# if (P2 != 'piedra' or P2 != 'papel' or P2 != 'tijera'):
# print('Solo puedes ingresar: piedra, papel o tijera')
draw = 0
if (P1 == P2):
print ('empate')
draw = 1
if (draw != 1):
if (P1 == 'piedra' and P2 == 'tijera' or P1 == 'papel' and P2 == 'piedra' or P1 == 'tijera' and P2 == 'papel'):
print('Gana Jugador1')
else:
print ('Gana Jugador2') |
97aae0d1f134c956bff067e88fe0e421d2bff864 | zhangruochi/leetcode | /play/first/14_Longest_Common_Prefix.py | 1,352 | 3.875 | 4 | #!/usr/bin/env python3
# info
# -name : zhangruochi
# -email : zrc720@gmail.com
"""
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix_1(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
min_length = min([len(_) for _ in strs])
result = ""
for i in range(min_length):
index = 0
for string in strs:
if index == 0:
chr_ = string[i]
index += 1
else:
if chr_ == string[i]:
continue
else:
return result
result += chr_
return result
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
prefix = strs[0]
for i in range(1, len(strs)):
while strs[i].find(prefix) != 0:
prefix = prefix[:-1]
if len(prefix) == 0:
return ""
return prefix
if __name__ == '__main__':
solution = Solution()
print(solution.longestCommonPrefix(["abc", "abcdf", "abrtf", "a"]))
|
973398c6a06f420668262e42ca9188645fe12e31 | hdcsantos/exercicios-python-secao05-41e-v2 | /10.py | 304 | 3.6875 | 4 | print("Peso ideal")
sexo = input('Qual seu genero (H ou M)? ')
h = float(input("Altura: "))
peso = float(input("Peso: "))
if sexo == 'H':
p_i = ((72.7 * h) - 58) // 1
print(f'Seu peso ideal é de {p_i} Kg!')
else:
p_i = ((62.1 * h) - 44.7) // 1
print(f'Seu peso ideal é de {p_i} Kg!')
|
bcb7788af7663d0e9c52057795c5f62acc349ba1 | mennanov/problem-sets | /other/strings/string_all_unique_chars.py | 1,371 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implement an algorithm to determine if a string has all unique characters.
"""
def all_unique_set(string):
"""
Running time and space is O(N).
"""
return len(string) == len(set(string))
def all_unique_list(string):
"""
Running time is O(N), space is O(R) where R is a length of an alphabet.
"""
# assume we have an ASCII string
r = 65535 if isinstance(string, unicode) else 255
if len(string) > r:
return False
chars = [0] * r
for i, char in enumerate(string):
chars[ord(char)] += 1
if chars[ord(char)] > 1:
return False
return True
def all_unique_bit(string):
"""
Running time is O(N), required space is 1 byte only for ASCII string and 2 bytes for a Unicode string.
Space usage is optimized using a bit vector.
"""
# bit vector
chars = 0
for i, char in enumerate(string):
# check if we have already seen this char
if chars & (1 << ord(char)) > 0:
return False
else:
chars |= (1 << ord(char))
return True
if __name__ == '__main__':
s = 'abcdefghatyk'
assert not all_unique_set(s)
assert not all_unique_list(s)
assert not all_unique_bit(s)
s = 'abcdefghtlk'
assert all_unique_set(s)
assert all_unique_list(s)
assert all_unique_bit(s) |
4c13f88ca3f68b9dd3b84895fcf00e69ef8a82dc | Laoudede/Laoudede.github.io | /Python 3/Python_Crash_Course/while_loops.py | 117 | 4 | 4 | guess = 0
answer = 5
while answer != guess:
guess = int(input("Guess: "))
else:
print("You guessed right!")
|
40f5fd524228904f7fdd2c41c2a1f435e129767b | kcarollee/Problem-Solving | /Python/9093.py | 797 | 3.53125 | 4 | class String:
def __init__(self, arr):
self._arr = arr
self._temp1 = []
self._temp2 = []
def flip(self):
L = len(self._temp1)
for i in range(L//2):
self._temp1[i], self._temp1[L-1-i] = self._temp1[L-1-i], self._temp1[i]
def index(self):
M = len(self._arr)
flag = 0
for j in range(M):
if self._arr[j] != ' ' and j != M-1:
self._temp1.append(self._arr[j])
elif self._arr[j] == ' ':
self.flip()
self._temp2 += self._temp1
self._temp2.append(' ')
self._temp1 = []
elif j == M-1:
self._temp1.append(self._arr[j])
self.flip()
self._temp2 += self._temp1
for k in range(len(self._temp2)):
print(self._temp2[k], end ='')
tc = int(input())
for l in range(tc):
array = list(input())
ans = String(array)
ans.index()
print()
|
dcd01ec717ec88da94497dcedbc5c05bf41b937a | StephenMa88/leetcode_solutions | /Add_Two_Nums/solution.py | 3,460 | 3.6875 | 4 | # attempted in 2021
# 76ms, 14.6 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def lnToList(self, listNode, lnlist =[]):
lnlist.append(listNode.val)
if listNode.next is not None:
self.lnToList(listNode.next, lnlist)
return lnlist
def listToLN(self, Nlist, i=0):
lnode = ListNode(Nlist[i])
while i < len(Nlist):
try:
i += 1
nnode = ListNode(Nlist[i])
nnode.next = lnode
lnode = nnode
except IndexError:
return lnode
return lnode
def addMore(self, listn, num):
zeros = []
print(num)
for x in range(num):
zeros.append(0)
result = listn + zeros
return result
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# create listnode to list
list1 = self.lnToList(l1, lnlist =[])
#print(list1)
list2 = self.lnToList(l2, lnlist =[])
#print(list2)
# if one list longer than the other
if len(list1) > len(list2):
list2 = self.addMore(list2, len(list1) - len(list2))
elif len(list2) > len(list1):
list1 = self.addMore(list1, len(list2) - len(list1))
#print(list1)
#print(list2)
total = 0
for x in range(len(list1)):
#print("b {} {} {}, {}".format(total,list1[x], list2[x], 10**x))
total = total + ((list1[x]+list2[x])*(10**x))
#print("a {} {} {}".format(total,list1[x], list2[x]))
flist = []
# Number to list
for y in str(total):
flist.append(int(y))
#print(flist)
result = self.listToLN(flist)
#print(result)
return result
# attempted in 2020
# 88ms, 14 MB
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class SingleLL:
# what the problem gives me is a list node but not a singly linked list. They nodes are not connected.
def __init__(self):
self.head = None
self.tail = None
return
def lltoString(self, llist):
str_val = []
str_re = ""
cur_head = llist
while cur_head is not None:
str_val.append(cur_head.val)
cur_head = cur_head.next
for x in str_val[::-1]:
str_re += str(x)
return str_re
class Solution:
# From SSL -> list --> reverse list --> string --> int
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
n1 = SingleLL()
n2 = SingleLL()
n3 = SingleLL()
s_n1 = n1.lltoString(l1)
s_n2 = n2.lltoString(l2)
#print("{} \n {}".format(s_n1, l2)
s_n3 = int(s_n1) + int(s_n2)
#print(s_n3)
l_n3 = []
for x in str(s_n3):
l_n3.append(int(x))
l3 = ListNode(l_n3[0])
#print(l3)
#print(l_n3)
for x in range(len(l_n3)):
if x != 0:
llist = ListNode(l_n3[x])
llist.next = l3
l3 = llist
return l3
"""
|
4dc289d6a59e7f582d388fc3b54c76e5dd4f4d5a | JohnPDrab/Git-hub-project | /Snakify problems/2. Intergers and float numbers/First digit after desimal.py | 80 | 3.515625 | 4 | num = float(input())
import math
a = (num * 10)
b = math.floor(a % 10)
print(b) |
2bdcf83f4ae7a97cf7874afcb14e65588940238c | Bialomazur/3dProgrammierung | /unittests/Employee.py | 430 | 3.515625 | 4 | class Employee:
def __init__(self, salary, surname, age, salary_increase):
self.salary = salary
self.surname = surname
self.age = age
self.salary_increase = salary_increase
def increase_salary(self):
self.salary *= self.salary_increase
@property
def email(self):
return f"{self.surname}@PythonModul.com"
def __repr__(self):
return self.surname
|
ad3c73f9b5766ec3f076a115fe90e14d55ba2977 | PrestonHicks26/secret-santa | /SecretSanta.py | 2,909 | 4 | 4 | # similar to doubly linked list, meaning has both 'next' and 'previous'
# each node represents a person taking part in exchange
# 'next' is written as 'giving,' the person that node n is giving a present to
# 'previous' is written as 'receiving,' the person that node n is receiving a present from
# code based on implementation of linked list given in
# https://realpython.com/linked-lists-python/#implementing-your-own-linked-list
import random
import os
#legacy class, leaving in case I want to try to implement the program differently
class Node:
def __init__(self, name):
self.name = name
self.giving = None
self.receiving = None
def __repr__(self):
return self.name
class SecretSanta:
# get people involved, create hat list, group list, and dictionary
def __init__(self):
self.hat = []
self.group = []
self.assignments = {}
self.more = True
self.name = ""
while self.more:
print("Enter a name. If you are finished entering names, then enter 'n'")
name = input()
if name == "n":
self.more = False
break
self.hat.append(name)
self.group.append(name)
def __repr__(self):
rep = 'SecretSanta('+str(self.hat)+','+str(self.group)+','+str(self.assignments)+')'
return rep
def pull(self):
copyHat = self.hat.copy()
for person in self.group:
subHat = []
for card in copyHat:
if card != person:
subHat.append(card)
if not subHat:
subHat.append("EMPTY")
choice = random.choice(subHat)
self.assignments[person] = choice
if choice != "EMPTY":
copyHat.remove(choice)
def reportRecipients(self):
for i in range(len(self.group)):
print("{}'s recipient will now be announced:".format(self.group[i]))
input("(Enter anything to continue)")
print()
print("You will be giving a present to {}!".format(self.assignments.get(self.group[i])))
input("(Enter anything to clear screen)")
self.clear()
if i == len(self.group)-1:
break
input("(Enter anything when the next person is ready)")
print()
print("Everyone now has a Secret Santa Partner!")
#note this only works in terminal or cmd, to clear in IDE, just print a ton of newlines
def clear(self):
IDE = True
if not IDE:
#for windows
if os.name == 'nt':
os.system('cls')
#for mac and linux
else:
os.system('clear')
else:
print ("\n"*100)
|
c92676b224bdf60b17b217045b527a46173964dc | luismontei/Atividades-Python | /atv003.py | 223 | 4.0625 | 4 | ##Faça um Programa que peça dois números e imprima a soma.
n1 = float(input('Informe um número: '))
n2 = float(input('Informe outro número: '))
soma= n1+n2
print('A soma dos números foram de {}'.format(soma))
|
d1e01ef176343d1bf992226f4785fb18fd0fd456 | pujkiee/python-programming | /player level/factorial.py | 116 | 4.09375 | 4 | num=int(input("enter the number")
n=1
while num<=20:
n=n*num
num=num-1
print ("factorial of the given number is",n)
|
0c375aeb7a50d4cc75897a2fb1f723f8e5f0dce7 | ChocolatePadmanaban/Learning_python | /Day11/part7.py | 705 | 4.09375 | 4 | # converting array to matrix for real
import numpy as np
# Numpy – matrices
# Numpy – matrices
a = np.array([[1,2],[3,4]])
m = np.mat(a) # convert 2-d array to matrix
m = np.matrix([[1, 2], [3, 4]])
print(a[0])
# result is 1-dimensional
print(m[0])
print(a*a)
# element-by-element multiplication
#array([[ 1, 4], [ 9, 16]])
print(m*m)
# (algebraic) matrix multiplication
print(a**3)
# element-wise power
print(m**3)
# matrix multiplication m*m*m
print( m.T)
# transpose of the matrix
print(m.H)
# conjugate transpose (differs from .T for complex matrices)
print(m.I)
# inverse matrix
# matrix([[-2. , 1. ], [ 1.5, -0.5]])
# Array and matrix operations may be quite different!
|
67bf3a860a88d71735afe315ecd2375ba3b1713d | b166erbot/300_ideias_para_programar | /tipo_de_triângulo3.2.9.py | 407 | 3.890625 | 4 | def main():
a, b, c = (float(a) for a in input('digite os lados: ').split())
if all((a + b >= c, b + c >= a, c + a >= b)):
if a == b == c:
print('equilátero')
elif a == b or b == c or c == a:
print('isóceles')
elif a != b != c:
print('escaleno')
else:
print('não forma um triangulo')
if __name__ == '__main__':
main()
|
11fdc96b4665ab80fcb0c8b21f03cdfa87b60aec | PallGudbrandsson/Skoli-2016V | /Forritun_3R/Tverk_1/Hluti_1.py | 93 | 3.53125 | 4 | x = "10010"
lengd = len(x)
if x[lengd-1] == "1":
print "oddatala"
else:
print "slett tala" |
a7799531035f9c67d11b84b314b781e9ccbdc4f7 | Hemant024/basic-python-programs | /reverse list 5 ways.py | 828 | 4.21875 | 4 | # REVERSE LIST
# case 1
#
# list1 = [1,2,3,4,5,6]
# list1.reverse() #using reverse method
# print(list1)
# case 2
#
# list1 = [1,2,3,4,5,6,7]
# y = list1[ ::-1] # using slicing
# print(y)
# case 3
# def Reverse1(list1):
# return [ele for ele in reversed(list1)] # using reversed bulid in funtion
# print(Reverse1([1,2,3,4,5,6,7,8]))
# case 4
# list1 = [1,2,3,4,5,6,7,8,9]
# y = list(reversed(list1)) # using reversed bulid in funtion
# print(y)
# case 5
# list1 = [1,2,3,4,5,6,7,8,9,10] # using for loop and .insert() method
# y = []
# for i in range(len(list1)):
# y.insert(0,list1[i])
#
# print(y)
|
d10fd0958740e1a5ad1e70c472141812e7e09a6f | kamkali/Kurs-Python | /week06_day02/zad2.py | 1,645 | 3.640625 | 4 | from typing import Dict
import pandas as pd
def read_file(file):
with open(file, 'r') as f:
text = f.read()
return text
def save_data(data: Dict[str, int], filename):
list_data = list(data)
list_data.sort()
with open(filename, 'w') as f:
for key in list_data:
line = key + ':' + str(data[key]) + '\n'
f.write(line)
def create_hist(data):
hist_dict = {}
for letter in data:
letter = letter.lower().strip()
if letter in hist_dict.keys():
hist_dict[letter] += 1
elif letter.isalnum():
hist_dict[letter] = 1
return hist_dict
def change(text, filename_to_save):
data = create_hist(text)
print(data)
count_list = [{'letter': key, 'count': value} for key, value in data.items()]
count_list.sort(key=lambda c: c['count'], reverse=True)
most_sig_char1 = count_list[0]['letter']
most_sig_char2 = count_list[1]['letter']
text_list = list(text)
for i in range(len(text)):
if text_list[i] == most_sig_char1:
text_list[i] = most_sig_char2
elif text_list[i] == most_sig_char2:
text_list[i] = most_sig_char1
text = ''.join(text_list)
with open(filename_to_save, 'w') as f:
f.write(text)
def reverse_text(text, filename_to_save):
reversed_text = text[::-1]
with open(filename_to_save, 'w') as f:
f.write(reversed_text)
if __name__ == '__main__':
data = read_file('literki.txt')
result = create_hist(data)
save_data(result, 'hist.txt')
change(data, 'zamiana.txt')
reverse_text(data, 'reverse.txt')
|
512e0de83450b4b34f1f82b163e1076293ac0a4d | santhoshkumar2/Guvi | /natural.py | 70 | 3.71875 | 4 | usr=int(raw_input())
num=0
while (usr>0):
num+=usr
usr-=1
print num
|
8d940e73632d43502c9d8be8af23829a3ef9e44d | AsherThomasBabu/AlgoExpert | /Strings/Valid-IP-Address/solution.py | 1,934 | 4.34375 | 4 | # You're given a string of length 12 or smaller, containing only digits. Write a function that returns all the possible IP addresses that can be
# created by inserting threes in the string. sequence of four positive
# An IP address is a
# 0255
# Inclusive.
# integers that are separated by s, where each individual integer is within the range
# An IP address isn't valid If any of the individual integers contains leading s. For example, "192.168.0.1" is a valid IP address, but "192.168.06.1" and "192.168.0.01" aren't, because they contain "e" and 01 respectively. Another example of a valid IP
# address is 99.1.1.10" conversely, "991.1.1.0" isn't valid, because "991" is greater than 255.
# Your function should return the IP addresses in string format and in no particular order. If no valid IP addresses can be created from the string, your function should return an empty list.
# Note: check out our Systems Design Fundamentals on SystemsExpert to learn more about IP addresses!
# https://leetcode.com/problems/restore-ip-addresses/discuss/31211/Adding-a-python-solution-also-requesting-for-improvement
# The Input is always fixed, so no matter what number of nested loops, it will always run in constant time :)
def validIPAddresses(string):
IPAddressesFound = []
for i in [1, 2, 3]:
for j in [i+1, i+2, i+3]:
for k in [j+1, j+2, j+3]:
if k >= len(string):
continue
s1 = string[:i]
s2 = string[i:j]
s3 = string[j:k]
s4 = string[k:]
tempList = [s1, s2, s3, s4]
if isValidString(tempList):
IPAddressesFound.append(".".join(tempList))
return IPAddressesFound
def isValidString(list):
for i in list:
if i[0] == "0" and i != "0":
return False
if int(i) > 255:
return False
return True
|
ea5315986be53f87d1d9c1aa6f398b19000ccdca | soma2000-lang/web-app | /app.py | 1,864 | 4.1875 | 4 | import pandas as pd
import numpy as np
import streamlit as st
#import the dataset and create a checkbox to shows the data on your website
df1 = pd.read_csv("df_surf.csv")
if st.checkbox('Show Dataframe'):
st.write(df1)
#Read in data again, but by using streamlit's caching aspect. Our whole app re-runs every time we make small changes, which is infeasible the more complicated our code becomes. So this is the recommended way to import the data.
df = st.cache(pd.read_csv)("df_surf.csv")
#create side bars that allow for multiple selections:
age = st.sidebar.multiselect("Select age", df['surfer_age'].unique())
st.write("Age selected", age)
weekly_surfs = st.sidebar.multiselect("Surfer Exercise frequency", df['surfer_exercise_frequency'].unique())
st.write("Frequency selected", weekly_surfs)
surfer_experience = st.sidebar.multiselect("Surfer Experience", df['surfer_experience'].unique())
st.write("Experience selected", surfer_experience)
surfer_gender = st.sidebar.multiselect("Surfer Gender", df['surfer_gender'].unique())
st.write("Gender selected", surfer_gender)
wave_height = st.sidebar.multiselect("Wave height", df['wave_height'].unique())
st.write("Wave height selected", wave_height)
board_type = st.sidebar.multiselect("Board Type", df['board_type'].unique())
st.write("Board type selected", board_type)
#create a sidebar to select the variable output you want to see after making your multiple selections
variables = st.sidebar.multiselect("Select what you want to see for your selection", df.columns)
st.write("You selected these variables", variables)
# return the sub-set data of variables you want to see
selected_data = df[(df['surfer_age'].isin(age))]
subset_data = selected_data[variables]
data_is_check = st.checkbox("Display the data of selected variables")
if data_is_check:
st.write(subset_data) |
1a1817b6bda36a0c0296bfdeb4394a2512b6b177 | priitohlo/prog | /lisa/lisa1.py | 1,515 | 3.640625 | 4 | import turtle
from random import randint
s = turtle.Screen()
t = turtle.Turtle()
idx = 0
with open('lisa/lisa1.txt', 'r', encoding='utf-8') as f:
for r in f:
try:
idx += 1
print(idx)
cmd = r.strip()
if cmd == 'mine_otse':
repeat = int(next(f))
idx += 1
t.fd(15 * repeat)
elif cmd == 'pööra_vasakule':
degrees = int(next(f))
idx += 1
t.lt(degrees)
elif cmd == 'tõsta_pastakas':
t.penup()
elif cmd == 'langeta_pastakas':
t.pendown()
elif cmd == 'joonista_kaar':
radius = int(next(f))
degrees = int(next(f))
idx += 2
t.circle(radius * 15, degrees)
elif cmd == 'joonista_hulknurk':
sides = int(next(f))
length = int(next(f))
idx += 2
if sides == 3:
degrees = 180 / sides
elif sides > 3:
degrees = 360 / sides
t.begin_poly()
for i in range(sides):
t.fd(length)
t.lt(degrees)
t.end_poly()
else:
raise Exception('Tekstifail on vigane. Real ' + str(idx) + ' asub tundmatu käsklus.')
except Exception as e:
print(e)
pass
s.exitonclick() |
9b483c89d5d20eaf377264eb17367e0105c62de3 | zhangcyril/linux_py | /trashcan/input_try.py | 266 | 4.3125 | 4 | #! usr/bin/env python3
# -*- coding: utf-8 -*-
#num = input('input any num: ')
#if int(num)%2:
# print('%s is a odd num' % num)
#else:
# print('%s is a even num' % num)
a,b,c=input('enter 3 nums:')
print('a=%s' % a)
print('b=%s' % b)
print('c=%s' % c)
|
805b6a7a48958962fc34ddcb77a5175894f77a17 | glredig/rosalind_challenges | /answer_compare.py | 960 | 3.671875 | 4 | def compare():
my_filename = raw_input("Your file: ")
other_filename = raw_input("Other file: ")
their_answers = []
my_answers = []
missing = []
extra = []
print "Comparing answers...\n"
with open(other_filename, 'r') as otherOpenFile:
for line in otherOpenFile:
their_answers.append(line)
with open(my_filename, 'r') as myOpenFile:
for line in myOpenFile:
my_answers.append(line)
print "Number of their answers: %s" % (len(their_answers))
print "Number of your answers: %s" % (len(my_answers))
print "-----------------------------------\n"
for i in xrange(len(their_answers)):
if their_answers[i] not in my_answers:
missing.append(their_answers[i])
for j in xrange(len(my_answers)):
if my_answers[j] not in their_answers:
extra.append(my_answers[j])
print "==================================="
print "Missing: "
print missing
print "==================================="
print "Extra: "
print extra
compare()
|
436c2c8ca0d03a1b2fa5c8380dab17d66f4ba469 | AsayehegnMolla/alx-higher_level_programming-1 | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 527 | 3.640625 | 4 | #!/usr/bin/python3
"""main file"""
if __name__ == '__main__':
import sys
import MySQLdb
conn = MySQLdb.connect(
user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3])
cur = conn.cursor()
# HERE I have to know SQL to grab all states in my database
cur.execute(
"""SELECT cities.id, cities.name, states.name
FROM cities
JOIN states
ON states.id = cities.state_id
ORDER BY cities.id ASC""")
for row in cur.fetchall():
print(row)
cur.close()
conn.close()
|
4811d720ca22964372c42ae076a3df9d86bc0e0e | Ichtiostega/PythonLearning | /Scripts/p_wgtConv.py | 328 | 3.890625 | 4 | import myHeaders
myHeaders.printp("Weight Converter")
inWeight = input("Input your weight ")
wValue = int(inWeight.partition(" ")[0])
wType = inWeight.partition(" ")[2]
if wType.find("lbs") != -1:
print(f"{wValue * 0.45} kg")
elif wType.find("kg") != -1:
print(f"{wValue / 0.45} lbs")
else:
print("No such thing") |
e6d35fe1778ac718abac4c2a4d777bae33ea0977 | q654528967/Demo | /python/demo22_keywords.py | 188 | 3.59375 | 4 | #默认值参数
def myFunc(arg1,arg2=6):
print(arg1,arg2)
myFunc(2)
myFunc(5)
myFunc(6)
myFunc(2,5)
#g关键字参数
def keyWord(arg1,arg2):
print(arg1,arg2)
keyWord(arg2=10,arg1=2) |
aeb7215a6fa14bbb4d897d4cba0fa40a0dbc8e2d | griadooss/HowTos | /Python/07_python_dictionaries.py | 17,149 | 4.8125 | 5 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
'''Python dictionaries'''
#
# In this part of the Python programming tutorial, we will cover Python dictionaries in more detail.
#
# Python dictionary is a container of key-value pairs.
# It is mutable and can contain mixed types.
# A dictionary is an unordered collection.
# Python dictionaries are called associative arrays or hash tables in other languages.
# The keys in a dictionary must be immutable objects like strings or numbers.
# They must also be unique within a dictionary.
#
'''Creating dictionaries'''
#
# First, we will show how to create Python dictionaries.
#
#
# #!/usr/bin/python
#
# weekend = { "Sun": "Sunday", "Mon": "Monday" }
# vals = dict(one=1, two=2)
#
# capitals = {}
# capitals["svk"] = "Bratislava"
# capitals["deu"] = "Berlin"
# capitals["dnk"] = "Copenhagen"
#
# d = { i: object() for i in range(4) }
#
# print weekend
# print vals
# print capitals
# print d
#
#
# In the example, we create four dictionaries.
# In four different ways.
# Later we print the contents of these dictionaries to the console.
#
# weekend = { "Sun": "Sunday", "Mon": "Monday" }
#
# We create a weekend dictionary using dictionary literal notation. The key-value pairs are enclosed by curly brackets. The pairs are separated by commas. The first value of a pair is a key, which is followed by a colon character and a value. The "Sun" string is a key and the "Sunday" string is a value.
#
# vals = dict(one=1, two=2)
#
# Dictionaries can be created using the dict() function.
#
# capitals = {}
# capitals["svk"] = "Bratislava"
# capitals["deu"] = "Berlin"
# capitals["dnk"] = "Copenhagen"
#
# This is the third way.
# An empty capitals dictionary is created.
# Three pairs are added to the dictionary.
# The keys are inside the square brackets, the values are located on the right side of the assignment.
#
# d = { i: object() for i in range(4) }
#
# A dictionary is created using a dictionary comprehension.
# The comprehension has two parts.
# The first part is the i: object() expression, which is executed for each cycle of a loop.
# The second part is the for i in range(4) loop.
# The dictionary comprehension creates a dictionary having four pairs,
# where the keys are numbers 0, 1, 2, and 3 and the values are simple objects.
#
# $ ./create_dict.py
# {'Sun': 'Sunday', 'Mon': 'Monday'}
# {'two': 2, 'one': 1}
# {'svk': 'Bratislava', 'dnk': 'Copenhagen', 'deu': 'Berlin'}
# {0: <object object at 0xb76cb4a8>, 1: <object object at 0xb76cb4b0>,
# 2: <object object at 0xb76cb4b8>, 3: <object object at 0xb76cb4c0>}
'''Basic operations'''
#
# The following examples will show some basic operations with Python dictionaries.
#
#
# #!/usr/bin/python
#
# basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }
#
# basket['bananas'] = 5
#
# print basket
# print "There are %d various items in the basket" % len(basket)
#
# print basket['apples']
# basket['apples'] = 8
# print basket['apples']
#
# print basket.get('oranges', 'undefined')
# print basket.get('cherries', 'undefined')
#
#
# We have a basket with different fruits.
# We perform some operations on the basket dictionary.
#
# basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }
#
# The basket dictionary is created. It has initially three key-value pairs.
#
# basket['bananas'] = 5
#
# A new pair is created.
# The 'bananas' string is a key, the 5 integer is the value.
#
# print "There are %d various items in the basket" % len(basket)
#
# The len() function gives the number of pairs in the dictionary.
#
# print basket['apples']
#
# The value of the 'apples' key is printed to the terminal.
#
# basket['apples'] = 8
#
# The value of the 'apples' key is modified.
# It is set to number 8.
#
# print basket.get('oranges', 'undefined')
#
# The get() method retrieves the value of a specified key.
# If there is no such a key, the second parameter of the method is returned.
#
# print basket.get('cherries', 'undefined')
#
# This line returns 'undefined'. There are no cherries in the basket.
#
# $ ./basics.py
# {'bananas': 5, 'pears': 5, 'oranges': 12, 'apples': 4}
# There are 4 various items in the basket
# 4
# 8
# 12
# undefined
#
# Example output.
#
# The next example will present two dictionary methods: the fromkeys() and the setdefault() method.
#
#
# #!/usr/bin/python
#
# basket = ('oranges', 'pears', 'apples', 'bananas')
#
# fruits = {}.fromkeys(basket, 0)
# print fruits
#
# fruits['oranges'] = 12
# fruits['pears'] = 8
# fruits['apples'] = 4
#
# print fruits.setdefault('oranges', 11)
# print fruits.setdefault('kiwis', 11)
#
# print fruits
#
#
# The fromkeys() method creates a new dictionary from a list.
# The setdefault() method returns a value if a key is present.
# Otherwise it inserts a key with a specified default value and returns the value.
#
# basket = ('oranges', 'pears', 'apples', 'bananas')
#
# We have a list of strings. From this list a new dictionary will be constructed.
#
# fruits = {}.fromkeys(basket, 0)
#
# The fromkeys() method creates a new dictionary, where the list items will be the keys. Each key will be initiated to 0. Note that the fromkeys() method is a class method and needs the class name, which is {} in our case, to be called.
#
# fruits['oranges'] = 12
# fruits['pears'] = 8
# fruits['apples'] = 4
#
# Here we add some values to the fruits dictionary.
#
# print fruits.setdefault('oranges', 11)
# print fruits.setdefault('kiwis', 11)
#
# The first line prints 12 to the terminal. The 'oranges' key exists in the dictionary. In such a case, the method returns the its value. In the second case, the key does not exist yet. A new pair 'kiwis': 11 is inserted to the dictionary. And value 11 is printed to the console.
#
# $ ./fruits.py
# {'bananas': 0, 'pears': 0, 'oranges': 0, 'apples': 0}
# 12
# 11
# {'kiwis': 11, 'bananas': 0, 'pears': 8, 'oranges': 12, 'apples': 4}
#
# We receive this output, when we launch the fruits.py script.
#
# The next code example will show, how to add two Python dictionaries.
#
#
# #!/usr/bin/python
#
# domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary"}
# domains2 = { "us": "United States", "no": "Norway" }
#
# domains.update(domains2)
#
# print domains
#
#
# We have two dictionaries.
# They are joined with the update() method.
#
# domains.update(domains2)
#
# The domains2 dictionary is added to the domains dictionary with the update() method.
#
# $ ./domains.py
# {'sk': 'Slovakia', 'de': 'Germany', 'no': 'Norway',
# 'us': 'United States', 'hu': 'Hungary'}
#
# The result shows all values from both dictionaries.
#
# Now we will show, how to remove a pair from a dictionary.
#
#
# #!/usr/bin/python
#
# items = { "coins": 7, "pens": 3, "cups": 2,
# "bags": 1, "bottles": 4, "books": 5 }
#
# print items
#
# items.pop("coins")
# print items
#
# del items["bottles"]
# print items
#
# items.clear()
# print items
#
#
# The items dictionary has 6 key-value pairs.
# We will delete pairs from this dictionary.
#
# items.pop("coins")
#
# The pop() method removes a pair with a specified key.
#
# del items["bottles"]
#
# The del keyword deletes a "bottles": 4 pair from the items dictionary.
#
# items.clear()
#
# The clear() method clears all items from the dictionary.
#
# $ ./removing.py
# {'bags': 1, 'pens': 3, 'coins': 7, 'books': 5, 'bottles': 4, 'cups': 2}
# {'bags': 1, 'pens': 3, 'books': 5, 'bottles': 4, 'cups': 2}
# {'bags': 1, 'pens': 3, 'books': 5, 'cups': 2}
# {}
#
# This is the example output.
'''Keys and values'''
#
# A Python dictionary consists of key-value pairs.
# The keys() method returns a list of keys from a dictionary.
# The values() method creates a list of values.
# And the items() method returns a list of key-value tuples.
#
#
# #!/usr/bin/python
#
# domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
# "us": "United States", "no": "Norway" }
#
# print domains.keys()
# print domains.values()
# print domains.items()
#
# print "de" in domains
# print "cz" in domains
#
#
# We demonstrate the above mentioned methods.
# We also check if a key is present with the in keyword.
#
# print domains.keys()
#
# We print the list of keys of a domains dictionary with the keys() method.
#
# print domains.values()
#
# We print the list of values of a domains dictionary with the values() method.
#
# print domains.items()
#
# And finally, we print the list of key-value tuples of a domains dictionary using the items() method.
#
# print "de" in domains
# print "cz" in domains
#
# With the in keyword, we check if the "de", "cz" keys are present in the domains dictionary.
# The return value is either True or False.
#
# $ ./keys_values.py
# ['sk', 'de', 'no', 'us', 'hu']
# ['Slovakia', 'Germany', 'Norway', 'United States', 'Hungary']
# [('sk', 'Slovakia'), ('de', 'Germany'), ('no', 'Norway'),
# ('us', 'United States'), ('hu', 'Hungary')]
# True
# False
#
# Output of the example.
'''Looping'''
#
# Looping through the dictionary is a common programming job. This can be done with the for keyword.
#
#
# #!/usr/bin/python
#
# domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
# "us": "United States", "no": "Norway" }
#
# for key in domains:
# print key
#
# for k in domains:
# print domains[k]
#
# for k, v in domains.items():
# print ": ".join((k, v))
#
#
# In the example, we traverse the domains dictionary to print the keys, values and both keys and values of the dictionary.
#
# for key in domains:
# print key
#
# This loop prints all the keys of the dictionary.
#
# for k in domains:
# print domains[k]
#
# The second loop prints all values of the dictionary.
#
# for k, v in domains.items():
# print ": ".join((k, v))
#
# In the final loop, all keys and values are printed.
#
# $ ./looping.py
# sk
# de
# no
# us
# hu
# Slovakia
# Germany
# Norway
# United States
# Hungary
# sk: Slovakia
# de: Germany
# no: Norway
# us: United States
# hu: Hungary
#
# Output of the example.
'''Sorting'''
#
# Python dictionaries are orderless.
# This also implies that they cannot be sorted like a Python list.
# Programmers can create sorted representations of Python dictionaries.
# In this section, we will show several ways to create a sorted output.
#
# Programmers might want to sort the data in a normal or reverse order.
# They could sort the data by keys or by values.
#
#
# #!/usr/bin/python
#
# items = { "coins": 7, "pens": 3, "cups": 2,
# "bags": 1, "bottles": 4, "books": 5 }
#
# kitems = items.keys()
# kitems.sort()
#
# for k in kitems:
# print ": ".join((k, str(items[k])))
#
#
# The first example provides the simplest solution to have the data sorted by the keys.
#
# kitems = items.keys()
# kitems.sort()
#
# A list of keys is obtained from the dictionary. The list is sorted with the sort() method.
#
# for k in kitems:
# print ": ".join((k, str(items[k])))
#
# In the loop we print the sorted keys together with their values from the dictionary.
#
# $ ./simplesort.py
# bags: 1
# books: 5
# bottles: 4
# coins: 7
# cups: 2
# pens: 3
#
# The items dictionary is sorted by its keys.
#
# More efficient sorting can be done with the built-in sorted() function.
#
#
# #!/usr/bin/python
#
# items = { "coins": 7, "pens": 3, "cups": 2,
# "bags": 1, "bottles": 4, "books": 5 }
#
# for key in sorted(items.iterkeys()):
# print "%s: %s" % (key, items[key])
#
# print "####### #######"
#
# for key in sorted(items.iterkeys(), reverse=True):
# print "%s: %s" % (key, items[key])
#
#
# In the example we print sorted data by their keys in ascending and descending order using the sorted() function.
#
# for key in sorted(items.iterkeys()):
# print "%s: %s" % (key, items[key])
#
# In this for loop, we print the pairs sorted in ascending order.
# The iteritems() function returns an iterator over the dictionary’s (key, value) pairs.
#
# for key in sorted(items.iterkeys(), reverse=True):
# print "%s: %s" % (key, items[key])
#
# In the second for loop, the data is sorted in descending order.
# The order type is controlled by the reverse parameter.
#
# $ ./sorting.py
# bags: 1
# books: 5
# bottles: 4
# coins: 7
# cups: 2
# pens: 3
# ####### #######
# pens: 3
# cups: 2
# coins: 7
# bottles: 4
# books: 5
# bags: 1
#
# Output of the sorting.py script.
#
# In the next example, we are going to sort the items by their values.
#
#
# #!/usr/bin/python
#
# items = { "coins": 7, "pens": 3, "cups": 2,
# "bags": 1, "bottles": 4, "books": 5 }
#
# for key, value in sorted(items.iteritems(),
# key=lambda (k,v): (v,k)):
#
# print "%s: %s" % (key, value)
#
# print "####### #######"
#
# for key, value in sorted(items.iteritems(),
# key=lambda (k,v): (v,k), reverse=True):
#
# print "%s: %s" % (key, value)
#
#
# The example prints the data in ascending and descending order by their values.
#
# for key, value in sorted(items.iteritems(),
# key=lambda (k,v): (v,k)):
#
# Dictionary pairs are sorted by their values and printed to the console.
# The key parameter takes a function, which indicates, how the data is going to be sorted.
#
# $ ./sorting2.py
# bags: 1
# cups: 2
# pens: 3
# bottles: 4
# books: 5
# coins: 7
# ####### #######
# coins: 7
# books: 5
# bottles: 4
# pens: 3
# cups: 2
# bags: 1
#
# From the output we can see that this time the pairs were sorted according to their values.
#
'''Views'''
#
# Python 2.7 introduced dictionary view objects.
# Views provide a dynamic view on the items of a dictionary.
# They bear similarity to SQL views.
# When the dictionary changes, the view reflects these changes.
# The dict.viewkeys(), dict.viewvalues() and dict.viewitems() methods return view objects.
#
# A view is a virtual read-only container.
# A view does not make a copy of a dictionary.
#
#
# #!/usr/bin/python
#
# fruits = { 'oranges': 12, 'pears': 5, 'apples': 4, 'bananas': 4 }
#
# vi = fruits.viewitems()
# vv = fruits.viewvalues()
# vk = fruits.viewkeys()
#
# for k, v in vi:
# print k, v
#
# for v in vv:
# print v
#
# for k in vk:
# print k
#
#
# Three view objects of the dictionary's items, dictionary's keys and dictionary's values are created.
# We traverse the view with the for loops.
#
# vi = fruits.viewitems()
#
# The viewitems() creates a view of the dictionary's items.
#
# for k, v in vi:
# print k, v
#
# We traverse the created view and print the keys and values in the for loop.
#
# $ ./views.py
# bananas 4
# pears 5
# oranges 12
# apples 4
# 4
# 5
# 12
# 4
# bananas
# pears
# oranges
# apples
#
# Output of the views.py script.
#
# In the next example we show that a view reflects dictionary changes.
#
#
# #!/usr/bin/python
#
# fruits = { 'oranges': 12, 'pears': 5, 'apples': 4, 'bananas': 4}
#
# vi = fruits.viewitems()
#
# for k, v in vi:
# print k, v
#
# fruits.pop('apples')
# fruits.pop('oranges')
#
# print "########### ##########"
#
# for k, v in vi:
# print k, v
#
#
# A view is created on the fruits dictionary.
# Two items are deleted from the dictionary.
# Then we traverse the view to see if the changes are reflected.
#
# vi = fruits.viewitems()
#
# A view is created on the fruits dictionary.
#
# fruits.pop('apples')
# fruits.pop('oranges')
#
# Two items are deleted with the pop() method.
#
# for k, v in vi:
# print k, v
#
# We loop through the view of the fruits.
#
# $ ./views2.py
# bananas 4
# pears 5
# oranges 12
# apples 4
# ########### ##########
# bananas 4
# pears 5
#
# From the output we can see that the changes were reflected in the view.
#
# In this part of the Python tutorial, we have written about Python dictionaries. |
8423292763f235a7f82cf8393fced1450e1ba75b | saranraj-protection-kingdom/python-course | /numeric_range.py | 71 | 3.640625 | 4 | n=int(input())
if (1<n and n<10):
print "Yes"
else:
print "No"
|
196be42f60a3f61cde80d4f4406ec1420a7af3a5 | fjolladuraj/RPAzadace | /zadaca1.py | 3,177 | 3.78125 | 4 | IgracPrvi = input ('Unesi skare,papir,stijena,guster ili spock ')
IgracDrugi = input ('Unesi skare,papir,stijena,gusterili spock ')
if IgracPrvi =='skare' and IgracDrugi =='papir':
print ('Skare režu papir. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'skare':
print ('Skare rezu papir. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'stijena':
print ('Papir prekriva stijenu. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'papir':
print ('Papir prekriva stijenu. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'guster':
print ('Stijena drobi gustera. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'guster' and IgracDrugi == 'stijena':
print ('Stijena drobi guštera. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'stijena':
print ('Papir prekriva stijenu. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'papir':
print ('Papir prekriva stijenu. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'guster' and IgracDrugi == 'spock':
print ('Guster truje Spock. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'spock' and IgracDrugi == 'guster':
print ('Guster truje Spock. \nIgrač drugi je pobjedio!')
elif IgracPrvi =='spock' and IgracDrugi == 'skare':
print ('Spock razbija skare. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'skare' and IgracDrugi == 'spock':
print ('Spock razbija skare. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'skare' and IgracDrugi == 'guster':
print ('Skare obrubljuju guštera. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'guster' and IgracDrugi == 'skare':
print ('Skare obrubljuju guštera. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'guster' and IgracDrugi == 'papir':
print ('Guster jede papir. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'guster':
print ('Guster jede papir. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'spock':
print ('Papir opovrgava Spock. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'spock' and IgracDrugi == 'papir':
print ('Papir opovrgava Spock. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'spock' and IgracDrugi == 'stijena':
print ('Spock isparava stijenu. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'spock':
print ('Spock isparava stijenu. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'skare':
print ('Stijena drobi škare. \nIgrač prvi je pobjedio!')
elif IgracPrvi == 'skare' and IgracDrugi == 'stijena':
print ('Stijena drobi škare. \nIgrač drugi je pobjedio!')
elif IgracPrvi == 'papir' and IgracDrugi == 'papir':
print ('Neriješeno!')
elif IgracPrvi == 'stijena' and IgracDrugi == 'stijena':
print ('Neriješeno!')
elif IgracPrvi == 'guster' and IgracDrugi == 'guster':
print ('Neriješeno!')
elif IgracPrvi == 'skare' and IgracDrugi == 'skare':
print ('Neriješeno!')
elif IgracPrvi == 'spock' and IgracDrugi == 'spock':
print ('Neriješeno!')
else:
print ('Neispravne vrijednosti') |
b2b1ec63bc7a7117bae9e16112a729b71b8af7f4 | LittleSheepy/MyMLStudy | /ml05Python/01修饰器/06消除副作用.py | 605 | 3.53125 | 4 | def foo_no(a, b):
"""foo_no example docstring"""
return a + b
def namedDecorator(name):
def run_time(func):
def wrap(a, b):
'''my decorator'''
print('this is:{}'.format(name))
r = func(a, b)
return r
return wrap
return run_time
@namedDecorator("装饰器带参数")
def foo(a, b):
"""foo example docstring"""
return a + b
print(foo(2, 45))
print(foo.__name__, ",", foo.__doc__)
print(foo_no.__name__, ",", foo_no.__doc__)
"""
this is:装饰器带参数
47
wrap , my decorator
foo_no , foo_no example docstring
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.