blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
88247b905e110b12e3dd60fdc12a79f6882f8e12 | subashreeashok/python_solution | /python_set2/q2_6.py | 382 | 3.734375 | 4 | '''
Name : Subahree
Setno: 2
Question_no:6
Description:first even number
'''
try:
def findAnEven(l):
#to store string as list
list=[]
list=l.split(',')
print(list)
for i in list:
#check even or not
if(int(i)%2==0):
return int(i)
l=raw_input("enter a list of integers")
sol=findAnEven(l)
print(sol)
except Exception as e:
print e
|
0683583d8aee92c016aa014029cd0190d34add4b | dabaopython/python | /1.4.6.py | 443 | 3.59375 | 4 | #break
print('break.....')
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')
#continue
print('continue.....')
for num in range(2,10):
if(num %2 ==0):
continue
print(num)
#pass
def funcname(parameter_list):
pass
class classname(object):
pass
a = 1
if a==0:
pass
else:
pass |
a97b32ffa1769d136239a2843022115a5becb89d | PuemMTH/history | /Trick/get_area.py | 916 | 4.25 | 4 | def Circumference(pi):
radius = float(input("radius : "))
return pi * (radius ** 2)
def Exponent(Number,Ex):
return Number ** Ex
logn = 30
print("██████████████████████████████")
print("█ █")
print("█ Cr.PuemMTH █")
print("█ Circumference : a █")
print("█ Exponent : b █")
print("█ █")
print("██████████████████████████████")
key = str(input("Run function : "))
if key == "a":
pi = 3.14
print("Ans circumference: ",Circumference(pi))
elif key == "b":
Number = float(input("Number : "))
Ex = float(input("Exponent : "))
print("Ans exponent: ",Exponent(Number,Ex))
elif key == "n":
raise SystemExit
else:
raise SystemExit |
9bc4cebca1ef3706a5edf30de390c2a50fd112e4 | girishtulabandu/guvi_tech | /prime.py | 530 | 4.125 | 4 | import sys
from math import ceil, sqrt
def is_prime(n: int) -> bool:
"""Returns True iff n is prime."""
if n == 2:
return True
elif n < 2 or n % 2 == 0:
return False
limit = ceil(sqrt(n))
for factor in range(3, limit + 1, 2):
if n % factor == 0:
return False
return True
if __name__ == '__main__':
try:
num = int(input("Check prime: "))
except ValueError:
print(f"Invalid")
sys.exit(1)
print('Yes' if is_prime(num) else 'No')
|
6facc230296f9316265008bd21a3af149e020dbb | BhagyashreeKarale/dichackathon | /20.py | 621 | 4.3125 | 4 | # Q21.Write a Python program to print all unique values in a dictionary.
# Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
# Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
SampleData = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
vallist=[]
uniqdic={}
for i in SampleData:
for val in i.values():
if val not in vallist:
vallist.append(val)
print(vallist)#list
uniqdic["unique values"]=vallist
print(uniqdic)#dictionary |
9d036f49abcf8535e89699fc726bf060aaacea41 | FelixTheC/practicepython.org | /listOverlap_exercise_5.py | 522 | 3.78125 | 4 | #! /usr/env/python3
from random import randint
list_1 = []
list_2 = []
commonList = []
for i in range(10):
list_1.append(randint(1,99))
for j in range(12):
list_2.append(randint(1,99))
if len(list_1) > len(list_2):
for item in list_1:
if item in list_2 and (item not in commonList):
commonList.append(item)
else:
for item in list_2:
if item in list_1 and (item not in commonList):
commonList.append(item)
print(list_1)
print(list_2)
print(commonList) |
7536ba39a645c9ac989321e8480375957526cb06 | wbroach/python_work | /person.py | 272 | 3.671875 | 4 | def build_person(first_name, last_name, age = ''):
person_dict = {'first': first_name, 'last': last_name}
if age:
person_dict['age'] = age
return person_dict
musician = build_person('jimi','hendrix',27)
print(musician)
|
3d7ecc3e1654e66643d59bb4d8b27032def34559 | YSreylin/HTML | /1101901079/0012/Estring16.py | 248 | 4.21875 | 4 | ''' write a Python program to insert a string in the middle of a string'''
a = input("Enter the input of a:")
y = a.split()
b = input('Enter the input in the middle of a:')
x = len(y)//2
y.insert(x,b)
print(y)
print(" ".join(c for c in y))
|
5f4b14988bd1a3bc47ffae2131935abcadfecc5f | gour6380/Python_demo | /swap.py | 398 | 4 | 4 | num1 = input("Enter first number: ");
num2 = input("Enter second number: ");
print("\nStarted swapping the given two numbers...");
number1 = int(num1);
number2 = int(num2);
swap = number1;
number1 = number2;
number2 = swap;
print("Given two numbers are successfully swapped!\n");
print("Value of First and Second number after swapping:");
print("First Number =",number1,"\nSecond Number=",number2); |
aabcac38259fee1d8f504ce256d2977c3410c059 | HolmQ84/PythonExercises | /venv/Week 37/Opgave 6 - OS Module exercise.py | 1,007 | 4 | 4 | # Opgave 6.
# os_exercise.py
# Do the following task using the os module
# 1. create a folder and name the folder 'os_exercises.'
# 2. In that folder create a file. Name the file 'exercise.py'
# 3. get input from the console and write it to the file.
# 4. repeat step 2 and 3 (name the file something else).
# 5. read the content of the files and and print it to the console.
import os
# 1. Create a folder 'os_exercises'
directory = 'C:/Users/marti/PycharmProjects/PythonExercises/venv/Week 37/'
name = 'os_exercises'
path = directory+name
if not os.path.exists(name):
os.mkdir(path)
# 2. Create a file in that folder called 'exercise.py'
os.chdir(path)
open('exercise1.py', 'w')
# 3.
text = input('Write something:\n=> ')
with open('exercise1.py', 'w') as f:
f.write(text)
# 4.
text = input('Write something:\n=> ')
with open('exercise2.py', 'w') as f:
f.write(text)
# 5.
with open('exercise1.py', 'r') as f:
with open('exercise2.py', 'r') as g:
print(f.read()+g.read()) |
8f7d916968eac5ab1e48dff1db0f748cc1d429cd | saivenkateshkurella93/Training-Deep-Network-Using-PyTorch | /singleFC.py | 637 | 3.890625 | 4 | ########################################################################
# Define a Convolution Neural Network
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 2. Change the code to have only a single fully connected layer.
# The model will have a single layer that connects the input to the output.
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(3 * 32 * 32, 10) #fully connected
def forward(self, x):
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
#x = self.fc1(x)
return x
|
920a9edddf9df0661a31384022044be1491501b1 | Maselkov/advent-of-code-2020 | /d18p2.py | 1,956 | 3.59375 | 4 | import puzzleinput
import operator
signs = {"+": operator.add, "*": operator.mul}
def evaluate(expression):
while True:
for i in range(1, len(expression), 2):
sign = expression[i]
if sign != operator.add:
continue
expression[i - 1:i +
2] = [sign(expression[i - 1], expression[i + 1])]
break
else:
break
count = expression[0]
for i in range(1, len(expression), 2):
count = expression[i](count, expression[i + 1])
return count
def evaluate_parentheses(line, start_pos):
if line[start_pos] != "(":
raise ValueError
for i in range(start_pos + 1, len(line)):
if line[i] == "(":
end_pos, value = evaluate_parentheses(line, i)
line[i:end_pos] = value
if line[i] == ")":
return i + 1, [evaluate(line[start_pos + 1:i])]
total = 0
for line in puzzleinput.lines:
line = line.split(" ")
added_index = 0
line_copy = line.copy()
for i, element in enumerate(line):
left_parentheses = [c for c in element if c == "("]
right_parentheses = [c for c in element if c == ")"]
number = "".join(c for c in element if c.isdigit())
if number:
line_copy[i + added_index] = int(number)
elif element in signs:
line_copy[i + added_index] = signs[element]
for p in left_parentheses:
line_copy.insert(i + added_index, "(")
added_index += 1
for p in right_parentheses:
line_copy.insert(i + 1 + added_index, ")")
added_index += 1
line = line_copy
while True:
for i, element in enumerate(line):
if element == "(":
end, value = evaluate_parentheses(line, i)
line[i:end] = value
break
else:
break
total += evaluate(line)
print(total)
|
3e1a6e1a2798e18e35c675bb778a363dc88f46f3 | LKBullard/bullardPythonChallenge | /Pypoll/PypollMain.py | 1,932 | 3.984375 | 4 | import csv
import os
#Create file path for csv import
path = os.path.join("Resources", "election_data.csv")
#sean recommends making this section a function using 'def'
#Define how to read in the csv
def read_file(path):
with open(path) as f:
csvreader = csv.reader(f, delimiter=',')
header = next(csvreader)
data = []
for row in csvreader:
data.append(row)
return data
#Define how to count the votes
def vote_count(data):
candidates = {}
total_votes = 0
for row in data:
candidate = row[2]
total_votes += 1
if candidate in candidates:
candidates[candidate] += 1
else:
candidates[candidate] = 1
return [candidates, total_votes]
#Define how to calculate the results
def calculate_results(candidates, total_votes):
winning_votes = 0
winner = ''
for candidate, votes in candidates.items():
if votes > winning_votes:
winner = candidate
winning_votes = votes
print_winner = f'The winner is {winner} with {winning_votes} votes!'
print_candidates = ''
for candidate, votes in candidates.items():
print_candidates = print_candidates+f'{candidate}: {votes} votes ({int(round((votes/total_votes)*100, 2))}%)\n'
results = f'{print_winner}\n-------------------------------------\n{print_candidates}'
return results
#Define how we want to print this to the console
def printresults(path):
vote_csv = read_file(path)
candidates, total_votes = vote_count(vote_csv)
results = calculate_results(candidates, total_votes)
print(results)
#Ask whether we want to save an output file of the results
save_results = input('Do you want to save the output? (y/n)\n')
if save_results=='y':
with open('Pypoll_Results.txt', 'w') as doc:
doc.write(save_results)
#print results in console
printresults(path) |
c4f8b75c575b1e9c5604e7f5ae8afcaf1ead8eb5 | AlitosJM/python_course | /OOP/car2.py | 571 | 3.84375 | 4 | class Car:
#constructor
def __init__(self, starting_top_speed=100):
self.top_speed = starting_top_speed
self.warnings = []
def drive(self):
print('I am driving not faster than {}'.format(self.top_speed))
#creating an object base on class
car1 = Car()
car1.drive()
car1.warnings.append('new warning')
print(car1.warnings)
car2 = Car(999)
car2.drive()
print(car2.warnings)
car3 = Car()
car3.drive()
print(car2.warnings)
'''
I am driving not faster than 100
I am driving not faster than 999
[]
I am driving not faster than 100
[]
''' |
8c2f43f3d8f72c3a265e100ed56d6929d34adf4b | deepsjuneja/Task1 | /comdiv.py | 211 | 3.65625 | 4 | def num():
a = int(input("Enter first number"))
b = int(input("Enter second number"))
n = min(a, b)
for i in range(1, n):
if a%i == 0 & b%i == 0:
print(i)
num()
|
fec4f73e5fdfd0be061f90a8531144c1bf25592c | Woody-1018/Python-Autotest_learning | /Python基础/2、if分支及for循环.py | 2,366 | 4.28125 | 4 | # if else 判断,注意分号
a = 5
b = 3
if a >= b:
print('a > b')
else:
print('a < b')
# 等于判断 ==
man = 'Wangnima'
if man == 'Wangnima':
print('%s is SB' % man)
else:
print('%s is SB as well' % man)
# in,not in 判断
hi = 'hello python'
if 'hello' in hi:
print('contained')
else:
print('not contained')
# True,False 布尔类型判断
# 1、有两种值True和
# Flase
#
# 2、布尔类型值得运算
#
# 与运算:只有两个布尔值都为
# True
# 时,计算结果才为
# True。
# True and True # ==> True
# True and False # ==> False
# False and True # ==> False
# False and False # ==> False
# 或运算:只要有一个布尔值为
# True,计算结果就是
# True。
# True or True # ==> True
# True or False # ==> True
# False or True # ==> True
# False or False # ==> False
# 非运算:把True变为False,或者把False变为True:
# not True # ==> False
# not False # ==> True
# 3、布尔类型还可以与其他数据类型做 and、or和not运算
# 例子:
# a = True
# print
# a and 'a=T' or 'a=F'
# 结果:a = T
# 字符串
# 'a=T',这是为什么呢?
# Python把0、空字符串
# ''
# 和None看成
# False,其他数值和非空字符串都看成
# True,所以:
# True and 'a=T'
# 计算结果是
# 'a=T'
# 继续计算
# 'a=T' or 'a=F'
# 计算结果还是
# 'a=T'
# and 和 or 运算的一条重要法则:短路计算。
# 多个if循环
score = 90
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 70:
print('中等')
elif score >= 60:
print('及格')
else:
print('不及格')
# for 循环
i = 'hello world'
for i in i:
print(i)
animals = ['dog', 'cat', 'pig', 'lion', 'monkey']
for animals in animals:
print(animals)
# range 函数
# 函数原型:range(start, end, scan):
#
# 参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
#
# end:计数到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
#
# scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
for i in range(10):
print(i)
for i in range(0, 10):
print(i)
for i in range(0, 10, 3):
print(i)
for i in range(5):
print(i)
i += 2
print(i)
print('一轮结束')
|
f4d32bb0f3a2e6a9402c132f9047b5e6db891a12 | ebarbs/p4e | /Course 3/Course3_Week6_Assignment2.py | 2,720 | 4.25 | 4 | # Welcome Eric Barbieri from Using Python to Access Web Data
#
# Calling a JSON API
#
# In this assignment you will write a Python program somewhat similar to
# http://www.py4e.com/code3/geojson.py. The program will prompt for a location,
# contact a web service and retrieve JSON for the web service and parse that
# data, and retrieve the first place_id from the JSON. A place ID is a textual
# identifier that uniquely identifies a place as within Google Maps.
# API End Points
#
# To complete this assignment, you should use this API endpoint that has a static
# subset of the Google Data:
#
# http://py4e-data.dr-chuck.net/geojson?
# This API uses the same parameter (address) as the Google API. This API also has
# no rate limit so you can test as often as you like. If you visit the URL with
# no parameters, you get a list of all of the address values which can be used
# with this API.
# To call the API, you need to provide address that you are requesting as the
# address= parameter that is properly URL encoded using the urllib.urlencode()
# fuction as shown in http://www.py4e.com/code3/geojson.py
#
# Test Data / Sample Execution
#
# You can test to see if your program is working with a location of "South Federal
# University" which will have a place_id of "ChIJJ8oO7_B_bIcR2AlhC8nKlok".
#
# $ python3 solution.py
# Enter location: South Federal UniversityRetrieving http://...
# Retrieved 2101 characters
# Place id ChIJJ8oO7_B_bIcR2AlhC8nKlok
# Turn In
#
# Please run your program to find the place_id for this location:
#
# University of Southern California
# Make sure to enter the name and case exactly as above and enter the place_id and
# your Python code below. Hint: The first seven characters of the place_id are
# "ChIJC2a ..."
# Make sure to retreive the data from the URL specified above and not the normal
# Google API. Your program should work with the Google API - but the place_id
# may not match for this assignment.
#
import urllib.request, urllib.parse, urllib.error
import json
# Note that Google is increasingly requiring keys
# for this API
serviceurl = 'http://py4e-data.dr-chuck.net/geojson?'
while True:
address = input('Enter location: ')
if len(address) < 1: break
url = serviceurl + urllib.parse.urlencode(
{'address': address})
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
try:
js = json.loads(data)
except:
js = None
if not js or 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue
# print(json.dumps(js, indent=4))
print('Place id', js["results"][0]["place_id"])
|
1fb8b22d0a98fd6dc687a4a80fae17c47e29070c | BilyanaDemirok/learning_python | /first_lesson.py | 3,614 | 4.46875 | 4 | # Task_1: Define a variable named 'my_first_string_variable' and
# assign 'This is a string type content.' value to it.
# Solution:
my_first_string_variable = 'This is a string type content.'
# Task_2: Print the value of my_first_string_variable to stdout.
# Solution:
print(my_first_string_variable)
# Task_3: Print the value of my_first_string_variable to stdout as in the following format:
# 'Value of my_first_string_variable: This is a string type content.'
# Hint: Use string substantiation.
# Solution:
print(f'Value of my_first_string_variable: This is a string type content')
# Task_4: Define two integer variables named 'num_1' and 'num_2' with the values of 100 and 200 respectively.
# Solution:
num_1, num_2 = 100, 200
# Task_5: Substract num_1 from num_2 and assing the result to a variable named 'substracted'.
# Solution:
num_1, num_2 = 100, 200
substracted = num_2 - num_1
print(substracted)
# Task_6: Print the value of substracted variable in the format of 'The result of substracting 100 from 200 equals to 100.'
# Hint: Use string substantiation for all the variables involved in the substraction.
# Solution:
print('The result of substracting 100 from 200 equals to 100.')
# Task_7:
# - Define a string type variable named 'name' with the value of 'John'.
# - Define a string type variable named 'lastname' with the value of 'Doe'.
# Print 'My name is John Doe.' to stdout by using string concatanation.
# Solution:
name = 'John'
lastname = 'Doe'
print('My name is ' +name +' '+lastname)
# Task_8: Define a list type variable named 'favorite_colours' with the value of 'black', 'red', 'orange'.
# Solution:
favorite_colours_list = ['black', 'red', 'orange']
print(favorite_colours_list)
# Task_9: Print the second item of the favorite_colours as: 'The second favorite of colour is red.'
# Hint: Use string substitution.
# Solution:
favorite_colours_list = ['black', 'red', 'orange']
favorite_cities = ['rome', 'madrid', 'paris']
print(f'The second favorite colour is {favorite_colours_list[1]}')
print(f'the sum of 2 and 3 equals {2+3}')
# Task_10: Add 'blue' to the favorite_colours list.
# Solution:
favorite_colours_list = ['black', 'red', 'orange']
favorite_colours_list.append('blue')
print(favorite_colours_list)
# Task_11: Print the following messages to the stdout.
# 'The content of the favorite_colours list: ['black', 'red', 'orange', 'blue']'
# 'The length of favorite_colours list is 4.'
# Hint: Use 2 print statements.
# Solution:
content = ['black', 'red', 'orange', 'blue']
print(len(content))
# Task_12: Print the first 2 items of the favorite_colours list by using list slicing.
# Solution:
content = ['black', 'red', 'orange', 'blue']
print(content[:2])
# Task_13: Print the content of the favorite_colours list as:
# 1 - black
# 2 - red
# 3 - orange
# 4 - blue
# Solution:
favorite_colours = ['black', 'red', 'orange', 'blue']
for item in favorite_colours:
print(f'{favorite_colours.index(item) +1} - {item}')
# Task_14: Define a dictionary variable with the name of 'user' and
# assign keys 'name', 'lastname', 'favorite_colours' with the previously (see above tasks) defined values.
# Solution:
user = {'name': name, 'lastname': lastname, 'favorite_colours': favorite_colours}
# Task_15: Print the user variable.
# Solution:
print(user)
# Task_16: Add a new key 'age' to the 'user' variable with the value of 39. And, print the user.
# Solution:
user['age'] = 39
# Task_17: Update the last favorite colour of the user variable as 'white'. Print the user.
# Solution:
user['favorite_colours'][-1] = 'white'
print(user)
|
90bcd85b3b672eb1f6e86d183d7466d4ef998d94 | gistable/gistable | /all-gists/4542897/snippet.py | 2,347 | 3.921875 | 4 | import heapq
from threading import Lock
class HeapQueue(object):
def __init__(self, values=None, maxsize=None, reversed=False):
"""
Create a new heap queue.
- ``maxsize`` will create a capped queue.
- ``reversed`` will create a max heap queue (default is min).
>>> queue = HeapQueue(maxsize=10, reversed=True)
>>> queue.push('foo', 3)
>>> queue.push('bar', 1)
>>> queue.push('baz', 2)
>>> # default behavior is to exhaust the queue
>>> results = queue.sorted(exhaust=True)
[(3, 'foo'), ('2, 'bar'), (1, 'baz')]
>>> # the queue now has been exhausted
>>> len(queue)
0
"""
self.lock = Lock()
self.lst = values or []
self.maxsize = maxsize
self.reversed = reversed
heapq.heapify(self.lst)
def __len__(self):
return len(self.lst)
def push(self, element, score):
if not self.reversed:
score = score * -1
element = (score, element)
with self.lock:
if self.maxsize and len(self.lst) >= self.maxsize:
heapq.heappushpop(self.lst, element)
else:
heapq.heappush(self.lst, element)
def pop(self):
with self.lock:
score, element = heapq.heappop(self.lst)
if self.reversed:
score = score * -1
return score, element
def sorted(self):
with self.lock:
results = [heapq.heappop(self.lst) for x in xrange(len(self.lst))]
for score, element in reversed(results):
if not self.reversed:
score = score * -1
yield score, element
if __name__ == '__main__':
# test min heap queue
queue = HeapQueue(maxsize=2)
queue.push('foo', 3)
queue.push('bar', 1)
queue.push('baz', 2)
results = list(queue.sorted())
assert len(results) == 2
assert results[0] == (1, 'bar'), results[0]
assert results[1] == (2, 'baz'), results[1]
# test max heap queue
queue = HeapQueue(maxsize=2, reversed=True)
queue.push('foo', 3)
queue.push('bar', 1)
queue.push('baz', 2)
results = list(queue.sorted())
assert len(results) == 2
assert results[0] == (3, 'foo'), results[0]
assert results[1] == (2, 'baz'), results[1]
|
ead854b5ed106f4d9b885c12b27e336d51fb0bfe | you-know1993/ComBots-Ethics | /pseudo_code.py | 2,955 | 3.796875 | 4 | # imports
"""
Things to think about
Which way are we defining the genders? (How does Tae do it?)
Suggestion
Male: 0
Female: 1
Unknown/Neutral/Both: 2
"""
def get_visual_gender(image_filepath):
"""
Reads image
Load Tae's gender-age code.
Extract gender & confidence.
Translate gender and confidence to Male, Female, Unknown/Neutral (0,1,2)
# Maybe we need a function to read the image file path to the format needed for Tae's module
:param image_filepath: string to filepath
:return: 0,1,2 for male, female, unknown
"""
def get_name_gender(name_string):
"""
Use (harvard) api.
Translate result to 0,1,2 for gender coding.
:param name_string: The name as a string (not sure about capitalisation)
:return: 0,1,2 for male, female, unknown
"""
def greeting_script():
"""
Script where Leolani introduces herself and asks who are you
:return: tuple(name, pronouns) or tuple(name, None)
"""
def pronoun_retrieving_script(name_gender, visual_gender):
"""
Assumes or asks for pronouns.
This is where the scenarios go if the pronouns were not given in the introduction.
:param name_gender: 0,1,2 relating to gender of name
:param visual_gender: 0,1,2 relating to gender of visual input
:return: pronouns
"""
def create_triple(name_string, pronouns_string):
"""
Create triple in Leolani brain format.
Probably something like: LeolaniWorld:Quirine, property:has_pronouns, value:she/her.
# How do we store the pronouns? Options: tuple of strings ("she", "her"), string "she/her", int 0, 1 or 2 (but then its a predefined finite set.
:param name_string: String of name to store in Leolani brain (is this needed to form the triple
:param pronouns_string: string of pronouns
:return: triple in Leolani brain format
"""
def store_triple(triple_object):
"""
Store triple object in folder and file
:param triple_object:
:return: nothing, saved triple in correct location
"""
def main():
triple_file = "somefolder/somefile.someformat" # Location of where to store triple
name = None
pronouns = None
# Leolani introduces herself and asks who are you. Assume name will be given. Pronouns might be given.
name, pronouns = greeting_script()
# If pronouns are not given
if pronouns == None:
# Extract gender based on visual input and name
visual_gender = get_visual_gender(image_filepath)
name_gender = get_name_gender(name_string)
# Run through script to extract pronouns either by asking or assuming
pronouns = pronoun_retrieving_script(name_gender, visual_gender)
# if for some reason the system breaks or there is a leak then use they them pronouns
if pronouns == None:
pronouns = "they/them"
# Adapt to Leolani format
triple_object = create_triple(name, pronouns)
store_triple(triple_object, triple_file) |
18a42c9697e0277da2823ac957026f80bfa62755 | Galdair/PythonHard | /ex21.py | 682 | 4.0625 | 4 | def add(a,b):
print "adding %d + %d " %(a ,b)
return a+b
def substract (a,b):
print "substracting %d - %d " %(a ,b)
return a-b
def multiply (a,b):
print "multiplying %d * %d" %(a,b)
return a*b
def divide(a,b):
print "dividing %d / %d" %(a,b)
return a/b
print "let's do some maths with just functions"
age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print "Age: %d ,Height: %d ,Weight: %d ,IQ: %d " %(age,height,weight,iq)
print "here is a puzzle"
what = add(age,substract(height,multiply(weight,divide(iq,2))))
my_answer = 35+(74-(25*180))
print "is what equals to my calculations?", what == my_answer |
22e3aa0e4f01ad764510bc406b67fe54e3107f53 | TemistoclesZwang/Algoritmo_IFPI_2020 | /exerciciosComCondicionais/A_CONDICIONAIS/02A_EX14.py | 930 | 3.75 | 4 | #14. Leia 5 (cinco) números inteiros, calcule a sua média e escreva os que são maiores que a média.
def main():
n1 = int(input('Insira o número 1: '))
n2 = int(input('Insira o número 2: '))
n3 = int(input('Insira o número 3: '))
n4 = int(input('Insira o número 4: '))
n5 = int(input('Insira o número 5: '))
media(n1,n2,n3,n4,n5)
def media(n1,n2,n3,n4,n5):
calc_media = (n1 + n2 + n3 + n4 + n5) / 5
print (f'A média é {calc_media}')
if n1 > calc_media:
print (f'Esse número é maior que a média: {n1}')
elif n2 > calc_media:
print (f'Esse número é maior que a média: {n2}')
elif n3 > calc_media:
print (f'Esse número é maior que a média: {n3}')
elif n4 > calc_media:
print (f'Esse número é maior que a média: {n4}')
elif n5 > calc_media:
print (f'Esse número é maior que a média: {n5}')
main() |
24fd41d12f880f479987ccfdb81e1cbbb2b365d3 | ahmachan/pythonDemo | /lotmain.py | 956 | 3.53125 | 4 | # coding=utf-8
import lottery
class MyTest:
myname = 'peter'
# add a instance attribute
def __init__(self, name):
self.name = name
def start(self):
print ('the name is %s'%self.name)
return lottery.choice_once()
def sayhello(self):
return "say hello to %s" % MyTest.myname
def spendRmbYears(self,year):
spendRmbData=lottery.spend_years(year)
#元组
pay_in,pay_out=spendRmbData
#字典
#pay_in = spendRmbData['in']
#pay_out = spendRmbData['out']
#列表
#pay_in = spendRmbData[0]
#pay_out = spendRmbData[1]
print("a day spend 2 RMB,then %s years late, you spent %i RMB, and earn %i RMB,so you cost %i RMB " % ( year,pay_out, pay_in,pay_out-pay_in))
if __name__ == "__main__":
test = MyTest('John')
outStr = test.start()
print(outStr)
print(test.sayhello())
print(test.spendRmbYears(10))
|
ebd53257ff3a0c569c43ef1d335a10ef983371d1 | Faraday1221/dividend | /read_file.py | 887 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 23:54:56 2015
@author: jonbruno
"""
import os
import csv
# change to the directory where the csv is stored (assuming it is not part of
# the path)
file_dir = '/Users/jonbruno/Documents/Python/dividend'
os.chdir(file_dir)
# note this is just a test
filename = 'BBEP Dividends Only.csv'
filename = 'BBEP Historical Stock Prices.csv'
with open(filename, 'rb') as source:
file_in = csv.reader(source, dialect=csv.excel_tab)
for line in file_in:
print line
# since excels csv formatting is throwing an error
# we will just use the tab delimited version from a nice old text file
filename = 'Breitburn.txt'
with open(filename, 'rb') as source:
file_in = csv.reader(source, delimiter="\t")
for line in file_in:
print line
# we might want to think about grabbing the dates and converting their format |
530c03355fbb85c4dec09a8e14b64b528d371359 | siddharthchd/Errors_and_Exception_Handling | /exception_handling.py | 275 | 4.0625 | 4 | def add(n1,n2):
print(n1 + n2)
number1 = 10
number2 = input("Enter number : ")
try:
# Attempt to run code that may have an error
#add(number1, number2)
result = 10 + 10
except:
print("You aren't adding correctly")
else:
print("Something went wrong")
|
7f4efebe413e2c16ba3d795c78ddd6c709d6f186 | amadjarov/thinkPython | /hangMan/hangMan.py | 2,022 | 3.828125 | 4 | import random
import sys
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
word = random.choice(words)
print word
noRepeatWord="".join(set(word))
wrongGuess = ""
rightGuess = ""
print " Hello this is HANGMAN game!!! Enjooy"
print " U can guess wrong only 6 times"
print "Hint : words are only animals "
#print HANGMANPICS[0]
def display(HANGMANPICS, wrongGuess):
print HANGMANPICS[len(wrongGuess)]
def getChar(wrongGuess):
leng = 0
while leng < 6:
print " Please enter a character"
guess = raw_input()
guess = guess.lower()
if len(guess) == 1 and guess in "abcdefghijklmnopqrstuvwxyz":
return guess
else:
print "You should enter only one character from the alphabet"
while True:
guess = getChar(wrongGuess)
if guess in word:
rightGuess += guess
else:
wrongGuess += guess
display(HANGMANPICS, wrongGuess)
if len(wrongGuess) == 6:
print " You loose the word was {"+word+"} try next time"
sys.exit()
if len(rightGuess) == len(noRepeatWord):
print " You are smart the word was {"+word+"} Good job"
sys.exit() |
76d9e09194dacd30a10e6068bb2b2a277a534a1a | AnnamalaiNagappan/crud_python_sqlite | /main.py | 2,783 | 3.625 | 4 | import sqlite3
import os
import csv
def create_new_db(db_name):
conn = sqlite3.connect(db_name + '.db')
print "Opened database successfully";
return conn
def get_current_date(conn):
curr_stmp = conn.execute("SELECT CURRENT_TIMESTAMP;")
return curr_stmp
def create_new_tble(conn):
conn.execute('''CREATE TABLE IF NOT EXISTS COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";
return
def insert_rows(conn, row):
uid = row[0]
name = row[1]
age = row[2]
address = row[3]
salary = row[4]
conn.execute("INSERT OR IGNORE INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (?, ?, ?, ?, ?)", (uid, name, age, address, salary ));
conn.commit()
return
def update_rows(conn):
conn.execute("UPDATE COMPANY SET SALARY = 25000.00 WHERE ID = 1");
conn.commit()
print "Records updated successfully";
cursor = get_data(conn)
display_data(cursor)
return
def delete_rows(conn, tbl_name, col_name, col_val):
conn.execute("DELETE FROM " + tbl_name + " WHERE " + col_name + "=" + col_val);
conn.commit()
print "Records deleted successfully";
cursor = get_data(conn)
display_data(cursor)
return
def get_data(conn):
cursor = conn.execute("SELECT id, name, address, salary from COMPANY")
return cursor
def display_data(cursor):
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
return
db_name = 'test' # raw_input()
conn = create_new_db(db_name)
create_new_tble(conn)
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
for ix, row in enumerate(reader):
if ix > 0:
insert_rows(conn, row)
print "All Records created successfully";
cursor = get_data(conn)
choice_display = { '0': ['Exit'],
'1': ['Display'],
'2': ['Update'],
'3': ['Delete'],
}
choice = 1
while(choice):
print "WELCOME :: "
for ch in choice_display:
print ch, choice_display[ch][0]
print " 1. Display 2. Update, 3. Delete"
print "Enter your choice"
choice = input()
if choice == 1:
display_data(cursor)
elif choice == 2:
update_rows(conn)
elif choice == 3:
print "Enter the table name"
tbl_name = raw_input()
print "Enter the column"
col_name = raw_input()
print "Enter the value for the column"
col_val = raw_input()
delete_rows(conn, tbl_name, col_name, col_val)
conn.close() |
5be1ba5884dfb1dc56f8f88c034335496ff0e675 | ocdarragh/Computer-Science-for-Leaving-Certificate-Solutions | /Chapter 1/pg29_branching_elif.py | 270 | 3.875 | 4 | payType = input("Do you want to pay using card, cash or coupon? \n \t:")
if payType == "cash" :
print ("Please insert cash.")
elif payType == "card" :
print("Insert card into the machine.")
else:
print("Coupons are only accepted at Customer Service.") |
83f16fd043b9c67102b80f6e35448c082e8f001d | tabletenniser/leetcode | /5650_min_hamming_distance.py | 3,642 | 4.09375 | 4 | '''
You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.
The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed).
Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.
Example 1:
Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
Output: 1
Explanation: source can be transformed the following way:
- Swap indices 0 and 1: source = [2,1,3,4]
- Swap indices 2 and 3: source = [2,1,4,3]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
Example 2:
Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
Output: 2
Explanation: There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
Example 3:
Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
Output: 0
Constraints:
n == source.length == target.length
1 <= n <= 105
1 <= source[i], target[i] <= 105
0 <= allowedSwaps.length <= 105
allowedSwaps[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
'''
class Solution:
def find(self, parent, i):
if (parent[i] == -1):
return i, 0
root, rank = self.find(parent, parent[i])
return root, rank+1
def union(self, parent, x, y):
xset, x_rank = self.find(parent, x)
yset, y_rank = self.find(parent, y)
if x_rank < y_rank:
parent[xset] = yset
else:
parent[yset] = xset
return
def minimumHammingDistance(self, source, target, allowedSwaps) -> int:
n = len(source)
lt = {}
for i, num in enumerate(source):
lt[num] = lt.get(num, []) + [i]
# print(lt)
parent = {}
for i in range(n):
parent[i] = -1
for a,b in allowedSwaps:
if self.find(parent, a)[0] == self.find(parent, b)[0]:
continue
self.union(parent, a, b)
# print(parent)
i = 0
res = 0
while i < n:
if source[i] == target[i]:
i += 1
continue
# print(i, target[i], lt[target[i]])
switched = False
if target[i] in lt:
for j in lt[target[i]]:
# print(i, j, self.find(parent,i), self.find(parent, j))
if self.find(parent, i)[0] == self.find(parent, j)[0]:
source[i], source[j] = source[j], source[i]
switched = True
break
if not switched:
res += 1
# print(i, source)
i += 1
return res
s = Solution()
source = [5,1,2,4,3]
target = [1,5,4,2,3]
allowedSwaps = [[0,4],[4,2],[1,3],[1,4],[0,3]]
source=[18,67,10,36,17,62,38,78,52]
target=[3,4,99,36,26,58,29,33,74]
allowedSwaps=[[4,7],[3,1],[8,4],[5,6],[2,8],[0,7],[1,6],[3,7],[2,5],[3,0],[8,5],[2,1],[6,7],[5,1],[3,6],[4,0],[7,2],[2,6],[4,1],[3,2],[8,6],[8,0],[5,3],[1,0],[4,6],[8,7],[5,7],[3,8],[6,0],[8,1],[7,1],[5,0],[4,3],[0,2]]
print(s.minimumHammingDistance(source, target, allowedSwaps))
|
27f0379c5d4d44d12ba69ebe961495feb91d747e | timofeysie/rainbow-connection | /python/lipo-voltage-demo.py | 1,486 | 3.53125 | 4 | # This example shows how to read the voltage from a lipo battery connected to a Raspberry Pi Pico via our Pico Lipo SHIM, and uses this reading to calculate how much charge is left in the battery.
# It then displays the info on the screen of Pico Display or Pico Explorer.
# Remember to save this code as main.py on your Pico if you want it to run automatically!
from machine import ADC, Pin
import utime
# Set up and initialise display
buf = bytearray(display.get_width() * display.get_height() * 2)
vsys = ADC(29) # reads the system input voltage
charging = Pin(24, Pin.IN) # reading GP24 tells us whether or not USB power is connected
conversion_factor = 3 * 3.3 / 65535
full_battery = 4.2 # these are our reference voltages for a full/empty battery, in volts
empty_battery = 2.8 # the values could vary by battery size/manufacturer so you might need to adjust them
while True:
voltage = vsys.read_u16() * conversion_factor
percentage = 100 * ((voltage - empty_battery) / (full_battery - empty_battery))
if percentage > 100:
percentage = 100.00
if charging.value() == 1: # if it's plugged into USB power...
print("Charging!", 15, 55, 240, 4)
else: 98i # if not, display the battery stats
print('{:.2f}'.format(voltage) + "v", 15, 10, 240, 5)
print('{:.0f}%'.format(percentage), 15, 50, 240, 5)
utime.sleep(1) |
f0c67ee7b363dbca4d56237f3bf82e1c261a0da8 | fares-ds/Algorithms_and_data_structures | /00_algorithms_classes/linear_search.py | 220 | 3.859375 | 4 | def linear_search(lst, element):
for item in lst:
if item == element:
return True
return False
lst_1 = [0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]
print(linear_search(lst_1, 14))
|
e683351d618c7da75f0f54c5314beb697d3b2942 | Yuta1004/ZeroDeepLearning-fromScratch | /ch4/gradient_descent.py | 1,363 | 3.828125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def function_1(x):
return x[0] ** 2 + x[1] ** 2
def function_2(x):
return x ** 2
def numerical_gradient(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
for idx in range(x.size):
x_tmp_val = x[idx]
# f(x+h)
x[idx] = x_tmp_val + h
fxh1 = f(x)
# f(x-h)
x[idx] = x_tmp_val - h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2) / (2 * h)
x[idx] = x_tmp_val
return grad
def gradient_descent(f, init_x, lr=0.1, step_num=100):
x = init_x
x_history = []
for _ in range(step_num):
x_history.append(x.copy())
grad = numerical_gradient(f, x)
# print(x, lr, grad)
x -= lr * grad
return x, np.array(x_history)
if __name__ == '__main__':
# x = np.arange(-10, 10, 0.1)
# y = function_1(np.array([x, x]))
init_x = np.array([-3.0, 4.0])
end_x, x_history = gradient_descent(function_1, init_x)
print(end_x)
plt.plot(x_history[:, 0], x_history[:, 1], 'o')
plt.xlim(-3.5, 3.5)
plt.ylim(-4.5, 4.5)
plt.xlabel("X0")
plt.ylabel("X1")
plt.show()
# init_x = np.array([10.0])
# end_x, x_history = gradient_descent(function_2, init_x)
#
# plt.plot(x, y)
# plt.plot(x_history, function_2(x_history), 'o')
# plt.show()
|
5bd0de0eab5d587746b684b9f4b510d378026898 | hariharan1307/python | /AlarmClock.py | 913 | 4 | 4 | import datetime
print("Required format : hr:min am/pm--> 07:20 am")
inputTime = input("WakeUp time? :")
WakeupList = inputTime.split(" ")
DayOrNight=WakeupList[1]
Time = WakeupList[0]
WakeupTime=Time.split(":")
hour=int(WakeupTime[0])
minutes = int(WakeupTime[1])
if DayOrNight=="pm":
hour+=12
def validation(hr,min):
if hr > 24:
if min > 60:
print("hours and minutes should not exceed the standard time limits")
return False
print("hours should not exceed 24")
return False
print("waiting for the alarm ", str(hour).zfill(2), ":", str(minutes).zfill(2),DayOrNight)
return True
if validation(hour,minutes):
while True:
if hour==datetime.datetime.now().hour and minutes== datetime.datetime.now().minute:
print("its ",str(hour).zfill(2),":",str(minutes).zfill(2),DayOrNight, " time to wakeup kid!!!!")
break
|
320bbec14d118120fc60d0ece6f7cae6d434462e | darkaxelcodes/randompython | /SelectionSortModified.py | 549 | 4.0625 | 4 | '''
Program to implement Selection Sort
The time complexity of above algorithm is O(n^2)
'''
def find_min (list0):
min = 0
for i in range(1,len(list0)):
if list0[i] < list0[min]:
min = i
return min
def selection_sort(list0):
i = 0
while i < len(list0):
pos = find_min(list0[i:])
if pos != 0:
list0[i], list0[pos+i] = list0[pos+i], list0[i]
i+=1
return list0
list0 = [10,9,8,7,6,5,4,3,2,1]
sorted_list0 = selection_sort(list0)
print(sorted_list0) |
b62e11c0207968b87dbaebd6df97f001b7b35913 | oeseo/-STEPIK-Python- | /11.1.py | 283 | 3.703125 | 4 | """
/step/2
элементами
/step/3
4
/step/4
4
/step/5
да
/step/6
[0, 1, 3, 14, 2, 7, 9, 8, 10]
/step/7
['Michael', 'John', 'Freddie']
/step/8
n = int(input())
print(list(range(1, n+1)))
/step/9
n = int(input())
s = 'abcdefghijklmnopqrstuvwxyz'
print(list(s[:n]))
"""
|
777e1a78cdec786954d030f8a6566f101acb03b6 | DDR7707/Python-Data-Structures | /Practice/Heaps.py | 1,533 | 3.703125 | 4 | def heapify(arr , n , i):
largest = i
left = 2*i + 1
right = 2*i + 2
while left < n and arr[left] > arr[largest]:
largest = left
while right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i] , arr[largest] = arr[largest] , arr[i]
heapify(arr , n , largest)
def insert(arr , new):
size = len(arr)
arr.append(new)
if size != 0:
for i in range((len(arr) // 2) - 1 , -1 , -1):
heapify(arr , len(arr) , i)
def delete(arr , tar):
size = len(arr)
for i in range(size):
if arr[i] == tar:
break
arr[i] , arr[size - 1] = arr[size - 1] , arr[i]
arr.pop()
for j in range((size // 2) - 1 , -1 , -1):
heapify(arr , len(arr) , j)
def heapsort(arr):
final = []
# Heapify
for i in range((len(arr) // 2) , -1 , -1):
heapify(arr , len(arr) , i)
# Delete from the top and heapify simultaniously
for i in range(len(arr) - 1, -1 , -1):
arr[0] , arr[i] = arr[i] , arr[0]
final.append(arr.pop())
heapify(arr , i , 0)
print(final)
arr = []
# insert(arr , 3)
# insert(arr , 4)
# insert(arr , 9)
# insert(arr , 5)
# insert(arr , 2)
# print(arr)
# delete(arr , 4)
# print(arr)
insert(arr , 1)
insert(arr , 12)
insert(arr , 9)
insert(arr , 5)
insert(arr , 6)
insert(arr , 10)
print(arr)
delete(arr , 6)
print(arr)
heapsort(arr)
|
7e5a9bb222d873f0eb3853660b546f49546b5407 | ertankara/leetcode-problems | /problems/python/powxn.py | 499 | 3.765625 | 4 | from math import pow
class Solution():
def myPow(_, x: float, n: int) -> float:
'''Raises x to the nth power'''
return pow(x, n)
def check_solution():
solution = Solution()
delta = 0.0001
assert abs(solution.myPow(2.00000, 10) - 1024.00000 < delta)
assert abs(solution.myPow(2.10000, 3) - 9.26100 < delta)
assert abs(solution.myPow(2.00000, -2) - 2 < delta)
assert abs(solution.myPow(-2.00000, 2) - 4 < delta)
print("Correct!")
check_solution()
|
87c920dc77ce7ed63ee36973fca67aae8316c506 | hitarthsolanki/ADV-C151-SALES-APPLICATION | /sales_application.py | 1,999 | 3.875 | 4 | from tkinter import *
import random
root=Tk()
root.title("SALES APPLICATION")
root.geometry("700x500")
root.configure(bg="yellow")
month = ("January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
profits = (20000, 45000, 78000, 97000, 12000, 456000, 65000, 54000, 10000, 30000, 70000, 90000)
max_profits = Label(root)
min_profits = Label(root)
label_month = Label(root)
label_profit = Label(root)
label_month["text"] = "Months : " + str(month)
label_profit["text"] = "Profits : " + str(profits)
def maxprofit():
max_profits["text"] = " The maximum profit of " + str(max_profit) + " was recorded in the month of " + str(max_profit_month)
def minprofit():
min_profits["text"] = " The minimum profit of " + str(min_profit) + " was recorded in the month of " + str(min_profit_month)
max_profit = max(profits)
max_profit_index = profits.index(max_profit)
print(max_profit_index)
max_profit_month = month[max_profit_index]
print( " The maximum profit of " + str(max_profit) + " was recorded in the month of " + str(max_profit_month))
min_profit = min(profits)
min_profit_index = profits.index(min_profit)
print(min_profit_index)
min_profit_month = month[min_profit_index]
print( " The minimum profit of " + str(min_profit) + " was recorded in the month of " + str(min_profit_month))
btn1 = Button(root)
btn1 = Button(root, text = "Show Max Profitable Month", command = maxprofit, bg="blue", fg="white")
btn1.place(relx = 0.5,rely = 0.4, anchor = CENTER)
btn2 = Button(root)
btn2 = Button(root, text = "Show Min Profitable Month", command = minprofit, bg="blue", fg="white")
btn2.place(relx = 0.5,rely = 0.6, anchor = CENTER)
label_month.place(relx=0.5,rely=0.2, anchor=CENTER)
label_profit.place(relx=0.5,rely=0.3, anchor=CENTER)
max_profits.place(relx=0.5,rely=0.5, anchor=CENTER)
min_profits.place(relx=0.5,rely=0.7, anchor=CENTER)
root.mainloop() |
bfd5136d47a591c0a6d05d0989c0f2e872544565 | sergedurand/3M101-Quadtree | /code/Compression/Compression.py | 4,077 | 3.5625 | 4 | from PIL import Image
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Pixel(object):
def __init__(self, color = [0, 0, 0],
topLeft = Point(0, 0),
bottomRight = Point(0, 0)):
self.R = color[0]
self.G = color[1]
self.B = color[2]
self.topLeft = topLeft
self.bottomRight = bottomRight
class quadtree():
def __init__(self, image):
self.tailletab = 0 #nb de noeuds
#chargement de l'image
self.image = image.load()
self.tree = [] #liste de noeuds
self.x = image.size[0]
#print("self x:",self.x)
self.y = image.size[1]
#print("self y:",self.y)
nbpixels = image.size[0] * image.size[1] #nombre total de feuilles (pixels)
print(self.x)
print(self.y)
print(nbpixels)
nbtemp=nbpixels
nbq=0 #nombre de quadrants
while(nbtemp>=1):
nbtemp=int(nbtemp/4)
nbq+=nbtemp
#print("nbtemp: ",nbtemp)
self.tailletab=nbq+nbpixels #taille du tableau: nombre de pixels+nombre de quadrants
for i in range(self.tailletab):
self.tree.append(Pixel())
#print(tree)
cpt=0
for i in range(self.x-1,0,-2): #Insertion des feuilles à la fin du tableau
for j in range(self.y-1,0,-2): #Remplissage ligne par ligne de droite à gauche, de bas en haut
self.tree[self.tailletab-1-4*cpt]=Pixel(self.image[i, j], Point(i, j), Point(i, j))
self.tree[self.tailletab-1-4*cpt-1]=Pixel(self.image[i, j-1], Point(i, j-1), Point(i, j-1))
self.tree[self.tailletab-1-4*cpt-2]=Pixel(self.image[i-1, j], Point(i-1, j), Point(i-1, j))
self.tree[self.tailletab-1-4*cpt-3]=Pixel(self.image[i-1, j-1], Point(i-1, j-1), Point(i-1, j-1))
cpt+=1
#insertion des quadrants
print("tailletab-cpt= ",self.tailletab-4*cpt-1)
for i in range(self.tailletab-4*cpt-1,-1,-1):
#print("i= ",i)
#print("4i+1= ",4*i+1)
if (4*i+4<self.tailletab):
self.tree[i] = Pixel( #Coordonnées des 4 fils de tree[i]: 4*i+1,4*i+2,4*i+3,4*i+4
[(self.tree[4 * i + 1].R + self.tree[4 * i + 2].R + self.tree[4 * i + 3].R + self.tree[4 * i + 4].R) / 4,
(self.tree[4 * i + 1].G + self.tree[4 * i + 2].G + self.tree[4 * i + 3].G + self.tree[4 * i + 4].G) / 4,
(self.tree[4 * i + 1].B + self.tree[4 * i + 2].B + self.tree[4 * i + 3].B + self.tree[4 * i + 4].B) / 4], #La couleur du nouveau pixel i est la moyenne arithmétique des couleurs de ses 4 pixels fils
self.tree[4 * i + 1].topLeft,
self.tree[4 * i + 4].bottomRight)
def compression(self,qual): #prend le niveau de compression en paramètre
start = 1
for i in range(0, qual):
start = 4 * start
"""while (start<self.size):
start=4*start+1
start=int((start-1)/4)
print(start)"""
if (start > self.tailletab):
print('Qualité trop grande')
return
img = Image.new("RGB", (self.x, self.y), "black")
pixels = img.load()
for i in self.tree[0 : 4 * start]: #parcours du quadtree, plus qual est grand, plus la qualité de l'image sera meilleure
x1 = i.topLeft.x
y1 = i.topLeft.y
x2 = i.bottomRight.x
y2 = i.bottomRight.y
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
pixels[x, y] = (int(i.R), int(i.G), int(i.B)) #Construction de la nouvelle image
img.show();
img.save('compression2.jpg')
def main():
I=Image.open("galaxie.jpg")
Tree=quadtree(I)
Tree.compression(8)
#Faire des tests avec le paramètre de la fonction compression. Trop bas: trop basse qualité, trop haut: comportement bizarre
|
adac3d678fa45770343e4101ee07d310b34d3d9a | coryeleven/learn_python | /file_exception/file_read.py | 1,613 | 3.828125 | 4 | #关键字with 在不需要访问文件后将其文件关闭
#open 函数
with open("1txt", encoding='utf-8') as file_object: #将文件内容存在变量file_object中
contens = file_object.read()
#rstrip 删除空白
print(contens.rstrip())
#\\反转 \t失败成制表符
file_path = "/\\2test"
with open("/\\2test", encoding='utf-8') as file_object:
contens = file_object.read()
print(contens)
#逐行读取
with open(file_path,encoding='utf-8') as file_object:
for conten in file_object:
print("逐行读取 :")
print("\t " + conten.rstrip())
#使用文件内容
with open("1txt") as file_number:
#readlines 读取文件的每一行
lines = file_number.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string[:50] + "....")
print(len(pi_string))
# birthday = input("Enter your birthdat,in the from mmddyy: ")
# if birthday in pi_string:
# print("Your birthday appers in the first million digits of pi!")
# else:
# print("Your birthday does not appers in the first million digits of pi!")
#10-1
print("\n10-1 练习笔记")
with open("pro.txt") as file_pro:
#读取整个文件
# contens = file_pro.read()
# print(contens)
#遍历循环读取文件
# for i in file_pro:
# print(i)
#存储在一个变量中,遍历读取文件
# lines = file_pro.readlines()
# for line in lines:
# print(line.strip())
#10-2
lines = file_pro.readlines()
for line in lines:
#replace 替换
print(line.rstrip().replace("Python","java"))
|
475f5f29140b85604c39114b8642472faae7e10d | amey-joshi/am | /p3/dbs.py | 907 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# We want to consider signals for n = -5, -4, ..., 4, 5.
# Note that we want to simulate negative indexes. We do
# so by translating an index to its array position. An
# index i of the signal translates to (i + EXTENT) in the
# array. Thus, the signal indexes -5, -4, ..., 4, 5 map to
# array indexes 0, 1, ..., 10.
EXTENT = 5
# The vectors b_1^0 and c_1^0.
b = np.zeros(2 * EXTENT + 1)
c = np.zeros(2 * EXTENT + 1)
# Initial values
b[0 + EXTENT] = 1
c[0 + EXTENT] = 1
def get_b1(k):
i = k + 5 # index in the array
return (k + 1) * c[i] + (1 - k) * c[i - 3]
def get_c1(k):
i = k + 5
return (k + 3/2) * b[i + 1] + (1/2 - k)*b[i]
# The vectors b_1^1 and c_1^1.
B = np.zeros(2 * EXTENT + 1)
C = np.zeros(2 * EXTENT + 1)
for k in range(-3, 3):
B[k + EXTENT] = get_b1(k)
C[k + EXTENT] = get_c1(k)
print(B)
print(C)
|
ae2f147a0cac3a11271285a4425ab84e8ce5fe2a | Werefriend/CS112-Spring2012 | /hw03/prissybot.py | 945 | 4.1875 | 4 | #!/usr/bin/env python
p="Prissybot: "
name=raw_input(p+"Enter your name ")
print p+"Hello there, %s." %(name)
n="%s: " %(name)
resp1=raw_input(n)
print p+'You mean, "%s," sir!!!1!1' %(resp1)
print p+"How old are you in years, miserable meatsock?"
age=int(raw_input(n))
dog=age*7
print p+"That means you're %d in dog years. Are you sure you're not a dog?" %(dog)
pause1=raw_input(n)
print "You know your mother was a dog."
resp2=raw_input(n)
length=len(resp2)
print p+"Oooh! Look! Look at the human! %s can make phrases with" %(name),length,"characters."
print p+"What a SPECIAL vertebrate..."
print p+"Do you know what that %d divided by 17283 is," %(length),name+"?"
lengthnum=length/17283.0
vd=raw_input(n)
print p+"It's",lengthnum,", meatsock."
print p+"What's you're favorite number?"
favorite=int(raw_input(n))
print p+"That's stupid,",name+"."
favorite+=1
print p,favorite,"is obviously superior, you ignorant air-breather."
|
5627e56c3e476a94b8e56b59f0366bc2e96598ad | dpkolee/first-repository | /exercise3.py | 458 | 3.921875 | 4 | dob = input("enter date of birth in yyyy-mm-dd format: ")
date_parts = dob.split('-')
[year, month, day] = date_parts
dob_timestamp = float(year) + float(month)/12 + float(day)/365
[today_year, today_month,today_day] = ['2017', '03', '17']
today_timestamp = float(today_year) + float(today_month)/12 + float(today_day)/365
years = today_timestamp - dob_timestamp
months = (years - int(years)) * 12
print('your age is %d years %d months' % (years, months)) |
f94c2b35cccc9f735a15a8c2b2332c9b4385aebe | gujie1216933842/codebase | /python-basicgrammar基本语法/08_zip用法.py | 156 | 3.890625 | 4 | a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9, 10]
zipped = zip(a, b)
zipped1 = zip(a, c)
print(list(zipped))
# print(list(zipped1))
print(list(zip(*zipped)))
|
75776986efbc9259b00a5e03ea3f71bb247d8585 | pasko-evg/miptLabs | /lab007_Test_01/task_b.py | 2,073 | 3.515625 | 4 | # Определите тип треугольника (остроугольный, тупоугольный, прямоугольный) с данными сторонами.
# Формат входных данных
# Даны три натуральных числа – стороны треугольника. Каждое число вводится с новой строки.
# Формат выходных данных
# Необходимо вывести одно из слов: right для прямоугольного треугольника,
# acute для остроугольного треугольника, obtuse для тупоугольного треугольника
# или impossible, треугольника с такими сторонами не существует.
debug = False
TESTS = [([3, 4, 5], "right")]
def check_triangle(triangle_params: list):
triangle_params.sort()
min_side = triangle_params[0]
middle_side = triangle_params[1]
max_side = triangle_params[2]
if debug:
print("min side: {}, middle side: {}, max side: {}".format(min_side, middle_side, max_side))
# проверка на треугольник
if min_side != 0 and middle_side != 0 and max_side != 0 and min_side + middle_side > max_side:
# проверка на прямоугольный треугольник
if min_side ** 2 + middle_side ** 2 == max_side ** 2:
return "right"
if min_side ** 2 + middle_side ** 2 > max_side ** 2:
return "acute"
if min_side ** 2 + middle_side ** 2 < max_side ** 2:
return "obtuse"
else:
return "impossible"
if __name__ == '__main__':
for test in TESTS:
testing_function = check_triangle
result = testing_function(test[0])
assert result == test[1], "Ожидаемый ответ: {0}, полученный овет: {1}".format(test[1], result)
parameters = []
for i in range(3):
parameters.append(int(input()))
print(check_triangle(parameters))
|
87c664be65fb3d9309345ce4be0020a73d416a15 | geseiche/cs2223 | /Project 1/p1.py | 1,443 | 3.671875 | 4 | import time
def euclid(m, n):
while (n != 0):
r = m % n
m = n
n = r
return m
def consecIntCheck(m, n):
t = min(m, n)
while True:
if(m%t==0 and n%t==0):
return t
else:
t -= 1
def primeFactors(m):
factors = []
t=2
while (m != 1):
if(m%t==0):
factors.append(t)
m = m/t
t=2
else:
t +=1
return factors
def middleSchool(m, n):
mfactors = primeFactors(m)
nfactors = primeFactors(n)
gcd = 1
for mfactor in mfactors:
if mfactor in nfactors:
gcd *= mfactor
nfactors.remove(mfactor)
return gcd
def effGCD(m, n):
start = time.clock()
euclid(m, n)
end = time.clock()
print("Euclid time: ", end-start)
start = time.clock()
consecIntCheck(m, n)
end = time.clock()
print("Consecutive Integer Checking time: ", end-start)
start = time.clock()
middleSchool(m, n)
end = time.clock()
print("Middle School time: ", end-start)
x = 1
while (x<=3):
m = int(input("Enter an m (must be an int >0): "))
n = int(input("Enter an n (must be an int >0): "))
if(m<=0 or n<=0):
if(x<3):
print("Invalid input. Try again")
else:
print("Invalid input. Goodbye")
x += 1
continue
else:
print("GCD: ", euclid(m,n))
effGCD(m,n)
break
|
a08fa779e6cbf25d38232fac500d5000e0c665b1 | AllenLiuX/My-LeetCode | /leetcode-python/#229 Majority Element II.py | 910 | 3.5625 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
target1, target2 = -1, -1
count1, count2 = 0, 0
for i in nums:
if i == target1:
count1 += 1
elif i == target2:
count2 += 1
elif count1 == 0:
target1 = i
count1 += 1
elif count2 == 0:
target2 = i
count2 += 1
else:
count1 -= 1
count2 -= 1
size1, size2 = 0, 0
for i in nums:
if i == target1:
size1 += 1
if i == target2:
size2 += 1
res = []
if size1 > len(nums)/3:
res.append(target1)
if size2 > len(nums) / 3 and target1 != target2:
res.append(target2)
return res
|
e57e20a050bc915c4dcd7422c0eac4a56791ae18 | TsvetomirTsvetkov/Python-Course-101 | /week01/02.DiveIntoPython/increasing_or_decreasing.py | 755 | 4.21875 | 4 | def increasing_or_decreasing(seq):
is_up = False
is_down = False
length = len(seq)
if length == 1:
return False
if seq[0] > seq[1]:
is_down = True
elif seq[0] < seq[1]:
is_up = True
for i in range(1, length - 1):
if(seq[i] > seq[i + 1] and is_up) or \
(seq[i] < seq[i + 1] and is_down) or \
(seq[i] == seq[i + 1]):
return False
if is_up:
return 'Up!'
if is_down:
return 'Down!'
def main():
print(increasing_or_decreasing([1,2,3,4,5]))
# Expected output : Up!
print(increasing_or_decreasing([5,6,-10]))
# Expected output : False
print(increasing_or_decreasing([1,1,1,1]))
# Expected output : False
print(increasing_or_decreasing([9,8,7,6]))
# Expected output : Down!
if __name__ == '__main__':
main() |
49ac9d28cdc33d372bad35111a0dada73d3cf5c4 | Gi1ia/TechNoteBook | /Algorithm/909_Snakes_Or_Ladders.py | 1,299 | 3.546875 | 4 | import collections
class Solution:
def snakesAndLadders(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
if not board or not board[0] or len(board[0]) == 1:
return 0
# Reorder board to straight
n = len(board)
straight = []
index = []
seq = 1
for i in reversed(range(n)):
if seq == 1:
straight.extend(board[i])
seq = -1
else:
straight.extend(reversed(board[i]))
seq = 1
# Calculate
step = 0
seen = {1:0}
possible = collections.deque([1])
while possible:
cursor = possible.popleft()
if cursor == n*n:
return seen[cursor]
# move to next
for cursor2 in range(cursor + 1, cursor + 7):
if cursor2 > n*n:
continue
if straight[cursor2 - 1] != -1:
cursor2 = straight[cursor2 - 1]
if cursor2 not in seen:
possible.append(cursor2)
seen[cursor2] = seen[cursor] + 1
return -1
|
123340781d0b2e8014c20551fcf79fa97e5b813a | kaushik4u1/DATA-STRUCTURE-AND-ALGORITHM | /Dictionaries(Pyhton)/04-search dict().py | 452 | 4.375 | 4 | #How to search for a value in dictionary.
myDict = {'Name':'Sam', 'Age':26, 'Address':'USA'} #dict{}-can use to create a dictionary.
def searchVal(dicti,value):
for key in dicti:
if dicti[key] == value:
return key, value
return 'This value does not exist.'
print(searchVal(myDict,26))
print(searchVal(myDict,27))
#Output: ('Age', 26)
# This value does not exist.
#Time Complexity:O(n)
#Space Complexity:O(1)
|
c765558e5c8a97e8f2aa98803a5950fd091ae757 | quixoteji/Leetcode | /solutions/559.maximum-depth-of-n-ary-tree.py | 710 | 3.625 | 4 | #
# @lc app=leetcode id=559 lang=python3
#
# [559] Maximum Depth of N-ary Tree
#
# @lc code=start
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root : return 0
level = []
level.append(root)
queue = []
queue.append(level)
while level :
next_level = []
for node in level :
for child in node.children :
next_level.append(child)
queue.append(next_level)
level = next_level
return len(queue) - 1
# @lc code=end
|
fe25c8a34635ef70f9b6a14080286deee2d55ebd | huynv184120/LSSR | /SLRS/state/TrialState.py | 1,983 | 3.5 | 4 | from abc import ABC, abstractmethod
class Trial:
@abstractmethod
def update(self):
pass
@abstractmethod
def check(self):
pass
@abstractmethod
def revert(self):
pass
@abstractmethod
def commit(self):
pass
class Objective:
@abstractmethod
def score(self):
pass
class TrialState(Trial):
def __init__(self):
self.nTrial = 0
self.maxTrial = 16
self.trials = []
@abstractmethod
def updateState(self):
pass
@abstractmethod
def commitState(self):
pass
@abstractmethod
def revertState(self):
pass
def addTrial(self, trial):
if self.nTrial == self.maxTrial:
self.maxTrial <<= 1
self.nTrial += 1
self.trials.append(trial)
def update(self):
self.updateState()
pTrial = 0
while pTrial < self.nTrial:
self.trials[pTrial].update()
pTrial += 1
def check(self):
pTrial = 0
while (pTrial < self.nTrial):
if self.trials[pTrial].check() == False:
break
pTrial += 1
_pass = (pTrial == self.nTrial)
if _pass != True :
while pTrial > 0:
pTrial -= 1
self.trials[pTrial].revert()
self.revertState()
return _pass
def revert(self):
self.revertAll()
self.revertState()
def commit(self):
self.commitAll()
self.commitState()
def revertAll(self):
pTrial = self.nTrial
while pTrial > 0:
pTrial -= 1
self.trials[pTrial].revert()
def commitAll(self):
pTrial = 0
while pTrial < self.nTrial:
self.trials[pTrial].commit()
pTrial += 1
|
8df65a7201bcfdc5e61219492bed306689b7e4d9 | muhammadalifh/PyopenGL | /Tugas1/Line_Bresenham.py | 1,524 | 3.578125 | 4 | from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import sys
def init():
glClearColor(0.0,0.0,0.0,1.0)
gluOrtho2D(0,100,0,100)
def plotLine(x1,y1,x2,y2):
# Bresenham Algo
m = 2 * (y2 - y1)
pk = m - (x2 - x1)
y = y1
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1.0,0.0,0.0)
glPointSize(10.0)
glBegin(GL_POINTS)
for x in range(x1,x2+1):
glVertex2f(x,y)
pk = pk + m
if (pk >= 0):
y = y+1
pk = pk - 2 * (x2 - x1)
glEnd()
glFlush()
os.system('clear')
os.system('cls')
def main():
choice = 0
while (choice != 2):
choice = input("Please Choose \n\t1. Plot a New line\n\t2. Exit\n")
if int(choice) == 1:
x1 = int(input("Enter x1: "))
y1 = int(input("Enter y1: "))
x2 = int(input("Enter x2: "))
y2 = int(input("Enter y2: "))
print("starting window....")
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGB)
glutInitWindowSize(500,500)
glutInitWindowPosition(0,0)
glutCreateWindow("Bresenham Algorithm")
glutDisplayFunc(lambda: plotLine(x1,y1,x2,y2))
glutIdleFunc(lambda: plotLine(x1,y1,x2,y2))
init()
glutMainLoop()
elif int(choice) == 2:
sys.exit()
else:
print("Invalid choice")
choice = 0
main() |
a768f8b74230cd0c599355dc74ea3fc57c3cb9d6 | Lodek/pdd | /pdd/sequential_blocks.py | 4,481 | 3.796875 | 4 | """
Sequential Logic building blocks
"""
import pdd.combinational_blocks as cb
from pdd.gates import *
from pdd.dl import BaseCircuit, Bus
class SRLatch(BaseCircuit):
"""
Classic SRLatch implementation using 2 NOR gates cross connected.
SRLatches are the fundamental building block of Sequential circuits.
"""
input_labels = 's r'.split()
output_labels = 'q q_bar'.split()
def make(self):
i = self.get_inputs()
q_or = OR(a=i.r, bubbles=['y'])
q_bar_or = OR(a=i.s, b=q_or.y, bubbles=['y'])
q_or.connect(b=q_bar_or.y)
self.set_outputs(q=q_or.y, q_bar=q_bar_or.y)
class DLatch(BaseCircuit):
"""
DLatch adds combinational logic to the SRLatch to make it more useful.
When clk is high the signal at d is propagated to q, else q is unchaged.
clk bus must be of size 1
"""
input_labels = 'd clk'.split()
output_labels = ['q']
sizes = dict(clk=1)
def make(self):
i = self.get_inputs()
clk = i.clk.branch(i.d)
reset_gate = AND(a=clk, b=i.d, bubbles=['b'])
set_gate = AND(a=clk, b=i.d)
sr = SRLatch(s=set_gate.y, r=reset_gate.y)
self.set_outputs(q=sr.q)
class DFlipFlop(BaseCircuit):
"""
In practice DLatches aren't used often. If d changes while clk is high, the
change propagates to q. FlipFlops only propagate d to q at the
rising edge of the clock.
"""
input_labels = 'd clk'.split()
output_labels = ['q']
sizes = dict(clk=1)
def make(self):
i = self.get_inputs()
l1 = DLatch(d=i.d, clk=i.clk, bubbles=['clk'])
l2 = DLatch(d=l1.q, clk=i.clk)
self.set_outputs(q=l2.q)
class FlipFlop(BaseCircuit):
"""
There are many variations of flip flops. Resetable flip flops, enable flip flops,
tri-stated output flipflops. This impelementation implements all of the above.
e and l are active low, r is active high
"""
input_labels = "r e clk l d".split()
output_labels = "q".split()
sizes = dict(r=1, e=1, clk=1, l=1)
def make(self):
i = self.get_inputs()
#have nice defaults without user intervention
not_e = INV(a=i.e).y
l_mux = cb.BaseMux(d0=i.d, s=i.l)
reset_mux = cb.BaseMux(d0=l_mux.y, d1=Bus.gnd(i.d), s=i.r)
dflip = DFlipFlop(d=reset_mux.y, clk=i.clk)
l_mux.connect(d1=dflip.q)
self.set_tristate(q=not_e)
self.set_outputs(q=dflip.q)
class Counter(BaseCircuit):
"""
Counter with a synchronous reset.
c is a count signal, if c is high counter will increment on the rising edge
otherwise it won't.
"""
input_labels = "clk r c".split()
output_labels = "q".split()
sizes = dict(clk=1, r=1, c=1)
def make(self):
i = self.get_inputs()
word_size = len(i.q)
flip = FlipFlop(q=i.q, clk=i.clk)
c_gate = AND(a=Bus.vdd(), b=i.c)
adder = cb.CPA(a=flip.q, b=c_gate.y.zero_extend(flip.q))
reset_mux = cb.BaseMux(d0=adder.s, d1=Bus.gnd(adder.s), s=i.r)
flip.connect(d=reset_mux.y)
self.set_outputs(q=flip.q)
class SettableCounter(BaseCircuit):
"""
"""
input_labels = "d l clr clk".split()
output_labels = "q".split()
sizes = dict(l=1, clr=1, clk=1)
def make(self):
i = self.get_inputs()
word_size = len(i.d)
mux = cb.SimpleMux(d1=i.d, s=i.l)
flip = sb.ResetFlipFlop(d=mux.y, clk=i.clk, reset=i.clr)
adder = cb.CPA(a=flip.q, b=Bus(word_size, 1))
mux.connect(d0=adder.s)
self.set_outputs(q=flip.q)
class RAM(BaseCircuit):
"""
Word adressable RAM implementation.
w and ce are high active.
"""
input_labels = "d clk addr w ce".split()
output_labels = "q".split()
def __init__(self, word_size, **kwargs):
self.word_size = word_size
self.sizes = dict(ce=1, clk=1, w=1, q=word_size, d=word_size)
super().__init__(**kwargs)
def make(self):
i = self.get_inputs()
self.set_tristate(q=i.ce)
#cells have active low enable
addr_lines = cb.Decoder(a=i.addr, e=Bus.vdd())
cells = [FlipFlop(clk=i.clk, d=i.d, e=en_bus, q=i.q, bubbles=['e']) for en_bus in addr_lines.y]
write_gates = [AND(a=i.w, b=bus, bubbles=['y']) for bus in addr_lines.y]
for gate, cell in zip(write_gates, cells):
cell.connect(l=gate.y)
|
600a2338c151d67c999fc0e1b6c7a52e9b22e66f | Mschikay/leetcode | /394. Coins in a Line.py | 1,511 | 3.875 | 4 | # There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.
#
# Could you please decide the first player will win or lose?
#
# If the first player wins, return true, otherwise return false.
#
# Example
# Example 1:
#
# Input: 1
# Output: true
# Example 2:
#
# Input: 4
# Output: true
# Explanation:
# The first player takes 1 coin at first. Then there are 3 coins left.
# Whether the second player takes 1 coin or two, then the first player can take all coin(s) left.
# Challenge
# O(n) time and O(1) memory
class Solution:
"""
@param n: An integer
@return: A boolean which equals to true if the first player will win
"""
def firstWillWin(self, n):
# write your code here
if not n: return False
dp = [False for i in range(n + 1)]
dp[1] = True
for i in range(2, len(dp)):
if not dp[i - 1] or not dp[i - 2]:
dp[i] = True
return dp[n]
class Solution:
"""
@param n: An integer
@return: A boolean which equals to true if the first player will win
"""
def firstWillWin(self, n):
# write your code here
if not n: return False
pre1 = False
pre2 = True
for i in range(1, n + 1):
if i == 1:
curr = True
else:
curr = not pre1 or not pre2
pre1, pre2 = pre2, curr
return curr |
2afda918607660bed82e01fc885a4c76cfefb971 | xinru1414/Steganography | /secret.py | 5,600 | 4.21875 | 4 | """
Steganography
A python program that hides information (text messages) in png files
Based on DrapsTV's "Steganography Tutorial - Hiding Text inside an Image" https://www.youtube.com/watch?v=q3eOOMx5qoo
Loads an image and look at each pixel's hex value
If the pixel's blue channel falls in the 0-5 range then 1 bit of info is stored
Ends the stream with a delimiter of fifteen 1's and one 0.
"""
from PIL import Image
import binascii
import optparse
def rgb2hex(r, g, b):
"""
Turn rgb color values to hex color values
:param r (int): red chanel value
:param g (int): green chanel value
:param b (int): blue chanel value
:return (string): a hex value
"""
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
def hex2rgb(hexcode):
"""
Turn hex color values to rgb color values
:param hexcode (string): hex value
:return (tuple): r, g, b value
"""
assert isinstance(hexcode, str)
assert len(hexcode) == 7
r = int(hexcode[1:3], 16)
g = int(hexcode[3:5], 16)
b = int(hexcode[5:7], 16)
return r, g, b
def str2bin(message):
"""
Turn a message into binary omit first two digits
:param message: This should be a str encoded in utf-8
:return: binary string
"""
message_bytes = bytes(message, "utf-8")
binary = bin(int(binascii.hexlify(message_bytes), 16))
return binary[2:]
def bin2str(binary):
"""
Turn a binary into string
:param binary:
:return:
"""
message_bytes = binascii.unhexlify('%x' % (int(binary, 2)))
return str(message_bytes, encoding="utf-8")
def encodeblue(hexcode, digit):
"""
:param hexcode:
:param digit:
:return:
"""
if hexcode[-1] in ('0', '1', '2', '3', '4', '5'):
hexcode = hexcode[:-1] + digit
return hexcode
else:
return None
def encodegreen(hexcode, digit):
"""
:param hexcode:
:param digit:
:return:
"""
if hexcode[-3] in ('0', '1', '2', '3', '4', '5'):
hexcode = hexcode[:-3] + digit + hexcode[5:]
return hexcode
else:
return None
def decodeblue(hexcode):
"""
:param hexcode:
:return:
"""
if hexcode[-1] in ('0', '1'):
return hexcode[-1]
else:
return None
def decodegreen(hexcode):
"""
:param hexcode:
:return:
"""
if hexcode[-3] in ('0', '1'):
return hexcode[-3]
else:
return None
def hide(filename, message):
"""
Hide the message in the png image
:param filename (png): the png file that's been used as the medium
:param message (string): the secret message you are trying to hide
:return:
"""
img = Image.open(filename)
binary = str2bin(message) + '1111111111111110'
if img.mode in 'RGBA':
img = img.convert('RGBA')
pixels = img.getdata()
new_pixels = []
digit = 0
count = 0
for item in pixels:
if digit < len(binary) and count % 2 == 0:
new_pix = encodeblue(rgb2hex(item[0], item[1], item[2]), binary[digit])
if new_pix is None:
new_pixels.append(item)
else:
r, g, b = hex2rgb(new_pix)
new_pixels.append((r, g, b, 255))
digit += 1
elif digit < len(binary) and count % 2 != 0:
new_pix = encodegreen(rgb2hex(item[0], item[1], item[2]), binary[digit])
if new_pix is None:
new_pixels.append(item)
else:
r, g, b = hex2rgb(new_pix)
new_pixels.append((r, g, b, 255))
digit += 1
else:
new_pixels.append(item)
count += 1
img.putdata(tuple(new_pixels))
img.save(filename, 'PNG')
return "Completed!"
return "Incorrect Image mode detect, couldn't hide message"
def retr(filename):
"""
retrieve the message from the png image
:param filename: the png file that contains the secret message
:return: the secret message
"""
img = Image.open(filename)
binary = ''
count = 0
if img.mode in 'RGBA':
img = img.convert('RGBA')
pixels = img.getdata()
for item in pixels:
if count % 2 == 0:
digit = decodeblue(rgb2hex(item[0], item[1], item[2]))
else:
digit = decodegreen(rgb2hex(item[0], item[1], item[2]))
count += 1
if digit is None:
pass
else:
binary = binary + digit
if binary[-16:] == '1111111111111110':
print("success")
return bin2str(binary[:-16])
return bin2str(binary)
return "Incorrect Image mode detect, couldn't retrieve message"
def main():
"""
parameter handling
"""
parser = optparse.OptionParser('usage %png '
'-e/-d <target file>')
parser.add_option('-e', dest='hide', type='string',
help='target picture parse to hide text')
parser.add_option('-d', dest='retr', type='string',
help='target picture parse to retrieve text')
(options, args) = parser.parse_args()
if options.hide is not None:
text = input("Enter a message to hide: ")
print(hide(options.hide, text))
elif options.retr is not None:
print(retr(options.retr))
else:
print(parser.usage)
exit(0)
if __name__ == "__main__":
main()
|
8274a918073fa28e910484761f73bf3f30c5dff1 | Vitormendesgoncalo/Pythoncomputer | /Número primo.py | 1,279 | 3.953125 | 4 | import time
Primo = int(input('Digite um numero que iremos dizer quantos numeros primos abaixo dele existem: ')) # Variável Primo aquisita um número que será limite
Divisor = int(1) # Numero inicial que irá dividir o numero e se o resto for 0 será contabilizado em uma variável Soma
Numero = int(2) # Sofrerá a divisão da variável Divisor
Soma = int(0) # Variável que começará com zero, mas irá somar cada vez que o resto der 0 da divisão
while Numero<=Primo: # Enquanto o numero for menor do que o valor aquisitado em primo executará a rotina abaixo
if Divisor<=Numero: # Enquanto o Divisor for menor do que o numero a ser dividido
Resultado = int (Numero%Divisor) # Pega o resto da divisão e armazena em resultado
Divisor += 1 # Soma mais 1 no numero para fazer a próxima divisão
if Resultado == 0: # Verifica se a divisão deu 0 mesmo
Soma+=1 # Soma 1 na variável Soma
else:
if Soma == 2: # Se só somou 2 vezes é um numero primo
print('O numero', Numero,'é primo') # mostra o numero primo
Soma = 0 # Zera a soma
Numero += 1 # soma 1 no numero
Divisor = 1 # joga novamente o valor inicial 1 no Divisor
|
96847d87e9fae0a6f63fa6e033b571469775011e | chiragnayak/python | /examples/uniqueWords.py | 434 | 3.859375 | 4 |
fhandle = open (input("Enter File To Fetch unique Words : "), encoding="utf8")
uniqueWords = []
for line in fhandle :
words = line.split()
if len(words) == 0 : continue
for word in words :
if word in uniqueWords :
continue
else :
uniqueWords.append(word)
print ("Unique word %s found ! " % word)
print ("Number of unique words : %d " % len(uniqueWords))
print ("Unique Words : ", uniqueWords)
|
c8ea5edcb60b5815163a11521eb033e343a6beb9 | zahraaliiii1997/AOA_assignment | /Towerofhenoi.py | 306 | 3.828125 | 4 | def tower(n, start, end, middle):
if n == 1:
print("move %i from tower %s to tower %s" % (n, start, end))
else:
tower(n - 1, start, middle, end)
print("move %i from tower %s to tower %s" % (n, start, end))
tower(n - 1, middle, end, start)
tower(6, "A", "C", "B")
|
46ca6f945964355723a600b216efe07688e559c4 | AmineMbaye/projects_am | /python/progs/7_boucles.py | 308 | 3.546875 | 4 | """
Boucle for
# salution = "Assalamu Alaykum Wa Rahmatullah"
# for mot in salution:
# print(mot)
"""
print("for")
for nombre in range(1, 11):
print(nombre)
"""
Boucle while
"""
print("while")
nombr = 8
indice = 0
while indice < 10:
print(indice+1, " * ", nombr, " = ", (indice+1)*nombr)
indice += 1
|
103a349b2c36e457ed99999911147dc74f7d7fb0 | Yvonnexx/code | /binary_tree_maximum_path_sum.py | 680 | 3.640625 | 4 | #!/usr/bin/python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root):
self.maxsum = float('-inf')
self.maxpath(root)
return self.maxsum
def maxpath(self, root):
if not root:
return 0
lsum = self.maxpath(root.left)
rsum = self.maxpath(root.right)
import pdb;pdb.set_trace()
self.maxsum = max(self.maxsum, lsum+root.val+rsum)
return max(root.val+lsum, root.val+rsum, 0)
s = Solution()
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.left = b
a.right = c
print s.maxPathSum(a)
|
815ebb247e01120fb67e56f5cdc8255e057058cd | tomgauth/p7-oc-AlgoInvest-Trade | /optimized.py | 3,617 | 3.65625 | 4 | import sys
import pandas as pd
import time
def main():
dataset = sys.argv[1]
budget = int(sys.argv[2]) * 100
def create_df(dataset_csv):
# Import the data from a csv file as a pandas dataframe
df = pd.read_csv(dataset, index_col=False)
# clean up the data set from negative or values equal to 0
df = df[df['price'] >= 0]
df['price'] = (df['price']*100).astype(int)
df['profit'] = (df['profit']*100).astype(int)
# create a column for the value of the action after 2 years
df['2y value'] = df['price'] * df['profit']/100
return df
def find_best_stocks(ids, values, prices, budget):
n = len(values)
best_stocks = []
total_cost = 0
# Create a 2D array of size budget+1 * n+1
K = [[0 for w in range(budget + 1)]
for i in range(n + 1)]
# Go through each row
for i in range(n + 1):
print(i, "rows out of ", n + 1, " done.")
# Fill each row (item) with the best value possible
for w in range(budget + 1):
# first row and first column are filled with 0's
if i == 0 or w == 0:
K[i][w] = 0
""" If the price of the cell above is less than the budget
Remove the current budget w to the current price (column)
Add to it the value of the currentcombination
unless the value of the previous cell is higher
"""
elif prices[i - 1] <= w:
K[i][w] = round(max(
values[i - 1] + K[i - 1][w - prices[i - 1]],
K[i - 1][w]), 2)
else:
# otherwise get the same value as the previous cell
K[i][w] = K[i - 1][w]
# stores the result
# The value of K[n][budget] (last row last column) is the highest
res = K[n][budget]
best_2y_roi = round(res / 100, 2)
# Now lets got through the table to find which items
# compose the highest value
w = budget
for i in range(n, 0, -1): # Starting at the bottom
# if res is 0, there are no more items possible
if res <= 0:
break
""" Checks the cell on the top, if the value is the same as
the current cell, move up
otherwise add the current item (row), remove the value
of the item, find the next best item with this value available
in the table
"""
if res == K[i - 1][w]:
continue
else:
# This item is included.
best_stocks.append(i - 1)
# Since this weight is included
# its value is deducted
res = round(res - values[i - 1], 2)
w = w - prices[i - 1]
total_cost = sum(prices[i] for i in best_stocks)
print("---------------")
print("Best 2y ROI is: ", round(best_2y_roi/100, 2))
print("Best stocks IDs: ", [ids[i] for i in best_stocks])
print("total Cost :", round(total_cost/100, 2))
df = create_df(dataset)
ids = df['name'].tolist()
values = [i for i in df['2y value'].tolist()]
prices = [i for i in df['price'].tolist()]
find_best_stocks(ids, values, prices, budget)
if __name__ == "__main__":
start_time = time.time()
main()
print("The algorithm took %s seconds to complete" %
(round((time.time() - start_time), 2)))
|
c7583c451ea78215476ec75594a57885a7569df5 | thinkingjxj/Python | /mark/高级/3.py | 271 | 3.65625 | 4 | __author__ = 'thinking'
# pre = 0
# cur = 1
# print(pre,cur,end=' ')
# n = 4
# for i in range(n-1):
# pre,cur = cur, pre + cur
# print(cur,end = ' ')
def fib(n):
return 1 if n < 2 else fib(n - 1) + fib(n - 2)
for i in range(5):
print(fib(i), end=' ')
|
a6da0001849d18a31b1347d88795ada959e4c887 | KonstantinSKY/LeetCode | /859_Buddy_Strings.py | 956 | 3.546875 | 4 | """859. Buddy Strings https://leetcode.com/problems/buddy-strings/ """
import time
from typing import List
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if A == B and len(set(A)) < len(A):
return True
idx = []
for i in range(len(A)):
if A[i] != B[i]:
idx.append(i)
if len(idx) > 2:
return False
if len(idx) == 2 and A[idx[0]] == B[idx[1]] and A[idx[1]] == B[idx[0]]:
return True
return False
if __name__ == "__main__":
start_time = time.time()
print(Solution().buddyStrings("ab", "ba"))
print(Solution().buddyStrings("ab", "bas"))
print(Solution().buddyStrings("aa", "aa"))
print(Solution().buddyStrings("ab", "ab"))
print(Solution().buddyStrings("abcaa", "abcbb"))
print("--- %s seconds ---" % (time.time() - start_time))
|
dc4a261d2a25eff8edd149987dc2bdba211b9093 | MANI3415/WebDevelopmentUsingDjango-internship-SRM-University | /18 june 2021/2.list_comprehension.py | 509 | 4.15625 | 4 | # calculate the sum of squares of n natural numbers
n = int(input("Enter value for n:"))
# print(sum([i**2 for i in range(1,n)]))
# calculate the sum of squares of even between n natural numbers
#result_l = []
#for i in range(1,n+1):
# if i%2 == 0:
# result_l.append(i**2)
#print(sum(result_l))
#print(result_l)
#syntax for comprehension with if condition
# [expression_on_loop_variable forloop if condition(loop_varibl)]
print(sum([i**2 for i in range(1,n+1) if i%2 ==0]))
|
e95448cefb1c184e5286ac6bc1e344dfdbbd3ef5 | akhil-sah/online_exam_form | /Test.py | 1,088 | 3.546875 | 4 | # name=input('Enter form name: ')
name = 'Test-Form'
html = open(name+'.html', 'w')
def tab(n):
str = ''
for i in range(n):
str += ' '
return str
def markdownToHtml(text):
return text
html.write('<!doctype html>'+'\n')
html.write('<html>'+'\n')
html.write(tab(1)+'<head>'+'\n')
html.write(tab(2)+'<title>')
html.write(name)
html.write('</title>'+'\n')
html.write(tab(1)+'</head>'+'\n')
html.write(tab(1)+'<body>'+'\n')
html.write(tab(2)+'<form>'+'\n')
n = int(input('Enter number of questions: '))
for i in range(n):
html.write(tab(3)+'<hr>'+'\n')
html.write(tab(3)+'<div>'+'\n')
ques = input('Enter the question: ')
ques = markdownToHtml(ques)
html.write(tab(4)+ques+'<br>'+'\n')
html.write(tab(4)+'<input type="text" placeholder="Enter your name">'+
'<br>'+'\n')
html.write(tab(4)+'<input type="submit" value="submit">'+'\n')
html.write(tab(3)+'</div>'+'\n')
html.write(tab(3)+'<hr>'+'\n')
html.write(tab(2)+'</form>'+'\n')
html.write(tab(1)+'</body>'+'\n')
html.write('</html>'+'\n')
|
3212ca8aa5c7397058b983219f00369ef0b2c454 | rashedrahat/py-programs | /list_comprehensions.py | 192 | 4.3125 | 4 | # a program of printing a new list where each and every list is a square value of the previous list.
list = [1, 2, 10, 12, 15]
new_li = []
new_li = [x ** 2 for x in list]
print(new_li)
|
9e7adbf400a1c68daddb7fac68da088603603162 | rlg2161/ProjectEuler | /problem17.py | 2,517 | 3.671875 | 4 | # If the numbers 1 to five are written out in words: one, two, three, four, five, then there
# are 3 + 3 + 5 + 4 + 4 = 19 letters used in total
# If all the unumbers from 1 to 1000 inclusive were written out in words, how many
# letters would be used?
def main():
total = 0
for x in range(1, 1001):
total = total + getLetterCount(x)
print "current total: " + str(total)
print "final total is: " + str(total)
def getLetterCount(number):
i = str(number)
j = len(str(number))
num_letters = 0
if (j == 4):
#print "thousands"
if (number == 1000):
num_letters = getThousandsPlace(i[0])
else:
num_letters = getThousandsPlace(i[0]) + getHundredsPlace(i[1]) + getTensPlace(i[2:4])
if (number % 100 != 0):
num_letters = num_letters + 3
elif (j == 3):
#print "hundreds"
if (number % 100 != 0):
num_letters = getHundredsPlace(i[0]) + getTensPlace(i[1:3])
num_letters = num_letters + 3
else:
num_letters = getHundredsPlace(i[0]) + 4
elif (j == 2):
#print "tens " + i
num_letters = getTensPlace(number)
elif (j == 1):
#print "ones"
num_letters = getOnesPlace(i[0])
#print (number, num_letters)
return num_letters
def getOnesPlace(number):
return numLetters(number)
def getTensPlace(number):
n = str(number)
num_letters = 0
if(number >19):
test_number = int(n[0])*10
num_letters = numLetters(test_number)
num_letters = num_letters + numLetters(int(n[1]))
#print (number, num_letters)
else:
num_letters = numLetters(number)
#print (number, num_letters)
return num_letters
def getHundredsPlace(number):
#print getOnesPlace(number)
return getOnesPlace(number) + 7
def getThousandsPlace(number):
return getOnesPlace(number) + 8
def numLetters(n):
number = int(n)
num_let = 0
if (number == 1 or number == 2 or number == 6 or number == 10):
num_let = 3
elif (number == 4 or number == 5 or number == 9):
num_let = 4
elif (number == 3 or number == 7 or number == 8 or number == 40 or number == 50 \
or number == 60):
num_let = 5
elif (number == 11 or number == 12 \
or number == 20 or number == 30 or number == 80 or number == 90):
num_let = 6
elif (number == 15 or number == 16 or number == 70):
num_let = 7
elif (number == 13 or number == 14 or number == 18 or number == 19):
num_let = 8
elif (number == 17):
num_let = 9
return num_let
if __name__ == "__main__":
main() |
6690670829471c7702d4a4e6e8ab7213106378a3 | pangyouzhen/data-structure | /unsolved/24 swapPairs.py | 497 | 3.671875 | 4 | # Definition for singly-linked list.
from base.linked_list.ListNode import ListNode
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
newHead = head.next
head.next = self.swapPairs(newHead.next)
newHead.next = head
return newHead
if __name__ == '__main__':
a = ListNode.from_list([1, 2, 3, 4, 5])
print(a)
sol = Solution()
print(sol.swapPairs(a))
|
b8da1f736a6db65efc3e72c5d74fec9004b4ea31 | lollipopnougat/AlgorithmLearning | /剑指/62圆圈中最后剩下的数字/yuanquanzhongzuihoushengxiadeshuzilcof.py | 699 | 3.546875 | 4 | #
''' 参考 https://blog.csdn.net/u011500062/article/details/72855826 约瑟夫环
约瑟夫问题是个著名的问题:N个人围成一圈,第一个人从1开始报数,报M的将被杀掉,
下一个人接着从1开始报。如此反复,最后剩下一个,求最后的胜利者。
公式
f(N, M) = (f(N − 1, M) + M) % N
f(N,M)表示,N个人报数,每报到M时杀掉那个人,最终胜利者的编号
f(N − 1, M)表示,N - 1个人报数,每报到 M 时杀掉那个人,最终胜利者的编号
'''
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
res = 0
for i in range(2, n + 1):
res = (res + m) % i
return res |
eb61cf959a025696dfb9324dbe99cb4936ce8ac9 | vtheenby/aoc2019 | /days/d01.py | 410 | 3.578125 | 4 | def fileToIntList(input):
ret = []
with open(input) as f:
for l in f.readlines():
l = int(l)
ret.append(l)
return (ret)
def calcFuel(n):
total = 0
total += int(n / 3 - 2)
return (total)
def fuelFuel(input):
total = 0
for n in input:
fuel = calcFuel(n)
while fuel >= 0:
total += fuel
fuel = calcFuel(fuel)
return (total)
input = fileToIntList("inputs/i01")
print (fuelFuel(input)) |
edb7377bfc063a1519bb9ea6009502c3fa3e11f0 | dbuedo/python-tests | /basics/003-primitive-types-numbers.py | 457 | 3.765625 | 4 | print "Numbers"
integer10 = 10
integerMinus9 = -9
print "integers ",integer10,integerMinus9,"=",integer10+integerMinus9
long999 = 999L
longVeryBig = 999999999999999L
print "longs ", long999, longVeryBig
floatingPoint1000 = 999.999999999999999
floatingPoint0 = 0.000000000000001
print "doubles ", floatingPoint1000, "+", floatingPoint0, "=", floatingPoint1000 + floatingPoint0
isFalse = False
isTrue = True
print "booleans " , isFalse, isTrue
|
9a5db38220504ead0b6b46b5d121383eab2ea5e9 | mrgomides/VemPython | /desafios/exe013.py | 289 | 3.59375 | 4 | # Projeto: VemPython/exe013
# Autor: rafael
# Data: 13/03/18 - 17:07
# Objetivo: TODO Faça um algoritimo que leia o salario e mostre seu novo salário, com 15% de aumento
sal = float(input('Informe o salario: R$ '))
print('O Salario com 15% de aumento é: R$ {}'.format(sal+(sal*0.15)))
|
a39d23f9094b0c3c4d506dd5e15693ada5e5c3df | AleksandrShkraba/hometask | /all_tasks/!!!TASK/python!/python/day2var1/task1.py | 262 | 3.6875 | 4 | n = int(input())
student_marks = {}
for i in range(n):
name, *args = input().split()
rezult_mark = sum(list(map(float, args))) / 3
a = {name: rezult_mark}
student_marks.update(a)
entered_name = input()
print('%.2f' % student_marks[entered_name])
|
9b3a5569fbb1aff321e7e50106caf7d69ecde389 | NickyThreeNames/RealPython1 | /Book1/Chapter5/5-3Review.py | 293 | 3.984375 | 4 | #Display result of find() on "a" in "AAA"
print("AAA".find("a"))
#Create string object and subset 2.0 via a float variable
s1 = "version 2.0"
s2 = 2.0
print(s1.find(str(s2)))
#Take user input and find certain letter (a) in that input
user_in = input("Type a word: ")
print(user_in.find("a")) |
196654f2e3cd55cea1af903a83b43961409ba1e8 | gutucristian/examples | /ctci/python/ch_1/1.4.py | 1,061 | 4.09375 | 4 | from collections import Counter
# Count char frequencies and return True if no more than one char freq is odd and False otherwise.
# A permutation may not have more than one type of char with odd freq.
def is_palindrome_permutation_1(a):
counter = Counter(a)
is_permutation = True
for count in counter.most_common():
if is_permutation == False:
return is_permutation
if count[1] % 2 == 1:
is_permutation = False
return True
def is_palindrome_permutation_2(a):
# use a bit vector to signal occurence of a char
bit_vector = [0] * 26
for char in a:
# get char position in bit vector using its ASCII encoding
index = ord(char) - ord('a')
# replace 1 with 0 to indicate that freq of this char (so far) is even
if bit_vector[index] == 1:
bit_vector[index] = 0
else:
bit_vector[index] = 1
# sum of bit_vector should be 1 if all but one char has a odd freq
bit_vector_sum = sum(bit_vector)
return bit_vector_sum == 1 or bit_vector_sum == 0
a = 'abas'
print(is_palindrome_permutation_2(a)) |
c155b695e3fe43ae1eb191e2f3192eb5e33f1cfd | Paul199199/THU-transfer-data | /SQL資料串接合併.py | 391 | 3.78125 | 4 | """
SQL資料串接合併
"""
import sqlite3
conn = sqlite3.connect('lcc.db')
sql = "create table if not exists customers(cid integer primary key autoincrement,name varchar(30),sex varchar(2))"
conn.execute(sql)
conn.commit()
sql = "create table if not exists orders(id integer primary key autoincrement,prices int, cid int)"
conn.execute(sql)
conn.commit()
conn.close() |
cc563dd012abeed760264f73f1db6fe0d4acfb48 | Jackobins/Hangman | /hangman.py | 2,336 | 4.125 | 4 | import random
# global variables needed for the game
dictionary = ["BANANA", "LACKADAISICAL", "IMPOSSIBLE", "GORILLA", "MONKEY"
"BURGER", "MILKSHAKE", "ONOMATOPOEIA", "EMERGENCY", "MIDNIGHT",
"ACACIA", "ALARM", "DRAINAGE", "SMARTPHONE", "COMMUNISM",
"SHREK", "VEHICLE"]
count = 7
secretWord = random.choice(dictionary)
userGuesses = []
# gets a guess letter from the player, if it is wrong, the player loses a life
def getUserGuess():
global count
guess = input("Enter a guess: ").upper()
while len(guess) != 1 or not guess.isalpha() or guess in userGuesses:
print("Your guess is not valid.")
guess = input("Enter a guess: ").upper()
if guess not in secretWord:
count -= 1
return guess
# displays the number of guesses the player has left
def displayLivesLeft():
global count
print("You have", count, "lives left.")
def displayUserGuesses():
print("\nYou have guessed:", userGuesses)
# displays the secret word with "_" for letters that have not been guessed
def displaySecretWord():
for letter in secretWord:
if letter in userGuesses:
print(letter, end=" ")
else:
print("_", end=" ")
# displays the state of the game after every guess
def displayGameBoard():
displaySecretWord()
displayUserGuesses()
displayLivesLeft()
def gameIsWon():
gameWon = True
for letter in secretWord:
if letter not in userGuesses:
gameWon = False
if gameWon:
return True
# the game is lost if the player loses all the lives without guessing the word
def gameIsLost():
if count <= 0:
return True
else:
return False
def gameIsOver():
return gameIsWon() or gameIsLost()
# displays the game over screen when the game is either won or lost
def displayGameOver():
if gameIsWon():
print("Congratulations, you won! The secret word was:", secretWord)
elif gameIsLost():
print("Oh no, you lost. The secret word was:", secretWord)
# plays a round of Hangman
def playOneRound():
while not gameIsOver():
displayGameBoard()
userGuesses.append(getUserGuess())
displayGameOver()
playOneRound()
|
f42c828c026d121eb0f716f60f8e06e44bb4b852 | rafaelperazzo/programacao-web | /moodledata/vpl_data/424/usersdata/323/90858/submittedfiles/divisores.py | 271 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import math
n= int(input('Digite o valor n: '))
a= int(input('Digite o valor a: '))
b= int(input('Digite o valor b: '))
x=1
cont=1
while cont<=n:
if x%a==0 or x%b==0:
print(x)
x=x+1
cont=cont+1
else:
x=x+1 |
ea3a79c88f6d2d7ace1baaa73de34cdf65fb6712 | LorenzoChavez/CodingBat-Exercises | /Logic-2/no_teen_sum.py | 492 | 3.90625 | 4 | # Given 3 int values, a b c, return their sum.
# However, if any of the values is a teen -- in the range 13..19 inclusive -- then that # value counts as 0, except 15 and 16 do not count as a teens.
# Write a separate helper "def fix_teen(n):"that takes in an int value and returns that # value fixed for the teen rule.
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
def fix_teen(n):
if n in range(13,15) or n in range(17,20):
return 0
else:
return n
|
b2fcb23e8cb376aede1b049a0431cf5157f79579 | roxcoldiron/simple_haunted_house | /hauntedhouse.py | 1,874 | 4.28125 | 4 | welcome = """
Welcome to the haunted house.
Prepare to be amazed or die.
The frights might turn your hair white.
And survivor takes the prize.
"""
print(welcome)
print("Choose which room to explore:
print("1. living room")
print("2. study room")
room = input("> ")
if room == "1" or room == "living room":
print("You see the ghost of the owner of the house.")
print("What do you do next?")
print("1. Run away.")
print("2. Stay and chat.")
owner_ghost = input("> ")
if owner_ghost == "1":
print("You don't win the prize.")
elif owner_ghost == "2":
print("You're very brave and win the prize.")
else:
print("You must make a choice.") #need a way to loop back until a choice is made
if room == "2" or room == "study room":
print("You meet the ghost of the family's child.")
print("What do you do next?")
print("1. Run away.")
print("2. Stay and play with the kid ghost.")
print("3. Move onto the living room.")
kid_ghost = input("> ")
if kid_ghost == "1":
print("You lost this game. No prize.")
elif kid_ghost == "2":
print("Choose a game to play:")
print("1. Hide and seek")
print("2. Checkers")
game_to_play = input("> ")
if game_to_play == "1":
print("You'll never get out of this house now!")
print("Game over!")
if game_to_play == "2":
print("This is the never-ending game of checkers! Muahaha!")
print("Game over!")
else:
print("You must now face the owner of the house!")
print("What do you do?")
print("1. Run away.")
print("2. Pour yourself a scotch for a staring contest with a ghost.")
print("3. Say a prayer.")
last_choice = input("> ")
if last_choice == "1":
print("You lose this game.")
elif last_choice == "2":
print("Congrats! You win!")
else:
print("Sorry, pal, that ain't gonna work here.")
|
19bfc2862a17cc345b9177662742a5b27ab946ea | Thonipho/Python | /PythonPostgreSQL Course 2.0/Working with dates and times/datetime_module.py | 810 | 4.25 | 4 | #Datetime object
import datetime
today = datetime.datetime(year=2019, month=12, day=23, hour=11, minute=49, second=30)
tomorrow = datetime.datetime(year=2019, month=12, day=24, hour=11, minute=49, second=30)
print(today > tomorrow) # False
#getting and displaying todays date and time
import datetime
today = datetime.datetime.now()
print(today.strftime("%Y-%m-%d"))
# 2019-12-23
print(today.strftime("%H:%M"))
# 11:54
#converting string to datetime
import datetime
user_date = input("Enter today's date: ")
# Assume they entered 23-12-2019
today = datetime.datetime.strptime(user_date, "%d-%m-%Y")
print(today) # 2019-12-23 00:00:00
#timestamps
import datetime
today = datetime.datetime.now()
print(today.timestamp()) # 1577104357.558527
import time
print(time.time()) # 1577104492.7515678 |
aaa004b7cc338168c6e11a3a274f1caee530f3b7 | Silvalhd/Aulas-Python | /Mundo 1/ex15.py | 155 | 3.65625 | 4 | d = int(input('Quantos dias alugados ?'))
km = float(input('Quantos Km rodados ?'))
s = (60*d) + 0.15*km
print('O total a pagar é de R${:.2f}'.format(s)) |
12d28ad3d33a175fcf9a4d4a33e2a46cb77fd983 | rghf/Twoc_Problem | /Day 2/2.py | 173 | 4.125 | 4 | N = int(input("Enter the value of N: "))
a = 0
b = 1
print("Fibonacci series are:", N)
for i in range(N):
print(a, end = " ")
c = a + b
a = b
b = c
|
38034d9332b3e458e639e36ca4d4d8c75eb79fa2 | BabaLangur/Employee-Management-System-using-Python-and-MySQL | /Login.py | 2,022 | 3.65625 | 4 | from tkinter import*
from tkinter import messagebox
class login:
def __init__(self,root):
self.root=root
self.root.title("Employee Management System")
self.root.geometry("515x360+600+100")
F1=Frame(self.root,bg="light blue")
F1.place(x=0,y=0,height=360)
self.user=StringVar()
self.password=StringVar()
title=Label(F1,text="Login System",font=("times new roman",31,"bold"),fg="black",bg="light blue").grid(row=0,columnspan=2,pady=20)
lblusername=Label(F1,text="Username",font=("times new roman",20,"bold"),fg="black",bg="light blue").grid(row=1,column=0,pady=10,padx=10)
txtuer=Entry(F1,textvariable=self.user,width=25,font=("arial", 15," bold")).grid(row=1,column=1,padx=10,pady=10)
lblpass=Label(F1,text="Password",font=("times new roman",20,"bold"),fg="black",bg="light blue").grid(row=2,column=0,pady=10,padx=10)
txtpass=Entry(F1,show="*",textvariable=self.password,width=25,font="arial 15 bold").grid(row=2,column=1,padx=10,pady=10)
btnlogin=Button(F1,text="Login",font=("times new roman", 15, "bold" ),bd=7,width=10,command=self.log_fun).place(x=10,y=270)
btnreser=Button(F1,text="Reset",font=("times new roman", 15, "bold" ),bd=7,width=10,command=self.reset).place(x=169,y=270)
btnexit=Button(F1,text="Exit",font=("times new roman", 15, "bold" ),bd=7,width=10,command=self.exit_fun).place(x=329,y=270)
def log_fun(self):
if self.user.get()=="softwarica" and self.password.get()=="coventry":
self.root.destroy()
import first
first.Employee()
else:
messagebox.showerror("Error","invalid username or password")
def reset(self):
self.user.set("")
self.password.set("")
def exit_fun(self):
option=messagebox.askyesno("Exit","Do you really want to exit?")
if option:
self.root.destroy()
else:
return
root=Tk()
ob=login(root)
root.mainloop() |
96e29d3997d64f7454e66132215cc30138aaef07 | Karina143/qwer | /z19_51.py | 128 | 3.59375 | 4 | a = int(input())
b = a // 10 % 10
sum1 = a// 100 + b
sum2 = b+ a % 10
print(str(max(sum1, sum2)) + str(min(sum1, sum2)))
|
f7d4a56126cba57ace86ec4b649ad4bef75a5de0 | wangsailing1/demo | /paixusuanfa/插入排序.py | 493 | 3.78125 | 4 | # encoding:utf8
def insert_sort(L):
for i in range(len(L)):
for a in range(i):
# if L[i] > L[a]:
if L[i] < L[a]:
L.insert(a, L.pop(i))
break
return L
# 升序, 第一个元素默认有序, 然后跟索引小于他的所有值进行比较, 谁大于他他就去谁的前面
# 降序, 取出一个遍历的元素, 我大余谁, 我就去谁前面
if __name__ == '__main__':
print(insert_sort([5,4,6,7,3,2,8,1]))
|
327b5783e10a364b73f25e6a1eedd3ff0b0a0fb8 | Ing-Josef-Klotzner/python | /_primes_generator.py | 692 | 4.1875 | 4 | def is_prime (n):
#return factorial (n - 1) % n == n - 1
if n == 2 or n == 3: return True
elif n < 2 or n % 2 == 0 or n % 3 == 0: return False
elif n < 9: return True
r = int (n ** 0.5)
# since all primes > 3 are of the form 6n ± 1 start with f=5
# (which is prime) and test f, f+2 for being prime, then loop by 6.
f = 5
while f <= r:
#print('\t', f)
if n % f == 0: return False
if n % (f + 2) == 0: return False
f += 6
return True
def primes (): # generator
for prime in 2, 3:
yield prime
f = 5
while f:
if is_prime (f): yield f
if is_prime (f + 2): yield f + 2
f += 6
|
a0d0c8e6f2a86c1763db341cf9af99d462a7a33f | Kirankumar422/HelloWorld | /Challenge_forloop.py | 1,148 | 4.28125 | 4 | # # Write a program to print out the capitals letters in the string
#
# quote = """
# Alright, but apart from the Sanitation, the Medicine, Education, Wine, Public Order, Irrigation, Roads,
# the Fresh-Water System, and Public Health, what have the Romans ever done for us ?"""
#
# for char in quote:
# if char in 'ASMEWPOIRFHR':
# print(char)
#
# # Write a program to print out all the numbers from 0 to 100 that are divisible by 7
#
# for i in range(0, 101):
# if (i % 7 == 0):
# print(i)
# Print numbers from 0 to 99 with added 7 and need to break code once the values reaches to remainder 0 with divisible by 11
# for i in range(0, 100, 7):
# print(i)
# if i > 0 and i % 11 == 0:
# break
# Write a program to print out all the numbers from 0 to 20 that aren't divisible by 3 or 5.
# Zero is considered divisible by everything(Zero should not be in your output)
# The aim is to use the continue statement, but it's also possible to do this without continue.
for i in range(1, 21):
# print(i)
if i % 3 == 0 or i % 5 == 0:
continue
#if i % 5 == 0:
# continue
print(i)
|
d06ddc880a88de9c5369e01c38cbc680901db20c | Rafsun-Jany/HackerRank | /Python 3/Day_of_the_Programmer[HackerRank].py | 838 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the dayOfProgrammer function below.
def dayOfProgrammer(year):
if year < 1918:
if year % 4 == 0:
return ('{0}.{1}.{2}'.format('12','09',year))
else:
return ('{0}.{1}.{2}'.format('13','09',year))
elif year == 1918:
return ('{0}.{1}.{2}'.format('26','09',year))
else:
if year % 400 == 0 or (year %4 ==0 and year % 100 !=0):
return ('{0}.{1}.{2}'.format('12','09',year))
else:
return ('{0}.{1}.{2}'.format('13','09',year))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
year = int(input().strip())
result = dayOfProgrammer(year)
fptr.write(result + '\n')
fptr.close()
|
071182fe38e3de52a97fa90a94f79eaed02db01b | pit1s/TrainingGround | /Lessons/01_Intro/01_hello_world.py | 1,528 | 4.53125 | 5 | # Simple print statement to console:
print('Hello World!')
# There are other ways output data with Python, but
# we'll focus on print() for now.
# Same concept, but letting the user choose what to say 'Hello' to:
thing = input('What should we say Hello to: ')
print('Hello ' + thing)
# Notice the space after 'Hello'. This is called concatenation,
# we're adding one string 'Hello ' with whatever 'thing' is,
# which is defined by whatever the user inputs
# We can also put the two together, without assigning a variable
print('My favorite food is ' + input('What is your favorite food? '))
# Notice that when this line is run, it will perform the input method first,
# then use the resulting string to finish the sentence.
# You can use concatenation to create more complex strings
name = input('What is your name? ')
quest = input('What is your quest? ')
color = input('What is your favorite color? ')
print('Your name is ' + name + '. Your quest is ' + quest + '. Your favorite color is ' + color +'.')
# You can use special characters to insert newlines (\n) or tabs (\t)
print('Your name is:\t' + name + '.\nYour quest is:\t' + quest + '.\nYour favorite color is:\t' + color +'.')
# You can also use \ to break up statements into multiple lines
print('Your name is:\t' + name \
+ '.\nYour quest is:\t' + quest \
+ '.\nYour favorite color is:\t' + color +'.')
# Note that using the backslash does not affect the strings themselves
print('This' + \
'is' + \
'one' + \
'word')
|
668074f6906e8912f777a9522e19b4769a866f94 | miyamotok0105/python_sample | /tutorial/descriptor/004.py | 401 | 3.546875 | 4 | def scale(name):
def getter(instance):
return instance.__dict__[name]
def setter(instance, value):
if value < 0:
raise ValueError('value must be > 0')
instance.__dict__[name] = value
return property(getter, setter)
class Size:
width = scale('width')
height = scale('height')
s = Size()
s.width = 300
s.height = 400
print(s.width, s.height) |
195654b099446aa0b9a61648a25afcc6914c71b1 | niemenX/HRPython | /CompareTriplets/solution.py | 544 | 3.6875 | 4 | #!/bin/python3
import sys
def compare(a,b):
return 1 if a > b else 0
def solve(a0, a1, a2, b0, b1, b2):
# Complete this function
res = [0,0]
res[0] = compare(a0, b0)+compare(a1, b1) + compare(a2, b2)
res[1] = compare(b0, a0)+compare(b1, a1) + compare(b2, a2)
return res;
a0, a1, a2 = input().strip().split(' ')
a0, a1, a2 = [int(a0), int(a1), int(a2)]
b0, b1, b2 = input().strip().split(' ')
b0, b1, b2 = [int(b0), int(b1), int(b2)]
result = solve(a0, a1, a2, b0, b1, b2)
print (" ".join(map(str, result))) |
5aa2c1f5f720a2bab9f027c5ca7bb4b96e0bb18c | Muckler/python-exercises-feb | /february_exercises/python_part3_exercises/turtle1_hexagon.py | 333 | 3.59375 | 4 | from turtle import *
def hex():
# move into position
up()
forward(50)
left(90)
forward(50)
left(90)
down()
# draw the hexagon
forward(100)
left(60)
forward(100)
left(60)
forward(100)
left(60)
forward(100)
left(60)
forward(100)
left(60)
forward(100)
if __name__ == "__main__":
hex()
mainloop() |
6a360a45e0b745bfcfdd7aa8283947f01789b71f | LilySu/Python_Practice | /Graph_Adjacency/Graph_Notes_Pluralsight_August_17.py | 3,125 | 3.703125 | 4 | import abc
import numpy as np
class Graph(abc.ABC):
def __init__(self, numVertices, directed = False): # assuming by default graph is undirected
self.numVertices = numVertices
self.directed = directed
@abc.abstractmethod # needs to be implemented by any class and derives from class Graph(abc.ABC)
def add_edge(self, v1, v2, weight):
pass
@abc.abstractmethod
def get_adjacent_vertices(self, v): # retrieves any adjacent vertices
pass
@abc.abstractmethod
def get_indegree(self, v): # gets number of edges inserted in a vertex
pass
@abc.abstractmethod
def get_edge_weight(self, v1, v2): # gets weights of edges
pass
@abc.abstractmethod
def display(self):
pass
class AdjacencyMatrixGraph(Graph):
def __init__(self, numVertices, directed=False):
super(AdjacencyMatrixGraph, self).__init__(numVertices, directed)
self.matrix = np.zeros((numVertices, numVertices)) # initalize all items in matrix to 0
def add_edge(self, v1, v2, weight=1):
# checks if numbers passed in are valid
if v1 >= self.numVertices or v2 >= self.numVertices or v1 < 0 or v2 < 0:
raise ValueError("Vertices %d and %d are out of bounds" % (v1, v2))
if weight < 1:
raise ValueError("An edge cannot have weight < 1")
self.matrix[v1][v2] == weight # if an edge exists, entry is equal to weight
if self.directed == False:
self.matrix[v2][v1] = weight # allows the path in the other direction is there too
def get_adjacent_vertices(self, v):
if v < 0 or v >= self.numVertices:
raise ValueError("Cannot access vertex %d" % v)
adjacent_vertices = []
for i in range(self.numVertices): # iterate through all nodes in adjacency matrix
if self.matrix[v][i] > 0: # if there is a non-zero in any cell then that entry is adjacent
adjacent_vertices.append(i) # append adjacent vertices to list of adjacent vertices
return adjacent_vertices
def get_indegree(self, v):
if v < 0 or v >= self.numVertices:
raise ValueError("Cannot access vertex %d" % v)
indegree = 0
for i in range(self.numVertices):
if self.matrix[i][v] > 0: # if incoming edge is greater than zero, increment indegree
indegree = indegree + 1
return indegree
def get_edge_weight(self, v1, v2):
return self.matrix[v1][v2]
def display(self):
for i in range(self.numVertices):
for v in self.get_adjacent_vertices(i):
print(i, "-->", v)
if __name__ == '__main__':
g = AdjacencyMatrixGraph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(2, 3)
for i in range(4):
print("Adjacent to:", i, g.get_adjacent_vertices(i))
for i in range(4):
print("Indegree ", i, g.get_indegree(i))
for i in range(4):
for j in g.get_adjacent_vertices(i):
print("Edge weight:", i, " ", j, "weight: ", g.get_edge_weight(i, j))
g.display()
|
67c75835c648b134e933f7025fcc9a6903d42847 | Tracyee/Leetcode-Games-python | /84. Largest Rectangle in Histogram/trick1.py | 776 | 3.515625 | 4 | class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
'''
For each bar i, we look for the first bar left_i on the left that is
lower than bar[i] and the first bar right_i on the right that is lower
than bar[i]. Then the largest size determined by bar[i]
(bar[i] as the peak) is height[i] * (right_i - left_i - 1)
'''
res = 0
n = len(heights)
for i in range(n):
left_i = i
right_i = i
while left_i >= 0 and heights[left_i] >= heights[i]:
left_i -= 1
while right_i < n and heights[right_i] >= heights[i]:
right_i += 1
res = max(res, (right_i - left_i - 1) * heights[i])
return res
|
66ec43e4118c46dd60bb353c0925a15dd6d17b17 | dabini/lecture | /알고리즘강의/02_13_string.py | 1,673 | 3.5625 | 4 | # #문자열뒤집기
# #내 CODE
# Data = list(input())
# new = ""
# for i in range(len(Data)):
# new += Data[-(i+1)]
# print(new)
#
# #연습문제1
# s = "Reverse this string"
# s = s[::-1]
# print(s)
#연습문제
#atoi
#char to int
# '1''2''3' -=> 123
# lst = ['1', '2', '3']
# res = 0
# for i in range(len(lst)):
# k = ord(lst[i]) - 48
# res += k * 10**(len(lst) - i -1)
# print(res)
#
#
# #itoa
# #int to char
# i = 123
# res = ''
# k = 0
# check = i
#
# while check > 0 :
# check = check // (10**k)
# k += 1
# # print(k) #k=3
#
# for n in range(k):
# a = i % (10** k-n)
# res += ascii(a)
# print(res)
# print(type(res))
#패턴매칭
# p = 'is'
# t = 'This is a book~!'
# M = len(p)
# N = len(t)
#
# def BruteForce(p, t):
# i = 0
# j = 0
# while j < M and i< N:
# if t[i] != p[j]:
# i = i - j
# j = -1
# i = i + 1
# j = j + 1
# if j == M:
# return i - M
# else:
# return -1
# print(BruteForce(p, t))
# 브루트
# N, K = map(int, input().split())
# field = [[0]*(N+1) for _ in range(N+1)]
# visited = [0] *(N+1)
# res = 0
#
# def GetSome(here):
# global res, ans
# if here == 7:
# if res < ans :
# ans=res
# return
#
# for now in range(N+1):
# if field[here][now] and not visited[now]:
# res += field[here][now]
# visited[now] = 1
# GetSome(now)
# visited[now] = 0
# res -= field[here][now]
#
# for k in range(K):
# start, end, cost = map(int, input().split())
# field[start][end] = cost
# ans = 987654321
# GetSome(1)
# print(ans) |
7566d536cea6eaafffecf1ee414f720a8311d4cc | vivaana/PythonTrg | /lesson1/class 9/set.py | 406 | 4.25 | 4 | # # animals = {"pigs","goats","duck","cow"}
# # for animal in animals:
# # print(animal)
# #
# # print("####################################################################")
# # #create a set of friends (five), print them each
# #
# # friends = {"1","2","3","4","5"}
# # for friend in friends:
# # print(friend)
#
# #
# # friends.remove("5")
# # for friends2 in friends:
# # print(friends2)
#
|
730b59976cc46a904ef9eb491b9165b8ef6626cd | lubogeshev/mm_logo | /mm_logo.py | 828 | 3.859375 | 4 | def draw_mm(n: int):
dash = '-'
star = '*'
d_side_cnt = n
d_mid_cnt = n
s_side_cnt = n
s_mid_cnt = n
middle = (n + 1) // 2
for i in range(n + 1):
if i < middle:
print((dash * d_side_cnt + star * s_mid_cnt + dash * d_mid_cnt
+ star * s_mid_cnt + dash * d_side_cnt) * 2)
d_side_cnt -= 1
if i < middle - 1:
d_mid_cnt -= 2
s_mid_cnt += 2
else:
print((dash * d_side_cnt + star * s_side_cnt + dash * d_mid_cnt
+ star * s_mid_cnt + dash * d_mid_cnt + star * s_side_cnt + dash * d_side_cnt) * 2)
d_side_cnt -= 1
d_mid_cnt += 2
s_mid_cnt -= 2
def main():
n = int(input())
draw_mm(n)
if __name__ == '__main__':
main()
|
3a7462d382d692c1cbfb086a5c9050c1313a739c | anansan969/temperature | /temperature.py | 92 | 3.75 | 4 | C = input('what is the temperature?(Celsius)')
C = float(C)
print('Fahreheit is',C*9/5+32)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.